no message

This commit is contained in:
Ioannis Kalyvas 2018-01-31 17:39:16 +02:00
parent 702339d9d6
commit a70529fb93
26 changed files with 625 additions and 68 deletions

View File

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

View File

@ -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;
@ -40,7 +41,7 @@ public class Login {
@Transactional
@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 {
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().payload(customAuthenticationProvider.authenticate(credentials)).status(ApiMessageCode.SUCCESS_MESSAGE));
}catch (UnauthorisedException ex){
@ -52,6 +53,20 @@ public class Login {
}
}
@Transactional
@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 {

View File

@ -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<ResponseItem<DataTableData<ProjectListingModel>>> getPaged(@Valid @RequestBody ProjectTableRequest projectTableRequest, Principal principal) {
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<ProjectListingModel>>> getPaged(@Valid @RequestBody ProjectTableRequest projectTableRequest, Principal principal) {
try {
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));
@ -56,7 +61,8 @@ public class Projects extends BaseController {
}
@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 {
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));
@ -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<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 {
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"));
@ -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<ResponseItem<Project>> inactivate(@PathVariable String id, Principal principal) {
public @ResponseBody
ResponseEntity<ResponseItem<Project>> 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<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")
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 {
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));
@ -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<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 {
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));
@ -114,7 +124,8 @@ public class Projects extends BaseController {
}
@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 {
List<Map<String, String>> remoteRepos = this.getApiContext().getRemoteFetcher().getProjects(query);
ProjectsExternalSourcesModel projectsExternalSourcesModel = new ProjectsExternalSourcesModel().fromExternalItem(remoteRepos);

View File

@ -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<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;
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,UUID> {
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.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<Credential> 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();
}
}

View File

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

View File

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

View File

@ -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<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;
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<Integer> roles;
private Set<Authorities> authorities;
public UUID getId() {
return id;
@ -46,11 +49,21 @@ public class Principal {
this.expiresAt = expiresAt;
}
public Set<Integer> getRoles() {
return roles;
public Set<Integer> getAuthorities() {
return authorities.stream().map(authz -> authz.getValue()).collect(Collectors.toSet());
}
public void setRoles(Set<Integer> roles) {
this.roles = roles;
@JsonIgnore
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")
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");
}

View File

@ -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<UserRole> 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<AppRole>();
principal.AppRoles.Add(item.Role);
List<UserRole> userRoles = this.apiContext.getDatabaseRepository().getUserRoleDao().getUserRoles(user);
for (UserRole item : userRoles) {
if (principal.getAuthz() == null) principal.setAuthorities(new HashSet<Authorities>());
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<UserInfo> 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<Credential> 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);
}
}

View File

@ -18,6 +18,7 @@ public interface DatabaseRepository {
ResearcherDao getResearcherDao();
ServiceDao getServiceDao();
UserInfoDao getUserInfoDao();
UserRoleDao getUserRoleDao();
InvitationDao getInvitationDao();
CredentialDao getCredentialDao();
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.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;
}
}

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

@ -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####################
########################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.name = item.name;
this.expiresAt = item.expiresAt;
this.appRoles = item.appRoles;
this.appRoles = item.authorities;
return this;
}
}

View File

@ -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) => {

View File

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