database enum handle implementation

This commit is contained in:
Efstratios Giannopoulos 2023-10-16 17:38:12 +03:00
parent d5c62539c5
commit 191f887530
26 changed files with 446 additions and 117 deletions

View File

@ -14,6 +14,14 @@
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
<dependencies>
<dependency>
<groupId>dmp-backend</groupId>
<artifactId>queryable</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build> <build>
<plugins> <plugins>

View File

@ -0,0 +1,29 @@
package eu.eudat.commons.enums;
import eu.eudat.data.converters.enums.DatabaseEnum;
import java.util.HashMap;
import java.util.Map;
public enum ProviderType implements DatabaseEnum<Integer> {
Google (1),
Facebook ( 2),
Twitter ( 3),
LinkedIn (4),
NativeLogin ( 5),
B2Access ( 6),
ORCID (7),
OpenAire ( 8),
Configurable ( 9),
Zenodo (10),
Keycloack ( 128);
private final Integer value;
ProviderType(Integer value) {
this.value = value;
}
public Integer getValue() { return this.value; }
}

View File

@ -0,0 +1,19 @@
package eu.eudat.commons.enums;
import eu.eudat.data.converters.enums.DatabaseEnum;
public enum Status implements DatabaseEnum<Integer> {
Inactive(0),
Active( 1);
private final Integer value;
Status(Integer value) {
this.value = value;
}
public Integer getValue() {
return value;
}
}

View File

@ -1,9 +1,13 @@
package eu.eudat.data.entities; package eu.eudat.data;
import eu.eudat.commons.enums.ProviderType;
import eu.eudat.commons.enums.Status;
import eu.eudat.data.converters.DateToUTCConverter; import eu.eudat.data.converters.DateToUTCConverter;
import eu.eudat.data.entities.helpers.EntityBinder;
import eu.eudat.queryable.queryableentity.DataEntity;
import eu.eudat.data.converters.enums.ProviderTypeConverter;
import eu.eudat.data.converters.enums.StatusConverter;
import eu.eudat.data.helpers.EntityBinder;
import eu.eudat.queryable.queryableentity.DataEntity;
import jakarta.persistence.*; import jakarta.persistence.*;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@ -12,29 +16,30 @@ import java.util.UUID;
@Entity @Entity
@Table(name = "\"Credential\"") @Table(name = "\"Credential\"")
@NamedEntityGraphs({ //@NamedEntityGraphs({
@NamedEntityGraph( // @NamedEntityGraph(
name = "credentialUserInfo", // name = "credentialUserInfo",
attributeNodes = {@NamedAttributeNode("userInfo")}) // attributeNodes = {@NamedAttributeNode("userInfo")})
}) //})
public class Credential implements DataEntity<Credential, UUID> { public class CredentialEntity implements DataEntity<CredentialEntity, UUID> {
@Id @Id
@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;
public final static String _id = "id"; public final static String _id = "id";
@ManyToOne @Column(name = "\"UserId\"", columnDefinition = "uuid", nullable = false)
@JoinColumn(name = "\"UserId\"", nullable = false) private UUID userId;
private UserInfo userInfo; public final static String _userId = "userId";
public final static String _userInfo = "userInfo"; //TODO: Authn
@Column(name = "\"Status\"", nullable = false) @Column(name = "\"Status\"", nullable = false)
private Integer status; @Convert(converter = StatusConverter.class)
private Status status;
public final static String _status = "status"; public final static String _status = "status";
@Column(name = "\"Provider\"", nullable = false) @Column(name = "\"Provider\"", nullable = false)
private Integer provider; @Convert(converter = ProviderTypeConverter.class)
private ProviderType provider;
public final static String _provider = "provider"; public final static String _provider = "provider";
@Column(name = "\"Public\"", nullable = false) @Column(name = "\"Public\"", nullable = false)
@ -71,27 +76,27 @@ public class Credential implements DataEntity<Credential, UUID> {
this.id = id; this.id = id;
} }
public UserInfo getUserInfo() { public UUID getUserId() {
return userInfo; return userId;
} }
public void setUserInfo(UserInfo userInfo) { public void setUserId(UUID userId) {
this.userInfo = userInfo; this.userId = userId;
} }
public Integer getStatus() { public Status getStatus() {
return status; return status;
} }
public void setStatus(Integer status) { public void setStatus(Status status) {
this.status = status; this.status = status;
} }
public Integer getProvider() { public ProviderType getProvider() {
return provider; return provider;
} }
public void setProvider(Integer provider) { public void setProvider(ProviderType provider) {
this.provider = provider; this.provider = provider;
} }
@ -148,18 +153,18 @@ public class Credential implements DataEntity<Credential, UUID> {
if (this == o) return true; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; if (o == null || getClass() != o.getClass()) return false;
Credential that = (Credential) o; CredentialEntity that = (CredentialEntity) o;
return provider.intValue() == that.provider.intValue(); return provider.getValue() == that.provider.getValue();
} }
@Override @Override
public int hashCode() { public int hashCode() {
return provider.intValue(); return provider.getValue();
} }
@Override @Override
public void update(Credential entity) { public void update(CredentialEntity entity) {
this.status = entity.status; this.status = entity.status;
this.publicValue = entity.getPublicValue(); this.publicValue = entity.getPublicValue();
this.email = entity.getEmail(); this.email = entity.getEmail();
@ -173,7 +178,7 @@ public class Credential implements DataEntity<Credential, UUID> {
} }
@Override @Override
public Credential buildFromTuple(List<Tuple> tuple, List<String> fields, String base) { public CredentialEntity buildFromTuple(List<Tuple> tuple, List<String> fields, String base) {
String currentBase = base.isEmpty() ? "" : base + "."; String currentBase = base.isEmpty() ? "" : base + ".";
if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id");
return this; return this;

View File

@ -0,0 +1,48 @@
package eu.eudat.data.converters;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
/**
* Created by ikalyvas on 9/25/2018.
*/
@Converter
public class DateToUTCConverter implements AttributeConverter<Date, Date> {
private static final Logger logger = LoggerFactory.getLogger(DateToUTCConverter.class);
@Override
public Date convertToDatabaseColumn(Date attribute) {
if(attribute == null) return null;
DateFormat formatterIST = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatterIST.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
String date = formatterIST.format(attribute);
return formatterIST.parse(date);
} catch (ParseException e) {
logger.error(e.getMessage(), e);
}
return null;
}
@Override
public Date convertToEntityAttribute(Date dbData) {
if(dbData == null) return null;
DateFormat formatterIST = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatterIST.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
String date = formatterIST.format(dbData);
return formatterIST.parse(date);
} catch (ParseException e) {
logger.error(e.getMessage(), e);
}
return null;
}
}

View File

@ -0,0 +1,5 @@
package eu.eudat.data.converters.enums;
public interface DatabaseEnum<T> {
T getValue();
}

View File

@ -0,0 +1,21 @@
package eu.eudat.data.converters.enums;
import eu.eudat.commons.enums.ProviderType;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
@Converter
public abstract class DatabaseEnumConverter<EnumType extends DatabaseEnum<T>, T> implements AttributeConverter<EnumType, T> {
protected abstract EnumType of(T dbData);
@Override
public T convertToDatabaseColumn(EnumType value) {
if (value == null) throw new IllegalArgumentException("value");
return value.getValue();
}
@Override
public EnumType convertToEntityAttribute(T dbData) {
return this.of(dbData);
}
}

View File

@ -0,0 +1,22 @@
package eu.eudat.data.converters.enums;
import eu.eudat.commons.enums.ProviderType;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import java.util.HashMap;
import java.util.Map;
@Converter
public class ProviderTypeConverter extends DatabaseEnumConverter<ProviderType, Integer> {
private static final Map<Integer, ProviderType> map;
static {
map = new HashMap<>();
for (ProviderType v : ProviderType.values()) {
map.put(v.getValue(), v);
}
}
public ProviderType of(Integer i) {
return map.get(i);
}
}

View File

@ -0,0 +1,22 @@
package eu.eudat.data.converters.enums;
import eu.eudat.commons.enums.ProviderType;
import eu.eudat.commons.enums.Status;
import jakarta.persistence.Converter;
import java.util.HashMap;
import java.util.Map;
@Converter
public class StatusConverter extends DatabaseEnumConverter<Status, Integer> {
private static final Map<Integer, Status> map;
static {
map = new HashMap<>();
for (Status v : Status.values()) {
map.put(v.getValue(), v);
}
}
public Status of(Integer i) {
return map.get(i);
}
}

View File

@ -0,0 +1,15 @@
package eu.eudat.data.helpers;
import jakarta.persistence.Tuple;
import java.util.List;
public class EntityBinder {
public static <T> T fromTuple(List<Tuple> tuple, String path) {
try {
return (T) tuple.get(0).get(path);
}catch (IllegalArgumentException illegalArgument){
return null;
}
}
}

View File

@ -0,0 +1,125 @@
package eu.eudat.query;
import eu.eudat.data.CredentialEntity;
import gr.cite.tools.data.query.FieldResolver;
import gr.cite.tools.data.query.QueryBase;
import gr.cite.tools.data.query.QueryContext;
import jakarta.persistence.Tuple;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Predicate;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.*;
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class CredentialQuery extends QueryBase<CredentialEntity> {
private Collection<UUID> ids;
private Collection<UUID> userIds;
private Collection<Short> statuses;
public CredentialQuery ids(UUID value) {
this.ids = List.of(value);
return this;
}
public CredentialQuery ids(UUID... value) {
this.ids = Arrays.asList(value);
return this;
}
public CredentialQuery ids(List<UUID> value) {
this.ids = value;
return this;
}
public CredentialQuery userIds(UUID value) {
this.userIds = List.of(value);
return this;
}
public CredentialQuery userIds(UUID... value) {
this.userIds = Arrays.asList(value);
return this;
}
public CredentialQuery userIds(List<UUID> value) {
this.userIds = value;
return this;
}
public CredentialQuery statuses(Short value) {
this.statuses = List.of(value);
return this;
}
public CredentialQuery statuses(Short... value) {
this.statuses = Arrays.asList(value);
return this;
}
public CredentialQuery statuses(List<Short> value) {
this.statuses = value;
return this;
}
@Override
protected Boolean isFalseQuery() {
return this.isEmpty(this.ids) || this.isEmpty(this.userIds) || this.isEmpty(this.statuses);
}
@Override
protected Class<CredentialEntity> entityClass() {
return CredentialEntity.class;
}
@Override
protected <X, Y> Predicate applyFilters(QueryContext<X, Y> queryContext) {
List<Predicate> predicates = new ArrayList<>();
if (this.ids != null) {
CriteriaBuilder.In<UUID> inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(CredentialEntity._id));
for (UUID item : this.ids)
inClause.value(item);
predicates.add(inClause);
}
if (this.userIds != null) {
CriteriaBuilder.In<UUID> inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(CredentialEntity._userId));
for (UUID item : this.userIds)
inClause.value(item);
predicates.add(inClause);
}
if (this.statuses != null) {
CriteriaBuilder.In<Short> inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(CredentialEntity._status));
for (Short item : this.statuses)
inClause.value(item);
predicates.add(inClause);
}
if (!predicates.isEmpty()) {
Predicate[] predicatesArray = predicates.toArray(new Predicate[0]);
return queryContext.CriteriaBuilder.and(predicatesArray);
} else {
return queryContext.CriteriaBuilder.and();
}
}
@Override
protected String fieldNameOf(FieldResolver item) {
return null;
}
@Override
protected CredentialEntity convert(Tuple tuple, Set<String> columns) {
return null;
}
}

View File

@ -1,12 +1,12 @@
package eu.eudat.data.dao.entities.security; package eu.eudat.data.dao.entities.security;
import eu.eudat.data.CredentialEntity;
import eu.eudat.data.dao.DatabaseAccessLayer; import eu.eudat.data.dao.DatabaseAccessLayer;
import eu.eudat.data.entities.Credential;
import java.util.UUID; import java.util.UUID;
public interface CredentialDao extends DatabaseAccessLayer<Credential, UUID> { public interface CredentialDao extends DatabaseAccessLayer<CredentialEntity, UUID> {
Credential getLoggedInCredentials(String username, String secret, Integer provider); CredentialEntity getLoggedInCredentials(String username, String secret, Integer provider);
} }

View File

@ -1,8 +1,8 @@
package eu.eudat.data.dao.entities.security; package eu.eudat.data.dao.entities.security;
import eu.eudat.data.CredentialEntity;
import eu.eudat.data.dao.DatabaseAccess; import eu.eudat.data.dao.DatabaseAccess;
import eu.eudat.data.dao.databaselayer.service.DatabaseService; import eu.eudat.data.dao.databaselayer.service.DatabaseService;
import eu.eudat.data.entities.Credential;
import eu.eudat.queryable.QueryableList; import eu.eudat.queryable.QueryableList;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -12,26 +12,26 @@ import java.util.concurrent.CompletableFuture;
@Component("credentialDao") @Component("credentialDao")
public class CredentialDaoImpl extends DatabaseAccess<Credential> implements CredentialDao { public class CredentialDaoImpl extends DatabaseAccess<CredentialEntity> implements CredentialDao {
@Autowired @Autowired
public CredentialDaoImpl(DatabaseService<Credential> databaseService) { public CredentialDaoImpl(DatabaseService<CredentialEntity> databaseService) {
super(databaseService); super(databaseService);
} }
@Override @Override
public Credential createOrUpdate(Credential item) { public CredentialEntity createOrUpdate(CredentialEntity item) {
return this.getDatabaseService().createOrUpdate(item, Credential.class); return this.getDatabaseService().createOrUpdate(item, CredentialEntity.class);
} }
@Override @Override
public Credential find(UUID id) { public CredentialEntity find(UUID id) {
return this.getDatabaseService().getQueryable(Credential.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingleOrDefault(); return this.getDatabaseService().getQueryable(CredentialEntity.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingleOrDefault();
} }
@Override @Override
public Credential getLoggedInCredentials(String username, String secret, Integer provider) { public CredentialEntity getLoggedInCredentials(String username, String secret, Integer provider) {
return this.getDatabaseService().getQueryable(Credential.class).where(((builder, root) -> return this.getDatabaseService().getQueryable(CredentialEntity.class).where(((builder, root) ->
builder.and( builder.and(
builder.equal(root.get("publicValue"), username), builder.equal(root.get("publicValue"), username),
builder.equal(root.get("secret"), secret), builder.equal(root.get("secret"), secret),
@ -40,22 +40,22 @@ public class CredentialDaoImpl extends DatabaseAccess<Credential> implements Cre
} }
@Override @Override
public void delete(Credential item) { public void delete(CredentialEntity item) {
this.getDatabaseService().delete(item); this.getDatabaseService().delete(item);
} }
@Override @Override
public QueryableList<Credential> asQueryable() { public QueryableList<CredentialEntity> asQueryable() {
return this.getDatabaseService().getQueryable(Credential.class); return this.getDatabaseService().getQueryable(CredentialEntity.class);
} }
@Override @Override
public CompletableFuture<Credential> createOrUpdateAsync(Credential item) { public CompletableFuture<CredentialEntity> createOrUpdateAsync(CredentialEntity item) {
return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item));
} }
@Override @Override
public Credential find(UUID id, String hint) { public CredentialEntity find(UUID id, String hint) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
} }

View File

@ -1,5 +1,6 @@
package eu.eudat.data.entities; package eu.eudat.data.entities;
import eu.eudat.data.CredentialEntity;
import eu.eudat.data.converters.DateToUTCConverter; import eu.eudat.data.converters.DateToUTCConverter;
import eu.eudat.data.entities.helpers.EntityBinder; import eu.eudat.data.entities.helpers.EntityBinder;
import eu.eudat.queryable.queryableentity.DataEntity; import eu.eudat.queryable.queryableentity.DataEntity;
@ -15,7 +16,7 @@ import java.util.*;
@NamedEntityGraphs({ @NamedEntityGraphs({
@NamedEntityGraph( @NamedEntityGraph(
name = "userInfo", name = "userInfo",
attributeNodes = {@NamedAttributeNode("userRoles"), @NamedAttributeNode("credentials"), @NamedAttributeNode("additionalinfo")}), attributeNodes = {@NamedAttributeNode("userRoles"), @NamedAttributeNode("additionalinfo")}),
}) })
public class UserInfo implements DataEntity<UserInfo, UUID> { public class UserInfo implements DataEntity<UserInfo, UUID> {
@ -76,8 +77,9 @@ public class UserInfo implements DataEntity<UserInfo, UUID> {
) )
private Set<DMP> dmps; private Set<DMP> dmps;
@OneToMany(mappedBy = "userInfo", fetch = FetchType.LAZY) @OneToMany(fetch = FetchType.LAZY)
private Set<Credential> credentials = new HashSet<>(); @JoinColumn(name = "Id")
private Set<CredentialEntity> credentialEntities = new HashSet<>();
@OneToMany(mappedBy = "userInfo", fetch = FetchType.LAZY) @OneToMany(mappedBy = "userInfo", fetch = FetchType.LAZY)
private Set<UserRole> userRoles = new HashSet<>(); private Set<UserRole> userRoles = new HashSet<>();
@ -168,12 +170,12 @@ public class UserInfo implements DataEntity<UserInfo, UUID> {
this.additionalinfo = additionalinfo; this.additionalinfo = additionalinfo;
} }
public Set<Credential> getCredentials() { public Set<CredentialEntity> getCredentials() {
return credentials; return credentialEntities;
} }
public void setCredentials(Set<Credential> credentials) { public void setCredentials(Set<CredentialEntity> credentialEntities) {
this.credentials = credentials; this.credentialEntities = credentialEntities;
} }
public Set<UserRole> getUserRoles() { public Set<UserRole> getUserRoles() {

View File

@ -45,8 +45,8 @@ public class SecurityConfiguration {
.headers(httpSecurityHeadersConfigurer -> httpSecurityHeadersConfigurer.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)) .headers(httpSecurityHeadersConfigurer -> httpSecurityHeadersConfigurer.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))
.addFilterBefore(apiKeyFilter, AbstractPreAuthenticatedProcessingFilter.class) .addFilterBefore(apiKeyFilter, AbstractPreAuthenticatedProcessingFilter.class)
.authorizeHttpRequests(authRequest -> .authorizeHttpRequests(authRequest ->
authRequest.requestMatchers(buildAntPatterns(webSecurityProperties.getAllowedEndpoints())).anonymous() authRequest.requestMatchers(buildAntPatterns(webSecurityProperties.getAllowedEndpoints())).permitAll() //TODO: Authz
.requestMatchers(buildAntPatterns(webSecurityProperties.getAuthorizedEndpoints())).authenticated()) .requestMatchers(buildAntPatterns(webSecurityProperties.getAuthorizedEndpoints())).permitAll())
.sessionManagement( sessionManagementConfigurer-> sessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.NEVER)) .sessionManagement( sessionManagementConfigurer-> sessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.NEVER))
.oauth2ResourceServer(oauth2 -> oauth2.authenticationManagerResolver(authenticationManagerResolver)); .oauth2ResourceServer(oauth2 -> oauth2.authenticationManagerResolver(authenticationManagerResolver));
return tempHttp.build(); return tempHttp.build();

View File

@ -1,14 +1,18 @@
package eu.eudat.interceptors; package eu.eudat.interceptors;
import eu.eudat.commons.enums.ProviderType;
import eu.eudat.commons.enums.Status;
import eu.eudat.commons.scope.UserScope; import eu.eudat.commons.scope.UserScope;
import eu.eudat.data.entities.Credential; import eu.eudat.data.CredentialEntity;
import eu.eudat.data.entities.UserInfo; import eu.eudat.data.entities.UserInfo;
import eu.eudat.data.entities.UserRole; import eu.eudat.data.entities.UserRole;
import eu.eudat.exceptions.security.NullEmailException; import eu.eudat.exceptions.security.NullEmailException;
import eu.eudat.query.CredentialQuery;
import eu.eudat.types.Authorities; import eu.eudat.types.Authorities;
import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver;
import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractor; import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractor;
import gr.cite.tools.data.query.QueryFactory;
import gr.cite.tools.exception.MyApplicationException; import gr.cite.tools.exception.MyApplicationException;
import gr.cite.tools.logging.LoggerService; import gr.cite.tools.logging.LoggerService;
import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManager;
@ -50,7 +54,7 @@ public class UserInterceptor implements WebRequestInterceptor {
@Autowired @Autowired
public UserInterceptor( public UserInterceptor(
UserScope userScope, UserScope userScope,
ClaimExtractor claimExtractor, ClaimExtractor claimExtractor,
CurrentPrincipalResolver currentPrincipalResolver, CurrentPrincipalResolver currentPrincipalResolver,
PlatformTransactionManager transactionManager, PlatformTransactionManager transactionManager,
@ -68,7 +72,6 @@ public class UserInterceptor implements WebRequestInterceptor {
UUID userId = null; UUID userId = null;
if (this.currentPrincipalResolver.currentPrincipal().isAuthenticated()) { if (this.currentPrincipalResolver.currentPrincipal().isAuthenticated()) {
String subjectId = this.claimExtractor.subjectString(this.currentPrincipalResolver.currentPrincipal()); String subjectId = this.claimExtractor.subjectString(this.currentPrincipalResolver.currentPrincipal());
UserInterceptorCacheService.UserInterceptorCacheValue cacheValue = this.userInterceptorCacheService.lookup(this.userInterceptorCacheService.buildKey(subjectId)); UserInterceptorCacheService.UserInterceptorCacheValue cacheValue = this.userInterceptorCacheService.lookup(this.userInterceptorCacheService.buildKey(subjectId));
if (cacheValue != null) { if (cacheValue != null) {
userId = cacheValue.getUserId(); userId = cacheValue.getUserId();
@ -94,15 +97,15 @@ public class UserInterceptor implements WebRequestInterceptor {
private UUID getUserIdFromDatabaseBySubject(String subjectId) { private UUID getUserIdFromDatabaseBySubject(String subjectId) {
CriteriaBuilder credentialCriteriaBuilder = this.entityManager.getCriteriaBuilder(); CriteriaBuilder credentialCriteriaBuilder = this.entityManager.getCriteriaBuilder();
CriteriaQuery<Tuple> credentialQuery = credentialCriteriaBuilder.createQuery(Tuple.class); CriteriaQuery<Tuple> credentialQuery = credentialCriteriaBuilder.createQuery(Tuple.class);
Root<Credential> credentialRoot = credentialQuery.from(Credential.class); Root<CredentialEntity> credentialRoot = credentialQuery.from(CredentialEntity.class);
credentialQuery.where( credentialQuery.where(
credentialCriteriaBuilder.and( credentialCriteriaBuilder.and(
credentialCriteriaBuilder.equal(credentialRoot.get(Credential._externalId), subjectId), credentialCriteriaBuilder.equal(credentialRoot.get(CredentialEntity._externalId), subjectId),
credentialCriteriaBuilder.equal(credentialRoot.get(Credential._status), 1), //TODO: Authn credentialCriteriaBuilder.equal(credentialRoot.get(CredentialEntity._status), Status.Active),
credentialCriteriaBuilder.equal(credentialRoot.get(Credential._provider), 128) credentialCriteriaBuilder.equal(credentialRoot.get(CredentialEntity._provider), ProviderType.Keycloack)
)); ));
credentialQuery.multiselect(credentialRoot.get(Credential._userInfo).get(UserInfo._id).alias(UserInfo._id)); credentialQuery.multiselect(credentialRoot.get(CredentialEntity._userId).alias(UserInfo._id));
List<Tuple> results = this.entityManager.createQuery(credentialQuery).getResultList(); List<Tuple> results = this.entityManager.createQuery(credentialQuery).getResultList();
return this.getUUIDFromTuple(results, UserInfo._id); return this.getUUIDFromTuple(results, UserInfo._id);
@ -194,17 +197,17 @@ public class UserInterceptor implements WebRequestInterceptor {
user.setAdditionalinfo("{\"data\":{\"avatar\":{\"url\":\"\"},\"zenodoToken\":\"\", \"expirationDate\": \"\", \"zenodoRefresh\": \"\", \"zenodoEmail\": \"\"}}"); //TODO: Authn user.setAdditionalinfo("{\"data\":{\"avatar\":{\"url\":\"\"},\"zenodoToken\":\"\", \"expirationDate\": \"\", \"zenodoRefresh\": \"\", \"zenodoEmail\": \"\"}}"); //TODO: Authn
} }
Credential credential = new Credential(); CredentialEntity credentialEntity = new CredentialEntity();
credential.setId(UUID.randomUUID()); credentialEntity.setId(UUID.randomUUID());
credential.setUserInfo(user); credentialEntity.setUserId(user.getId());
credential.setSecret(subjectId); credentialEntity.setSecret(subjectId);
credential.setCreationTime(new Date()); credentialEntity.setCreationTime(new Date());
credential.setLastUpdateTime(new Date()); credentialEntity.setLastUpdateTime(new Date());
credential.setStatus(1); credentialEntity.setStatus(Status.Active);
credential.setProvider(128);//TODO: Authn credentialEntity.setProvider(ProviderType.Keycloack);//TODO: Authn
credential.setExternalId(subjectId); credentialEntity.setExternalId(subjectId);
credential.setEmail(email); credentialEntity.setEmail(email);
credential.setPublicValue(email); credentialEntity.setPublicValue(email);
DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
@ -218,12 +221,12 @@ public class UserInterceptor implements WebRequestInterceptor {
user = this.entityManager.merge(user); user = this.entityManager.merge(user);
this.entityManager.flush(); this.entityManager.flush();
userRole.setUserInfo(user); userRole.setUserInfo(user);
credential.setUserInfo(user); credentialEntity.setUserId(user.getId());
this.entityManager.merge(userRole); this.entityManager.merge(userRole);
this.entityManager.merge(credential); this.entityManager.merge(credentialEntity);
} else { } else {
this.entityManager.persist(user); this.entityManager.persist(user);
this.entityManager.persist(credential); this.entityManager.persist(credentialEntity);
} }
this.entityManager.flush(); this.entityManager.flush();
transactionManager.commit(status); transactionManager.commit(status);

View File

@ -1,7 +1,9 @@
package eu.eudat.logic.builders.entity; package eu.eudat.logic.builders.entity;
import eu.eudat.commons.enums.ProviderType;
import eu.eudat.commons.enums.Status;
import eu.eudat.data.CredentialEntity;
import eu.eudat.logic.builders.Builder; import eu.eudat.logic.builders.Builder;
import eu.eudat.data.entities.Credential;
import eu.eudat.data.entities.UserInfo; import eu.eudat.data.entities.UserInfo;
import java.util.Date; import java.util.Date;
@ -10,15 +12,15 @@ import java.util.UUID;
/** /**
* Created by ikalyvas on 2/15/2018. * Created by ikalyvas on 2/15/2018.
*/ */
public class CredentialBuilder extends Builder<Credential> { public class CredentialBuilder extends Builder<CredentialEntity> {
private UUID id; private UUID id;
private UserInfo userInfo; private UserInfo userInfo;
private Integer status; private Status status;
private Integer provider; private ProviderType provider;
private String publicValue; private String publicValue;
@ -42,12 +44,12 @@ public class CredentialBuilder extends Builder<Credential> {
return this; return this;
} }
public CredentialBuilder status(Integer status) { public CredentialBuilder status(Status status) {
this.status = status; this.status = status;
return this; return this;
} }
public CredentialBuilder provider(Integer provider) { public CredentialBuilder provider(ProviderType provider) {
this.provider = provider; this.provider = provider;
return this; return this;
} }
@ -82,15 +84,15 @@ public class CredentialBuilder extends Builder<Credential> {
return this; return this;
} }
public Credential build() { public CredentialEntity build() {
Credential credential = new Credential(); CredentialEntity credential = new CredentialEntity();
credential.setStatus(status); credential.setStatus(status);
credential.setLastUpdateTime(lastUpdateTime); credential.setLastUpdateTime(lastUpdateTime);
credential.setCreationTime(creationTime); credential.setCreationTime(creationTime);
credential.setProvider(provider); credential.setProvider(provider);
credential.setSecret(secret); credential.setSecret(secret);
credential.setPublicValue(publicValue); credential.setPublicValue(publicValue);
credential.setUserInfo(userInfo); credential.setUserId(userInfo.getId());
credential.setId(id); credential.setId(id);
credential.setExternalId(externalId); credential.setExternalId(externalId);
credential.setEmail(email); credential.setEmail(email);

View File

@ -1,7 +1,7 @@
package eu.eudat.logic.builders.entity; package eu.eudat.logic.builders.entity;
import eu.eudat.data.CredentialEntity;
import eu.eudat.logic.builders.Builder; import eu.eudat.logic.builders.Builder;
import eu.eudat.data.entities.Credential;
import eu.eudat.data.entities.DMP; import eu.eudat.data.entities.DMP;
import eu.eudat.data.entities.UserInfo; import eu.eudat.data.entities.UserInfo;
import eu.eudat.data.entities.UserRole; import eu.eudat.data.entities.UserRole;
@ -36,7 +36,7 @@ public class UserInfoBuilder extends Builder<UserInfo> {
private Set<DMP> dmps; private Set<DMP> dmps;
private Set<Credential> credentials = new HashSet<>(); private Set<CredentialEntity> credentials = new HashSet<>();
private Set<UserRole> userRoles = new HashSet<>(); private Set<UserRole> userRoles = new HashSet<>();
@ -92,7 +92,7 @@ public class UserInfoBuilder extends Builder<UserInfo> {
return this; return this;
} }
public UserInfoBuilder credentials(Set<Credential> credentials) { public UserInfoBuilder credentials(Set<CredentialEntity> credentials) {
this.credentials = credentials; this.credentials = credentials;
return this; return this;
} }

View File

@ -1,6 +1,6 @@
package eu.eudat.logic.managers; package eu.eudat.logic.managers;
import eu.eudat.data.entities.Credential; import eu.eudat.data.CredentialEntity;
import eu.eudat.data.entities.EmailConfirmation; import eu.eudat.data.entities.EmailConfirmation;
import eu.eudat.data.entities.UserInfo; import eu.eudat.data.entities.UserInfo;
import eu.eudat.exceptions.emailconfirmation.HasConfirmedEmailException; import eu.eudat.exceptions.emailconfirmation.HasConfirmedEmailException;
@ -45,7 +45,7 @@ public class EmailConfirmationManager {
// Checks if mail is used by another user. If it is, merges the new the old. // Checks if mail is used by another user. If it is, merges the new the old.
Long existingUsers = databaseRepository.getUserInfoDao().asQueryable().where((builder, root) -> builder.equal(root.get("email"), loginConfirmationEmail.getEmail())).count(); Long existingUsers = databaseRepository.getUserInfoDao().asQueryable().where((builder, root) -> builder.equal(root.get("email"), loginConfirmationEmail.getEmail())).count();
if (existingUsers > 0) { if (existingUsers > 0) {
Credential credential = databaseRepository.getCredentialDao().asQueryable().where((builder, root) -> builder.equal(root.get("userInfo"), user)).getSingle(); CredentialEntity credential = databaseRepository.getCredentialDao().asQueryable().where((builder, root) -> builder.equal(root.get("userId"), user.getId())).getSingle();
credential.setEmail(loginConfirmationEmail.getEmail()); credential.setEmail(loginConfirmationEmail.getEmail());
databaseRepository.getCredentialDao().createOrUpdate(credential); databaseRepository.getCredentialDao().createOrUpdate(credential);
UserInfo oldUser = databaseRepository.getUserInfoDao().asQueryable().where((builder, root) -> builder.equal(root.get("email"), loginConfirmationEmail.getEmail())).getSingle(); UserInfo oldUser = databaseRepository.getUserInfoDao().asQueryable().where((builder, root) -> builder.equal(root.get("email"), loginConfirmationEmail.getEmail())).getSingle();
@ -57,7 +57,7 @@ public class EmailConfirmationManager {
user.setEmail(loginConfirmationEmail.getEmail()); user.setEmail(loginConfirmationEmail.getEmail());
databaseRepository.getUserInfoDao().createOrUpdate(user); databaseRepository.getUserInfoDao().createOrUpdate(user);
Credential credential = databaseRepository.getCredentialDao().asQueryable() CredentialEntity credential = databaseRepository.getCredentialDao().asQueryable()
.where((builder, root) -> builder.equal(root.get("userInfo"), user)).getSingle(); .where((builder, root) -> builder.equal(root.get("userInfo"), user)).getSingle();
if(credential.getEmail() == null){ if(credential.getEmail() == null){
credential.setEmail(user.getEmail()); credential.setEmail(user.getEmail());
@ -80,8 +80,8 @@ public class EmailConfirmationManager {
} }
private void mergeNewUserToOld(UserInfo newUser, UserInfo oldUser) { private void mergeNewUserToOld(UserInfo newUser, UserInfo oldUser) {
Credential credential = databaseRepository.getCredentialDao().asQueryable().where((builder, root) -> builder.equal(root.get("userInfo"), newUser)).getSingle(); CredentialEntity credential = databaseRepository.getCredentialDao().asQueryable().where((builder, root) -> builder.equal(root.get("userId"), newUser.getId())).getSingle();
credential.setUserInfo(oldUser); credential.setUserId(oldUser.getId());
databaseRepository.getCredentialDao().createOrUpdate(credential); databaseRepository.getCredentialDao().createOrUpdate(credential);
} }
} }

View File

@ -1,6 +1,6 @@
package eu.eudat.logic.managers; package eu.eudat.logic.managers;
import eu.eudat.data.entities.Credential; import eu.eudat.data.CredentialEntity;
import eu.eudat.data.entities.EmailConfirmation; import eu.eudat.data.entities.EmailConfirmation;
import eu.eudat.data.entities.UserDMP; import eu.eudat.data.entities.UserDMP;
import eu.eudat.data.entities.UserInfo; import eu.eudat.data.entities.UserInfo;
@ -86,8 +86,8 @@ public class MergeEmailConfirmationManager {
@Transactional @Transactional
private void mergeNewUserToOld(UserInfo newUser, UserInfo oldUser, Integer provider) { private void mergeNewUserToOld(UserInfo newUser, UserInfo oldUser, Integer provider) {
Credential credential = databaseRepository.getCredentialDao().asQueryable().where((builder, root) -> builder.and(builder.equal(root.get("userInfo"), oldUser), builder.equal(root.get("provider"), provider))).getSingle(); CredentialEntity credential = databaseRepository.getCredentialDao().asQueryable().where((builder, root) -> builder.and(builder.equal(root.get("userId"), oldUser.getId()), builder.equal(root.get("provider"), provider))).getSingle();
credential.setUserInfo(newUser); credential.setUserId(newUser.getId());
databaseRepository.getCredentialDao().createOrUpdate(credential); databaseRepository.getCredentialDao().createOrUpdate(credential);
List<UserDMP> userDmps = databaseRepository.getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("user"), oldUser)).toList(); List<UserDMP> userDmps = databaseRepository.getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("user"), oldUser)).toList();
userDmps.forEach(userDmp -> { userDmps.forEach(userDmp -> {
@ -128,7 +128,7 @@ public class MergeEmailConfirmationManager {
} }
oldUser.setUserStatus((short)1); oldUser.setUserStatus((short)1);
oldUser.setEmail(null); oldUser.setEmail(null);
List<Credential> credentials = databaseRepository.getCredentialDao().asQueryable().where((builder, root) -> builder.equal(root.get("userInfo"), oldUser)).toList(); List<CredentialEntity> credentials = databaseRepository.getCredentialDao().asQueryable().where((builder, root) -> builder.equal(root.get("userId"), oldUser.getId())).toList();
credentials.forEach(cred -> { credentials.forEach(cred -> {
if (cred.getId() != credential.getId()) { if (cred.getId() != credential.getId()) {
databaseRepository.getCredentialDao().delete(cred); databaseRepository.getCredentialDao().delete(cred);

View File

@ -2,7 +2,7 @@ package eu.eudat.logic.managers;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.data.entities.Credential; import eu.eudat.data.CredentialEntity;
import eu.eudat.data.entities.EmailConfirmation; import eu.eudat.data.entities.EmailConfirmation;
import eu.eudat.data.entities.UserInfo; import eu.eudat.data.entities.UserInfo;
import eu.eudat.exceptions.emailconfirmation.HasConfirmedEmailException; import eu.eudat.exceptions.emailconfirmation.HasConfirmedEmailException;
@ -64,7 +64,7 @@ public class UnlinkEmailConfirmationManager {
@Transactional @Transactional
private void unlinkUser(String emailTobeUnlinked, Integer provider){ private void unlinkUser(String emailTobeUnlinked, Integer provider){
Credential credential = databaseRepository.getCredentialDao().asQueryable() CredentialEntity credential = databaseRepository.getCredentialDao().asQueryable()
.where((builder, root) -> builder.and(builder.equal(root.get("email"), emailTobeUnlinked), builder.equal(root.get("provider"), provider))).getSingle(); .where((builder, root) -> builder.and(builder.equal(root.get("email"), emailTobeUnlinked), builder.equal(root.get("provider"), provider))).getSingle();
if(credential != null) { if(credential != null) {
databaseRepository.getCredentialDao().delete(credential); databaseRepository.getCredentialDao().delete(credential);

View File

@ -1,6 +1,7 @@
package eu.eudat.logic.managers; package eu.eudat.logic.managers;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.data.CredentialEntity;
import eu.eudat.data.dao.criteria.DataManagementPlanCriteria; import eu.eudat.data.dao.criteria.DataManagementPlanCriteria;
import eu.eudat.data.dao.entities.UserInfoDao; import eu.eudat.data.dao.entities.UserInfoDao;
import eu.eudat.data.entities.*; import eu.eudat.data.entities.*;
@ -89,7 +90,7 @@ public class UserManager {
public List<UserCredential> getCredentials(UUID userId) { public List<UserCredential> getCredentials(UUID userId) {
List<UserCredential> results = new ArrayList<>(); List<UserCredential> results = new ArrayList<>();
eu.eudat.data.entities.UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userId); eu.eudat.data.entities.UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userId);
List<Credential> credentials = apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao().asQueryable().where((builder, root) -> builder.equal(root.get("userInfo"), user)).toList(); List<CredentialEntity> credentials = apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao().asQueryable().where((builder, root) -> builder.equal(root.get("userInfo"), user)).toList();
credentials.forEach(credential -> { credentials.forEach(credential -> {
UserCredential userCredential = new UserCredential(); UserCredential userCredential = new UserCredential();
userCredential.setEmail(credential.getEmail()); userCredential.setEmail(credential.getEmail());

View File

@ -1,18 +1,20 @@
package eu.eudat.models.data.userinfo; package eu.eudat.models.data.userinfo;
import eu.eudat.commons.enums.ProviderType;
public class UserCredential { public class UserCredential {
private String email; private String email;
private Integer provider; private ProviderType provider;
public String getEmail() { public String getEmail() {
return email; return email;
} }
public void setEmail(String email) { public void setEmail(String email) {
this.email = email; this.email = email;
} }
public Integer getProvider() { public ProviderType getProvider() {
return provider; return provider;
} }
public void setProvider(Integer provider) { public void setProvider(ProviderType provider) {
this.provider = provider; this.provider = provider;
} }

View File

@ -35,11 +35,11 @@ export class LanguageService {
public getCurrentLanguageJSON(): Observable<HttpResponse<Blob>> { public getCurrentLanguageJSON(): Observable<HttpResponse<Blob>> {
const params = new BaseHttpParams(); const params = new BaseHttpParams();
params.interceptorContext = { // params.interceptorContext = {
excludedInterceptors: [ // excludedInterceptors: [
InterceptorType.AuthToken, // InterceptorType.AuthToken,
] // ]
}; // };
return this.http.get(`${this.publicApiBase}/${this.currentLanguage}`, { params: params, responseType: 'blob', observe: 'response' }); return this.http.get(`${this.publicApiBase}/${this.currentLanguage}`, { params: params, responseType: 'blob', observe: 'response' });
} }

View File

@ -17,11 +17,11 @@ export class TranslateServerLoader implements TranslateLoader{
} }
getTranslation(lang: string): Observable<any> { getTranslation(lang: string): Observable<any> {
const params = new BaseHttpParams(); const params = new BaseHttpParams();
params.interceptorContext = { // params.interceptorContext = {
excludedInterceptors: [ // excludedInterceptors: [
InterceptorType.AuthToken, // InterceptorType.AuthToken,
] // ]
}; // };
return this.http.get(`${this.apiBase}/${lang}`, { params: params }); return this.http.get(`${this.apiBase}/${lang}`, { params: params });
} }
} }

View File

@ -52,12 +52,12 @@
], ],
"keycloak": { "keycloak": {
"enabled": true, "enabled": true,
"address": "http://dev03.local.cite.gr:60201/auth", "address": "",
"realm": "dmp-development", "realm": "",
"flow": "standard", "flow": "standard",
"clientId": "dmp_webapp", "clientId": "",
"silentCheckSsoRedirectUri": "http://localhost:4200/assets/silent-check-sso.html", "silentCheckSsoRedirectUri": "http://localhost:4200/assets/silent-check-sso.html",
"scope": "openid profile email address phone dmp_web", "scope": "openid profile email address phone",
"clientSecret": null, "clientSecret": null,
"grantType": "code" "grantType": "code"
}, },