This commit is contained in:
annampak 2018-01-31 17:46:44 +02:00
commit 1fbeaf073e
27 changed files with 689 additions and 124 deletions

View File

@ -18,10 +18,10 @@ import java.util.List;
public class EuDatApplication extends SpringBootServletInitializer { public class EuDatApplication extends SpringBootServletInitializer {
private static final Logger logger = LoggerFactory.getLogger(EuDatApplication.class); private static final Logger logger = LoggerFactory.getLogger(EuDatApplication.class);
/*@Override @Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(EuDatApplication.class); return builder.sources(EuDatApplication.class);
}*/ }
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(EuDatApplication.class, args); SpringApplication.run(EuDatApplication.class, args);

View File

@ -5,7 +5,10 @@ import java.util.UUID;
import eu.eudat.dao.entities.*; import eu.eudat.dao.entities.*;
import eu.eudat.managers.DashBoardManager; import eu.eudat.managers.DashBoardManager;
import eu.eudat.models.dashboard.DashBoardStatistics; 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.services.ApiContext;
import eu.eudat.types.Authorities;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
@ -23,9 +26,11 @@ import eu.eudat.models.admin.composite.DatasetProfile;
import javax.transaction.Transactional; import javax.transaction.Transactional;
import javax.validation.Valid; import javax.validation.Valid;
import static eu.eudat.types.Authorities.ADMIN;
@RestController @RestController
@CrossOrigin @CrossOrigin
public class Admin extends BaseController{ public class Admin extends BaseController {
@Autowired @Autowired
public Admin(ApiContext apiContext) { public Admin(ApiContext apiContext) {
@ -33,22 +38,22 @@ public class Admin extends BaseController{
} }
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, value = { "/admin/addDmp" },consumes = "application/json", produces="application/json") @RequestMapping(method = RequestMethod.POST, value = {"/admin/addDmp"}, consumes = "application/json", produces = "application/json")
public ResponseEntity<Object> addDmp(@Valid @RequestBody DatasetProfile profile){ public ResponseEntity<Object> addDmp(@Valid @RequestBody DatasetProfile profile, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) {
try{ try {
eu.eudat.entities.DatasetProfile modelDefinition = AdminManager.generateViewStyleDefinition(profile); eu.eudat.entities.DatasetProfile modelDefinition = AdminManager.generateViewStyleDefinition(profile);
this.getApiContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(modelDefinition); this.getApiContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(modelDefinition);
return ResponseEntity.status(HttpStatus.OK).body(modelDefinition.getId()); return ResponseEntity.status(HttpStatus.OK).body(modelDefinition.getId());
}catch(Exception ex){ } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"reason\":\""+ex.getMessage()+"\"}"); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"reason\":\"" + ex.getMessage() + "\"}");
} }
} }
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, value = { "/admin/addDmp/{id}" },consumes = "application/json", produces="application/json") @RequestMapping(method = RequestMethod.POST, value = {"/admin/addDmp/{id}"}, consumes = "application/json", produces = "application/json")
public ResponseEntity<Object> updateDmp(@PathVariable String id,@RequestBody DatasetProfile profile){ public ResponseEntity<Object> updateDmp(@PathVariable String id, @RequestBody DatasetProfile profile, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) {
try{ try {
eu.eudat.entities.DatasetProfile modelDefinition = AdminManager.generateViewStyleDefinition(profile); eu.eudat.entities.DatasetProfile modelDefinition = AdminManager.generateViewStyleDefinition(profile);
eu.eudat.entities.DatasetProfile datasetprofile = this.getApiContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id)); eu.eudat.entities.DatasetProfile datasetprofile = this.getApiContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
@ -56,22 +61,22 @@ public class Admin extends BaseController{
this.getApiContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(datasetprofile); this.getApiContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(datasetprofile);
return ResponseEntity.status(HttpStatus.OK).body(null); return ResponseEntity.status(HttpStatus.OK).body(null);
}catch(Exception ex){ } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"reason\":\""+ex.getMessage()+"\"}"); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"reason\":\"" + ex.getMessage() + "\"}");
} }
} }
@RequestMapping(method = RequestMethod.GET, value = { "/admin/get/{id}" }, produces="application/json") @RequestMapping(method = RequestMethod.GET, value = {"/admin/get/{id}"}, produces = "application/json")
public ResponseEntity<Object> get(@PathVariable String id){ public ResponseEntity<Object> get(@PathVariable String id, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) {
try{ try {
eu.eudat.entities.DatasetProfile profile = this.getApiContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id)); eu.eudat.entities.DatasetProfile profile = this.getApiContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
eu.eudat.models.admin.composite.DatasetProfile datasetprofile = AdminManager.generateDatasetProfileModel(profile); eu.eudat.models.admin.composite.DatasetProfile datasetprofile = AdminManager.generateDatasetProfileModel(profile);
datasetprofile.setLabel(profile.getLabel()); datasetprofile.setLabel(profile.getLabel());
return ResponseEntity.status(HttpStatus.OK).body(datasetprofile); return ResponseEntity.status(HttpStatus.OK).body(datasetprofile);
}catch(Exception ex){ } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"reason\":\""+ex.getMessage()+"\"}"); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"reason\":\"" + ex.getMessage() + "\"}");
} }
} }
} }

View File

@ -1,6 +1,7 @@
package eu.eudat.controllers; package eu.eudat.controllers;
import eu.eudat.exceptions.UnauthorisedException; import eu.eudat.exceptions.UnauthorisedException;
import eu.eudat.managers.UserManager;
import eu.eudat.models.login.Credentials; import eu.eudat.models.login.Credentials;
import eu.eudat.models.helpers.responses.ResponseItem; import eu.eudat.models.helpers.responses.ResponseItem;
import eu.eudat.models.login.LoginInfo; import eu.eudat.models.login.LoginInfo;
@ -39,21 +40,36 @@ public class Login {
} }
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, value = { "/externallogin" }, consumes = "application/json", produces="application/json") @RequestMapping(method = RequestMethod.POST, value = {"/externallogin"}, consumes = "application/json", produces = "application/json")
public @ResponseBody ResponseEntity<ResponseItem<Principal>> googleLogin(@RequestBody LoginInfo credentials) { public @ResponseBody
ResponseEntity<ResponseItem<Principal>> externallogin(@RequestBody LoginInfo credentials) {
try { try {
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().payload(customAuthenticationProvider.authenticate(credentials)).status(ApiMessageCode.SUCCESS_MESSAGE)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().payload(customAuthenticationProvider.authenticate(credentials)).status(ApiMessageCode.SUCCESS_MESSAGE));
}catch (UnauthorisedException ex){ } catch (UnauthorisedException ex) {
throw ex; throw ex;
} } catch (Exception ex) {
catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<Principal>().status(ApiMessageCode.DEFAULT_ERROR_MESSAGE).message(ex.getMessage())); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<Principal>().status(ApiMessageCode.DEFAULT_ERROR_MESSAGE).message(ex.getMessage()));
} }
} }
@RequestMapping(method = RequestMethod.GET, value = { "/twitterRequestToken" }, produces="application/json") @Transactional
public @ResponseBody ResponseEntity<ResponseItem<OAuthToken>> twitterRequestToken() { @RequestMapping(method = RequestMethod.POST, value = {"/nativelogin"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Principal>> nativelogin(@RequestBody Credentials credentials) {
try {
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().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<Principal>().status(ApiMessageCode.DEFAULT_ERROR_MESSAGE).message(ex.getMessage()));
}
}
@RequestMapping(method = RequestMethod.GET, value = {"/twitterRequestToken"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<OAuthToken>> twitterRequestToken() {
try { try {
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<OAuthToken>().payload(this.twitterTokenValidator.getRequestToken()).status(ApiMessageCode.NO_MESSAGE)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<OAuthToken>().payload(this.twitterTokenValidator.getRequestToken()).status(ApiMessageCode.NO_MESSAGE));
} catch (Exception ex) { } catch (Exception ex) {
@ -62,8 +78,9 @@ public class Login {
} }
} }
@RequestMapping(method = RequestMethod.POST, value = { "/me" }, consumes = "application/json", produces="application/json") @RequestMapping(method = RequestMethod.POST, value = {"/me"}, consumes = "application/json", produces = "application/json")
public @ResponseBody ResponseEntity<ResponseItem<Principal>> authMe(Principal principal) { public @ResponseBody
ResponseEntity<ResponseItem<Principal>> authMe(Principal principal) {
try { try {
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().payload(this.authenticationService.Touch(principal.getToken())).status(ApiMessageCode.NO_MESSAGE)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().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") @RequestMapping(method = RequestMethod.POST, value = {"/logout"}, consumes = "application/json", produces = "application/json")
public @ResponseBody ResponseEntity<ResponseItem<Principal>> logout(Principal principal) { public @ResponseBody
ResponseEntity<ResponseItem<Principal>> logout(Principal principal) {
try { try {
this.authenticationService.Logout(principal.getToken()); this.authenticationService.Logout(principal.getToken());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().status(ApiMessageCode.NO_MESSAGE)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().status(ApiMessageCode.NO_MESSAGE));

View File

@ -11,6 +11,7 @@ import eu.eudat.models.helpers.responses.*;
import eu.eudat.models.project.ProjectCriteriaRequest; import eu.eudat.models.project.ProjectCriteriaRequest;
import eu.eudat.models.project.ProjectListingModel; import eu.eudat.models.project.ProjectListingModel;
import eu.eudat.models.security.Principal; import eu.eudat.models.security.Principal;
import eu.eudat.security.claims.ClaimedAuthorities;
import eu.eudat.services.ApiContext; import eu.eudat.services.ApiContext;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import org.springframework.beans.factory.annotation.Autowired; 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.HugeResultSet;
import eu.eudat.proxy.config.exceptions.NoURLFound; import eu.eudat.proxy.config.exceptions.NoURLFound;
import static eu.eudat.types.Authorities.ADMIN;
import static eu.eudat.types.Authorities.USER;
@RestController @RestController
@CrossOrigin @CrossOrigin
@ -44,7 +48,8 @@ public class Projects extends BaseController {
} }
@RequestMapping(method = RequestMethod.POST, value = {"/projects/getPaged"}, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/projects/getPaged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody ResponseEntity<ResponseItem<DataTableData<ProjectListingModel>>> getPaged(@Valid @RequestBody ProjectTableRequest projectTableRequest, Principal principal) { public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<ProjectListingModel>>> getPaged(@Valid @RequestBody ProjectTableRequest projectTableRequest, Principal principal) {
try { try {
DataTableData<eu.eudat.models.project.ProjectListingModel> dataTable = new ProjectManager().getPaged(this.getApiContext().getDatabaseRepository().getProjectDao(), projectTableRequest); DataTableData<eu.eudat.models.project.ProjectListingModel> dataTable = new ProjectManager().getPaged(this.getApiContext().getDatabaseRepository().getProjectDao(), projectTableRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<eu.eudat.models.project.ProjectListingModel>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<eu.eudat.models.project.ProjectListingModel>>().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") @RequestMapping(method = RequestMethod.GET, value = {"/projects/getSingle/{id}"}, produces = "application/json")
public @ResponseBody ResponseEntity<ResponseItem<eu.eudat.models.project.Project>> getSingle(@PathVariable String id, Principal principal) { public @ResponseBody
ResponseEntity<ResponseItem<eu.eudat.models.project.Project>> getSingle(@PathVariable String id, Principal principal) {
try { try {
eu.eudat.models.project.Project project = new ProjectManager().getSingle(this.getApiContext().getDatabaseRepository().getProjectDao(), id); eu.eudat.models.project.Project project = new ProjectManager().getSingle(this.getApiContext().getDatabaseRepository().getProjectDao(), id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.models.project.Project>().payload(project).status(ApiMessageCode.NO_MESSAGE)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.models.project.Project>().payload(project).status(ApiMessageCode.NO_MESSAGE));
@ -69,7 +75,8 @@ public class Projects extends BaseController {
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/projects/createOrUpdate"}, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/projects/createOrUpdate"}, consumes = "application/json", produces = "application/json")
public @ResponseBody ResponseEntity<ResponseItem<Project>> addProject(@Valid @RequestBody eu.eudat.models.project.Project project, Principal principal) { public @ResponseBody
ResponseEntity<ResponseItem<Project>> addProject(@Valid @RequestBody eu.eudat.models.project.Project project, Principal principal) {
try { try {
ProjectManager.createOrUpdate(this.getApiContext().getDatabaseRepository().getProjectDao(), this.getApiContext().getDatabaseRepository().getUserInfoDao(), project, principal); ProjectManager.createOrUpdate(this.getApiContext().getDatabaseRepository().getProjectDao(), this.getApiContext().getDatabaseRepository().getUserInfoDao(), project, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.entities.Project>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created")); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.entities.Project>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created"));
@ -81,7 +88,8 @@ public class Projects extends BaseController {
@Transactional @Transactional
@RequestMapping(method = RequestMethod.DELETE, value = {"/projects/inactivate/{id}"}, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.DELETE, value = {"/projects/inactivate/{id}"}, consumes = "application/json", produces = "application/json")
public @ResponseBody ResponseEntity<ResponseItem<Project>> inactivate(@PathVariable String id, Principal principal) { public @ResponseBody
ResponseEntity<ResponseItem<Project>> inactivate(@PathVariable String id, Principal principal) {
try { try {
Project project = new ProjectManager().inactivate(this.getApiContext().getDatabaseRepository().getProjectDao(), id); Project project = new ProjectManager().inactivate(this.getApiContext().getDatabaseRepository().getProjectDao(), id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.entities.Project>().status(ApiMessageCode.SUCCESS_MESSAGE)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.entities.Project>().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") @RequestMapping(method = RequestMethod.POST, value = {"/projects/getWithExternal"}, consumes = "application/json", produces = "application/json")
public @ResponseBody ResponseEntity<ResponseItem<List<eu.eudat.models.project.Project>>> getWithExternal(@RequestBody ProjectCriteriaRequest projectCriteria, Principal principal) { public @ResponseBody
ResponseEntity<ResponseItem<List<eu.eudat.models.project.Project>>> getWithExternal(@RequestBody ProjectCriteriaRequest projectCriteria, Principal principal) {
try { try {
List<eu.eudat.models.project.Project> dataTable = new ProjectManager().getCriteriaWithExternal(this.getApiContext().getDatabaseRepository().getProjectDao(), projectCriteria, this.getApiContext().getRemoteFetcher()); List<eu.eudat.models.project.Project> dataTable = new ProjectManager().getCriteriaWithExternal(this.getApiContext().getDatabaseRepository().getProjectDao(), projectCriteria, this.getApiContext().getRemoteFetcher());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<eu.eudat.models.project.Project>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<eu.eudat.models.project.Project>>().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") @RequestMapping(method = RequestMethod.POST, value = {"/projects/get"}, consumes = "application/json", produces = "application/json")
public @ResponseBody ResponseEntity<ResponseItem<List<eu.eudat.models.project.Project>>> get(@RequestBody ProjectCriteriaRequest projectCriteria, Principal principal) { public @ResponseBody
ResponseEntity<ResponseItem<List<eu.eudat.models.project.Project>>> get(@RequestBody ProjectCriteriaRequest projectCriteria, Principal principal) {
try { try {
List<eu.eudat.models.project.Project> dataTable = new ProjectManager().getCriteria(this.getApiContext().getDatabaseRepository().getProjectDao(), projectCriteria, this.getApiContext().getRemoteFetcher()); List<eu.eudat.models.project.Project> dataTable = new ProjectManager().getCriteria(this.getApiContext().getDatabaseRepository().getProjectDao(), projectCriteria, this.getApiContext().getRemoteFetcher());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<eu.eudat.models.project.Project>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<eu.eudat.models.project.Project>>().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") @RequestMapping(method = RequestMethod.GET, value = {"/external/projects"}, produces = "application/json")
public @ResponseBody ResponseEntity<ResponseItem<ProjectsExternalSourcesModel>> listExternalProjects(@RequestParam(value = "query", required = false) String query, Principal principal) { public @ResponseBody
ResponseEntity<ResponseItem<ProjectsExternalSourcesModel>> listExternalProjects(@RequestParam(value = "query", required = false) String query, Principal principal) {
try { try {
List<Map<String, String>> remoteRepos = this.getApiContext().getRemoteFetcher().getProjects(query); List<Map<String, String>> remoteRepos = this.getApiContext().getRemoteFetcher().getProjects(query);
ProjectsExternalSourcesModel projectsExternalSourcesModel = new ProjectsExternalSourcesModel().fromExternalItem(remoteRepos); ProjectsExternalSourcesModel projectsExternalSourcesModel = new ProjectsExternalSourcesModel().fromExternalItem(remoteRepos);

View File

@ -1,22 +1,64 @@
package eu.eudat.controllers; 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.services.ApiContext;
import eu.eudat.types.ApiMessageCode;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RestController; 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 @RestController
@CrossOrigin @CrossOrigin
public class Users extends BaseController{ public class Users extends BaseController {
@Autowired @Autowired
public Users(ApiContext apiContext) { public Users(ApiContext apiContext) {
super(apiContext); super(apiContext);
} }
@RequestMapping(method = RequestMethod.POST, value = {"/users/getPaged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<UserListingModel>>> getPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) {
try {
DataTableData<UserListingModel> dataTable = UserManager.getPaged(this.getApiContext().getDatabaseRepository().getUserInfoDao(), userInfoTableRequestItem);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<UserListingModel>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
} catch (Exception ex) {
ex.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DataTableData<UserListingModel>>().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<ResponseItem<UserListingModel>> editRoles(@Valid @RequestBody UserListingModel userListingModel, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) {
try {
UserManager.editRoles(this.getApiContext(), userListingModel);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserListingModel>().status(ApiMessageCode.NO_MESSAGE));
} catch (Exception ex) {
ex.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<UserListingModel>().status(ApiMessageCode.DEFAULT_ERROR_MESSAGE).message(ex.getMessage()));
}
}
}

View File

@ -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<UserRole, UUID> {
List<UserRole> getUserRoles(UserInfo userInfo);
}

View File

@ -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<UserRole> implements UserRoleDao{
@Autowired
public UserRoleDaoImpl(DatabaseService<UserRole> 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<UserRole> getUserRoles(UserInfo userInfo) {
return this.getDatabaseService().getQueryable(UserRole.class).where((builder, root) -> builder.equal(root.get("userInfo"),userInfo)).toList();
}
}

View File

@ -1,12 +1,16 @@
package eu.eudat.dao.entities.security; package eu.eudat.dao.entities.security;
import eu.eudat.dao.DatabaseAccessLayer;
import eu.eudat.entities.Credential; 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. * Created by ikalyvas on 12/15/2017.
*/ */
public interface CredentialDao { public interface CredentialDao extends DatabaseAccessLayer<Credential,UUID> {
Credential createOrUpdate(Credential item);
Credential getLoggedInCredentials(Credentials credentials);
} }

View File

@ -4,9 +4,13 @@ import eu.eudat.dao.DatabaseAccess;
import eu.eudat.dao.databaselayer.service.DatabaseService; import eu.eudat.dao.databaselayer.service.DatabaseService;
import eu.eudat.entities.Credential; import eu.eudat.entities.Credential;
import eu.eudat.entities.UserInfo; 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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.UUID;
/** /**
* Created by ikalyvas on 12/15/2017. * Created by ikalyvas on 12/15/2017.
*/ */
@ -20,6 +24,21 @@ public class CredentialDaoImpl extends DatabaseAccess<Credential> implements Cre
@Override @Override
public Credential createOrUpdate(Credential item) { 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();
} }
} }

View File

@ -14,6 +14,8 @@ import java.util.UUID;
public class Credential implements DataEntity<Credential> { public class Credential implements DataEntity<Credential> {
@Id @Id
@GeneratedValue
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(name = "\"Id\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") @Column(name = "\"Id\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)")
private UUID id; private UUID id;

View File

@ -64,6 +64,9 @@ public class UserInfo implements DataEntity<UserInfo>{
@OneToMany(mappedBy="userInfo",fetch = FetchType.LAZY) @OneToMany(mappedBy="userInfo",fetch = FetchType.LAZY)
Set<Credential> credentials = new HashSet<>(); Set<Credential> credentials = new HashSet<>();
@OneToMany(mappedBy="userInfo",fetch = FetchType.LAZY)
Set<UserRole> userRoles = new HashSet<>();
public Set<DMP> getDmps() { public Set<DMP> getDmps() {
return dmps; return dmps;
} }
@ -152,6 +155,14 @@ public class UserInfo implements DataEntity<UserInfo>{
this.credentials = credentials; this.credentials = credentials;
} }
public Set<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
@Override @Override
public void update(UserInfo entity) { public void update(UserInfo entity) {
this.name = entity.getName(); this.name = entity.getName();

View File

@ -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<UserRole> {
@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};
}
}

View File

@ -2,16 +2,19 @@ package eu.eudat.handlers;
import eu.eudat.exceptions.UnauthorisedException; import eu.eudat.exceptions.UnauthorisedException;
import eu.eudat.models.security.Principal; import eu.eudat.models.security.Principal;
import eu.eudat.security.claims.ClaimedAuthorities;
import eu.eudat.services.AuthenticationService; 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.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.method.support.ModelAndViewContainer;
import java.util.Date; import java.lang.annotation.Annotation;
import java.util.UUID; import java.util.*;
import static eu.eudat.types.Authorities.USER;
/** /**
* Created by ikalyvas on 12/15/2017. * Created by ikalyvas on 12/15/2017.
@ -28,6 +31,8 @@ public final class PrincipalArgumentResolver implements HandlerMethodArgumentRes
@Override @Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception { public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
String token = nativeWebRequest.getHeader("AuthToken"); String token = nativeWebRequest.getHeader("AuthToken");
Optional<Annotation> claimsAnnotation = Arrays.stream(methodParameter.getParameterAnnotations()).filter(annotation -> annotation.annotationType().equals(ClaimedAuthorities.class)).findAny();
List<Authorities> claimList = claimsAnnotation.map(annotation -> Arrays.asList(((ClaimedAuthorities) annotation).claims())).orElse(Authorities.all());
if (token == null) throw new UnauthorisedException("Authentication Information Is Missing"); if (token == null) throw new UnauthorisedException("Authentication Information Is Missing");
UUID authToken; UUID authToken;
try { try {
@ -38,6 +43,7 @@ public final class PrincipalArgumentResolver implements HandlerMethodArgumentRes
Principal principal = this.authenticationService.Touch(authToken); Principal principal = this.authenticationService.Touch(authToken);
if (principal == null) throw new UnauthorisedException("Authentication Information Missing"); 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; return principal;
} }

View File

@ -1,10 +1,27 @@
package eu.eudat.managers; 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.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import eu.eudat.utilities.builders.XmlBuilder; import eu.eudat.utilities.builders.XmlBuilder;
import java.util.List;
public class UserManager { public class UserManager {
public static eu.eudat.models.user.composite.DatasetProfile generateDatasetProfileModel(eu.eudat.entities.DatasetProfile profile){ public static eu.eudat.models.user.composite.DatasetProfile generateDatasetProfileModel(eu.eudat.entities.DatasetProfile profile){
Document viewStyleDoc = XmlBuilder.fromXml(profile.getDefinition()); Document viewStyleDoc = XmlBuilder.fromXml(profile.getDefinition());
@ -16,4 +33,32 @@ public class UserManager {
return datasetprofile; return datasetprofile;
} }
public static DataTableData<UserListingModel> getPaged(UserInfoDao userInfoDao , UserInfoTableRequestItem userInfoTableRequestItem) throws Exception {
QueryableList<eu.eudat.entities.UserInfo> users = userInfoDao.getWithCriteria(userInfoTableRequestItem.getCriteria());
QueryableList<eu.eudat.entities.UserInfo> pagedUsers = PaginationManager.applyPaging(users,userInfoTableRequestItem);
List<UserListingModel> modelUsers = new DomainModelConverter<eu.eudat.entities.UserInfo,UserListingModel>().fromDataModel(pagedUsers.toList(),UserListingModel.class);
DataTableData<UserListingModel> 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;
}
} }

View File

@ -1,8 +1,11 @@
package eu.eudat.models.security; package eu.eudat.models.security;
import java.util.Date; import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.Set; import eu.eudat.exceptions.UnauthorisedException;
import java.util.UUID; import eu.eudat.types.Authorities;
import java.util.*;
import java.util.stream.Collectors;
/** /**
* Created by ikalyvas on 12/15/2017. * Created by ikalyvas on 12/15/2017.
@ -12,7 +15,7 @@ public class Principal {
private UUID token; private UUID token;
private String name; private String name;
private Date expiresAt; private Date expiresAt;
private Set<Integer> roles; private Set<Authorities> authorities;
public UUID getId() { public UUID getId() {
return id; return id;
@ -46,11 +49,21 @@ public class Principal {
this.expiresAt = expiresAt; this.expiresAt = expiresAt;
} }
public Set<Integer> getRoles() { public Set<Integer> getAuthorities() {
return roles; return authorities.stream().map(authz -> authz.getValue()).collect(Collectors.toSet());
} }
public void setRoles(Set<Integer> roles) { @JsonIgnore
this.roles = roles; public Set<Authorities> getAuthz() {
return this.authorities;
}
public void setAuthorities(Set<Authorities> authorities) {
this.authorities = authorities;
}
public boolean isAuthorized(List<Authorities> requiredAuthorities) {
if (!Collections.disjoint(this.authorities, requiredAuthorities) || requiredAuthorities.size() == 0) return true;
else return false;
} }
} }

View File

@ -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<UserInfoCriteria> {
}

View File

@ -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<eu.eudat.entities.UserInfo> {
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<Integer> 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<Integer> getAppRoles() {
return appRoles;
}
public void setAppRoles(List<Integer> 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;
}
}

View File

@ -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};
}

View File

@ -13,7 +13,7 @@ import org.springframework.stereotype.Service;
@Service("tokenValidatorFactory") @Service("tokenValidatorFactory")
public class TokenValidatorFactoryImpl implements TokenValidatorFactory{ public class TokenValidatorFactoryImpl implements TokenValidatorFactory{
public enum LoginProvider { 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; private short value;
@ -35,6 +35,8 @@ public class TokenValidatorFactoryImpl implements TokenValidatorFactory{
return TWITTER; return TWITTER;
case 4: case 4:
return LINKEDIN; return LINKEDIN;
case 5:
return NATIVELOGIN;
default: default:
throw new RuntimeException("Unsupported LoginProvider"); throw new RuntimeException("Unsupported LoginProvider");
} }

View File

@ -4,13 +4,18 @@ import eu.eudat.dao.entities.UserInfoDao;
import eu.eudat.dao.entities.security.UserTokenDao; import eu.eudat.dao.entities.security.UserTokenDao;
import eu.eudat.entities.Credential; import eu.eudat.entities.Credential;
import eu.eudat.entities.UserInfo; import eu.eudat.entities.UserInfo;
import eu.eudat.entities.UserRole;
import eu.eudat.entities.UserToken; import eu.eudat.entities.UserToken;
import eu.eudat.models.criteria.UserInfoCriteria; import eu.eudat.models.criteria.UserInfoCriteria;
import eu.eudat.models.login.Credentials;
import eu.eudat.models.loginprovider.LoginProviderUser; import eu.eudat.models.loginprovider.LoginProviderUser;
import eu.eudat.models.security.Principal; import eu.eudat.models.security.Principal;
import eu.eudat.security.validators.TokenValidatorFactoryImpl; import eu.eudat.security.validators.TokenValidatorFactoryImpl;
import eu.eudat.types.Authorities;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.xml.ws.ServiceMode; import javax.xml.ws.ServiceMode;
import java.util.*; import java.util.*;
@ -21,14 +26,15 @@ import java.util.*;
@Service("authenticationService ") @Service("authenticationService ")
public class AuthenticationService { public class AuthenticationService {
private ApiContext apiContext; private ApiContext apiContext;
private Environment environment;
@Autowired @Autowired
public AuthenticationService(ApiContext apiContext) { public AuthenticationService(ApiContext apiContext, Environment environment) {
this.environment = environment;
this.apiContext = apiContext; this.apiContext = apiContext;
} }
public Principal Touch(UUID token) public Principal Touch(UUID token) {
{
UserToken tokenEntry = this.apiContext.getDatabaseRepository().getUserTokenDao().find(token); UserToken tokenEntry = this.apiContext.getDatabaseRepository().getUserTokenDao().find(token);
if (tokenEntry == null || tokenEntry.getExpiresAt().before(new Date())) return null; if (tokenEntry == null || tokenEntry.getExpiresAt().before(new Date())) return null;
@ -37,20 +43,16 @@ public class AuthenticationService {
return principal; return principal;
} }
public void Logout(UUID token) public void Logout(UUID token) {
{
UserToken tokenEntry = this.apiContext.getDatabaseRepository().getUserTokenDao().find(token); UserToken tokenEntry = this.apiContext.getDatabaseRepository().getUserTokenDao().find(token);
this.apiContext.getDatabaseRepository().getUserTokenDao().delete(tokenEntry); 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; if (token == null || token.getExpiresAt().before(new Date())) return null;
UserInfo user = this.apiContext.getDatabaseRepository().getUserInfoDao().find(token.getUser().getId()); UserInfo user = this.apiContext.getDatabaseRepository().getUserInfoDao().find(token.getUser().getId());
if (user == null /*|| user.Status != ActivityStatus.Active*/) return null; if (user == null) return null;
//List<UserRole> appRoles = this._unitOfWork.UserRoles.GetAll().Where(x => x.UserId == token.UserId /*&& x.Status == ActivityStatus.Active*/).ToList();
Principal principal = new Principal(); Principal principal = new Principal();
principal.setId(user.getId()); principal.setId(user.getId());
@ -58,23 +60,38 @@ public class AuthenticationService {
principal.setExpiresAt(token.getExpiresAt()); principal.setExpiresAt(token.getExpiresAt());
principal.setName(user.getName()); principal.setName(user.getName());
/*foreach (UserRole item in appRoles) List<UserRole> userRoles = this.apiContext.getDatabaseRepository().getUserRoleDao().getUserRoles(user);
{ for (UserRole item : userRoles) {
if (principal.AppRoles == null) principal.AppRoles = new HashSet<AppRole>(); if (principal.getAuthz() == null) principal.setAuthorities(new HashSet<Authorities>());
principal.AppRoles.Add(item.Role); principal.getAuthz().add(Authorities.fromInteger(item.getRole()));
} }
if (this._config.Refresh) token.ExpiresAt = DateTime.UtcNow.AddMinutes(this._config.Lifetime);
*/
return principal; 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(); UserInfoCriteria criteria = new UserInfoCriteria();
criteria.setEmail(profile.getEmail()); criteria.setEmail(profile.getEmail());
List<UserInfo> users = apiContext.getDatabaseRepository().getUserInfoDao().getWithCriteria(criteria).toList(); List<UserInfo> users = apiContext.getDatabaseRepository().getUserInfoDao().getWithCriteria(criteria).toList();
UserInfo userInfo = null; UserInfo userInfo = null;
if(users.size()>0)userInfo = users.get(0); if (users.size() > 0) userInfo = users.get(0);
final Credential credential = new Credential(); final Credential credential = new Credential();
credential.setId(UUID.randomUUID()); credential.setId(UUID.randomUUID());
credential.setCreationTime(new Date()); credential.setCreationTime(new Date());
@ -82,9 +99,9 @@ public class AuthenticationService {
credential.setLastUpdateTime(new Date()); credential.setLastUpdateTime(new Date());
credential.setProvider((int) profile.getProvider().getValue()); credential.setProvider((int) profile.getProvider().getValue());
credential.setSecret(profile.getSecret()); credential.setSecret(profile.getSecret());
if(userInfo == null) { if (userInfo == null) {
userInfo = new UserInfo(); userInfo = new UserInfo();
userInfo.setName((String)profile.getName()); userInfo.setName((String) profile.getName());
userInfo.setVerified_email(profile.getIsVerified()); userInfo.setVerified_email(profile.getIsVerified());
userInfo.setEmail(profile.getEmail()); userInfo.setEmail(profile.getEmail());
userInfo.setCreated(new Date()); userInfo.setCreated(new Date());
@ -95,15 +112,18 @@ public class AuthenticationService {
credential.setPublicValue(userInfo.getName()); credential.setPublicValue(userInfo.getName());
credential.setUserInfo(userInfo); credential.setUserInfo(userInfo);
apiContext.getDatabaseRepository().getCredentialDao().createOrUpdate(credential); apiContext.getDatabaseRepository().getCredentialDao().createOrUpdate(credential);
}
else { UserRole role = new UserRole();
role.setRole(Authorities.USER.getValue());
role.setUserInfo(userInfo);
} else {
userInfo.setLastloggedin(new Date()); userInfo.setLastloggedin(new Date());
Set<Credential> credentials = userInfo.getCredentials(); Set<Credential> credentials = userInfo.getCredentials();
if(credentials.contains(credential)){ if (credentials.contains(credential)) {
Credential oldCredential = credentials.stream().filter(item->credential.getProvider().equals(item.getProvider())).findFirst().get(); Credential oldCredential = credentials.stream().filter(item -> credential.getProvider().equals(item.getProvider())).findFirst().get();
credential.setId(oldCredential.getId()); credential.setId(oldCredential.getId());
} } else {
else{
credential.setUserInfo(userInfo); credential.setUserInfo(userInfo);
credential.setId(UUID.randomUUID()); credential.setId(UUID.randomUUID());
credential.setPublicValue(userInfo.getName()); credential.setPublicValue(userInfo.getName());
@ -122,7 +142,7 @@ public class AuthenticationService {
return Touch(userToken.getToken()); return Touch(userToken.getToken());
} }
private Date addADay(Date date){ private Date addADay(Date date) {
Date dt = new Date(); Date dt = new Date();
Calendar c = Calendar.getInstance(); Calendar c = Calendar.getInstance();
c.setTime(dt); c.setTime(dt);
@ -130,4 +150,34 @@ public class AuthenticationService {
dt = c.getTime(); dt = c.getTime();
return dt; 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);
}
} }

View File

@ -18,6 +18,7 @@ public interface DatabaseRepository {
ResearcherDao getResearcherDao(); ResearcherDao getResearcherDao();
ServiceDao getServiceDao(); ServiceDao getServiceDao();
UserInfoDao getUserInfoDao(); UserInfoDao getUserInfoDao();
UserRoleDao getUserRoleDao();
InvitationDao getInvitationDao(); InvitationDao getInvitationDao();
CredentialDao getCredentialDao(); CredentialDao getCredentialDao();
UserTokenDao getUserTokenDao(); UserTokenDao getUserTokenDao();

View File

@ -6,6 +6,8 @@ import eu.eudat.dao.entities.security.UserTokenDao;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.persistence.EntityManager;
/** /**
* Created by ikalyvas on 1/4/2018. * Created by ikalyvas on 1/4/2018.
*/ */
@ -26,6 +28,9 @@ public class DatabaseRepositoryImpl implements DatabaseRepository{
private CredentialDao credentialDao; private CredentialDao credentialDao;
private UserTokenDao userTokenDao; private UserTokenDao userTokenDao;
private ExternalDatasetDao externalDatasetDao; private ExternalDatasetDao externalDatasetDao;
private UserRoleDao userRoleDao;
private EntityManager entityManager;
@Autowired @Autowired
private void setDataRepositoryDao(DataRepositoryDao dataRepositoryDao) { private void setDataRepositoryDao(DataRepositoryDao dataRepositoryDao) {
@ -166,4 +171,19 @@ public class DatabaseRepositoryImpl implements DatabaseRepository{
public void setExternalDatasetDao(ExternalDatasetDao externalDatasetDao) { public void setExternalDatasetDao(ExternalDatasetDao externalDatasetDao) {
this.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;
}
} }

View File

@ -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<Authorities> all(){
return Arrays.asList(USER,ADMIN,MANAGER);
}
}

View File

@ -63,3 +63,6 @@ twitter.login.redirect_uri=http://dl043.madgik.di.uoa.gr:8080/login/twitter
#persistence.hibernate.connectionpool.c3p0.test_connection_on_checkout = false #persistence.hibernate.connectionpool.c3p0.test_connection_on_checkout = false
#persistence.hibernate.connectionpool.c3p0.preferred_test_query = select 1 #persistence.hibernate.connectionpool.c3p0.preferred_test_query = select 1
########################Persistence/Hibernate/Connection pool#################### ########################Persistence/Hibernate/Connection pool####################
autouser.root.email = root@dmp.com
autouser.root.password = root
autouser.root.username = root

View File

@ -13,7 +13,7 @@ export class Principal implements Serializable<Principal> {
this.token = item.token; this.token = item.token;
this.name = item.name; this.name = item.name;
this.expiresAt = item.expiresAt; this.expiresAt = item.expiresAt;
this.appRoles = item.appRoles; this.appRoles = item.authorities;
return this; return this;
} }
} }

View File

@ -100,9 +100,8 @@ export class AuthService {
let headers = this.headers; let headers = this.headers;
headers = headers.set('AuthToken', principal.token) headers = headers.set('AuthToken', principal.token)
return this.http.post(url, null, { headers: headers }) return this.http.post(url, null, { headers: headers })
.map((r: Response) => { .map((res: any) => {
const princ = this.current(JsonSerializer.fromJSONObject(r.json(), Principal)); const princ = this.current(JsonSerializer.fromJSONObject(res.payload, Principal));
//this.loginContextSubject.next(true);
return princ; return princ;
}) })
.catch((error: any) => { .catch((error: any) => {

View File

@ -25,6 +25,7 @@ export class UnauthorizedComponent {
this.authService.me().subscribe( this.authService.me().subscribe(
principal => { principal => {
if (!principal) this.router.navigate(['/login'], { queryParams: { returnUrl: returnUrl } }); if (!principal) this.router.navigate(['/login'], { queryParams: { returnUrl: returnUrl } });
else this.router.navigate(["/"])
}, },
err => console.error('An error occurred', err)); err => console.error('An error occurred', err));
} }