This commit is contained in:
Diamantis Tziotzios 2019-07-15 18:50:23 +03:00
commit e3e3c0fa1b
91 changed files with 2095 additions and 493 deletions

View File

@ -0,0 +1,6 @@
package eu.eudat.data.dao.criteria;
import eu.eudat.data.entities.LoginConfirmationEmail;
public class LoginConfirmationEmailCriteria extends Criteria<LoginConfirmationEmail>{
}

View File

@ -0,0 +1,13 @@
package eu.eudat.data.dao.entities;
import eu.eudat.data.dao.DatabaseAccessLayer;
import eu.eudat.data.dao.criteria.LoginConfirmationEmailCriteria;
import eu.eudat.data.entities.LoginConfirmationEmail;
import eu.eudat.queryable.QueryableList;
import java.util.UUID;
public interface LoginConfirmationEmailDao extends DatabaseAccessLayer<LoginConfirmationEmail, UUID> {
QueryableList<LoginConfirmationEmail> getWithCriteria(LoginConfirmationEmailCriteria criteria);
}

View File

@ -0,0 +1,56 @@
package eu.eudat.data.dao.entities;
import eu.eudat.data.dao.DatabaseAccess;
import eu.eudat.data.dao.criteria.LoginConfirmationEmailCriteria;
import eu.eudat.data.dao.databaselayer.service.DatabaseService;
import eu.eudat.data.entities.LoginConfirmationEmail;
import eu.eudat.queryable.QueryableList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@Service("LoginConfirmationEmailDao")
public class LoginConfirmationEmailDaoImpl extends DatabaseAccess<LoginConfirmationEmail> implements LoginConfirmationEmailDao {
@Autowired
public LoginConfirmationEmailDaoImpl(DatabaseService<LoginConfirmationEmail> databaseService) {
super(databaseService);
}
@Override
public QueryableList<LoginConfirmationEmail> getWithCriteria(LoginConfirmationEmailCriteria criteria) {
return null;
}
@Override
public LoginConfirmationEmail createOrUpdate(LoginConfirmationEmail item) {
return this.getDatabaseService().createOrUpdate(item, LoginConfirmationEmail.class);
}
@Override
public CompletableFuture<LoginConfirmationEmail> createOrUpdateAsync(LoginConfirmationEmail item) {
return null;
}
@Override
public LoginConfirmationEmail find(UUID id) {
return this.getDatabaseService().getQueryable(LoginConfirmationEmail.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
}
@Override
public LoginConfirmationEmail find(UUID id, String hint) {
throw new UnsupportedOperationException();
}
@Override
public void delete(LoginConfirmationEmail item) {
throw new UnsupportedOperationException();
}
@Override
public QueryableList<LoginConfirmationEmail> asQueryable() {
return this.getDatabaseService().getQueryable(LoginConfirmationEmail.class);
}
}

View File

@ -167,6 +167,9 @@ public class DMP implements DataEntity<DMP, UUID> {
@Convert(converter = DateToUTCConverter.class)
private Date publishedAt;
@Column(name = "\"DOI\"")
private String doi;
public String getDescription() {
return description;
@ -315,7 +318,14 @@ public class DMP implements DataEntity<DMP, UUID> {
this.publishedAt = publishedAt;
}
@Override
public String getDoi() {
return doi;
}
public void setDoi(String doi) {
this.doi = doi;
}
@Override
public void update(DMP entity) {
this.associatedDmps = entity.associatedDmps;
this.label = entity.getLabel();
@ -333,6 +343,7 @@ public class DMP implements DataEntity<DMP, UUID> {
if (entity.getStatus().equals(DMPStatus.FINALISED.getValue())) this.setFinalizedAt(new Date());
if (entity.isPublic) this.setPublishedAt(new Date());
if (entity.getUsers() != null) this.users = entity.getUsers();
if (entity.getDoi() != null && entity.getDoi().trim().isEmpty()) this.doi = entity.doi;
}
@Override

View File

@ -0,0 +1,94 @@
package eu.eudat.data.entities;
import eu.eudat.data.converters.DateToUTCConverter;
import eu.eudat.queryable.queryableentity.DataEntity;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Entity
@Table(name = "\"LoginConfirmationEmail\"")
public class LoginConfirmationEmail implements DataEntity<LoginConfirmationEmail, UUID> {
@Id
@GeneratedValue
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(name = "\"ID\"", updatable = false, nullable = false)
private UUID id;
@Column(name = "\"email\"", nullable = false)
private String email;
@Column(name = "\"isConfirmed\"", nullable = false)
private boolean isConfirmed;
@Column(name = "\"token\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)")
private UUID token;
@Column(name = "\"userId\"", nullable = false)
private UUID userId;
@Column(name = "\"expiresAt\"", nullable = false)
@Convert(converter = DateToUTCConverter.class)
private Date expiresAt;
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 boolean getIsConfirmed() {
return isConfirmed;
}
public void setIsConfirmed(boolean confirmed) {
isConfirmed = confirmed;
}
public UUID getToken() {
return token;
}
public void setToken(UUID token) {
this.token = token;
}
public UUID getUserId() {
return userId;
}
public void setUserId(UUID userId) {
this.userId = userId;
}
public Date getExpiresAt() {
return expiresAt;
}
public void setExpiresAt(Date expiresAt) {
this.expiresAt = expiresAt;
}
@Override
public void update(LoginConfirmationEmail entity) {
}
@Override
public UUID getKeys() {
return null;
}
@Override
public LoginConfirmationEmail buildFromTuple(List<Tuple> tuple, List<String> fields, String base) {
return null;
}
}

View File

@ -3,7 +3,7 @@ package eu.eudat.configurations;
import eu.eudat.controllers.interceptors.RequestInterceptor;
import eu.eudat.logic.handlers.PrincipalArgumentResolver;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.AuthenticationService;
import eu.eudat.logic.services.operations.authentication.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
@ -17,24 +17,26 @@ import java.util.List;
@Configuration
public class WebMVCConfiguration extends WebMvcConfigurerAdapter {
private ApiContext apiContext;
private ApiContext apiContext;
private AuthenticationService authenticationService;
private AuthenticationService verifiedUserAuthenticationService;
private AuthenticationService nonVerifiedUserAuthenticationService;
@Autowired
public WebMVCConfiguration(ApiContext apiContext, AuthenticationService authenticationService) {
this.apiContext = apiContext;
this.authenticationService = authenticationService;
}
@Autowired
public WebMVCConfiguration(ApiContext apiContext, AuthenticationService verifiedUserAuthenticationService, AuthenticationService nonVerifiedUserAuthenticationService) {
this.apiContext = apiContext;
this.verifiedUserAuthenticationService = verifiedUserAuthenticationService;
this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService;
}
@Autowired
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new PrincipalArgumentResolver(authenticationService));
}
@Autowired
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new PrincipalArgumentResolver(verifiedUserAuthenticationService, nonVerifiedUserAuthenticationService));
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RequestInterceptor(this.apiContext.getHelpersService().getLoggerService()));
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RequestInterceptor(this.apiContext.getHelpersService().getLoggerService()));
}
}

View File

@ -257,4 +257,14 @@ public class DMPs extends BaseController {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DMP>().status(ApiMessageCode.ERROR_MESSAGE).message(e.getMessage()));
}
}
@RequestMapping(method = RequestMethod.POST, value = {"/createZenodoDoi/{id}"})
public ResponseEntity<ResponseItem<String>> createZenodoDoi(@PathVariable String id, Principal principal) {
try {
String zenodoDOI = this.dataManagementPlanManager.createZenodoDoi(UUID.fromString(id), principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<String>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully created DOI for Data Datamanagement Plan in question.").payload(zenodoDOI));
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<String>().status(ApiMessageCode.ERROR_MESSAGE).message(e.getMessage()));
}
}
}

View File

@ -0,0 +1,54 @@
package eu.eudat.controllers;
import eu.eudat.exceptions.emailconfirmation.HasConfirmedEmailException;
import eu.eudat.exceptions.emailconfirmation.TokenExpiredException;
import eu.eudat.logic.managers.EmailConfirmationManager;
import eu.eudat.logic.security.CustomAuthenticationProvider;
import eu.eudat.logic.services.operations.authentication.AuthenticationService;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.transaction.Transactional;
@RestController
@CrossOrigin
@RequestMapping(value = "api/emailConfirmation")
public class EmailConfirmation {
private EmailConfirmationManager emailConfirmationManager;
@Autowired
public EmailConfirmation(EmailConfirmationManager emailConfirmationManager) {
this.emailConfirmationManager = emailConfirmationManager;
}
@Transactional
@RequestMapping(method = RequestMethod.GET, value = {"/{emailToken}"})
public @ResponseBody
ResponseEntity<ResponseItem> emailConfirmation(@PathVariable(value = "emailToken") String token) {
try {
this.emailConfirmationManager.confirmEmail(token);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
} catch
(HasConfirmedEmailException | TokenExpiredException ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE));
}
}
@Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity sendConfirmatioEmail(@RequestBody String email, Principal principal) {
try {
this.emailConfirmationManager.sendConfirmationEmail(email, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
} catch (Exception ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE));
}
}
}

View File

@ -1,13 +1,17 @@
package eu.eudat.controllers;
import eu.eudat.core.logger.Logger;
import eu.eudat.exceptions.security.NullEmailException;
import eu.eudat.logic.managers.UserManager;
import eu.eudat.logic.security.CustomAuthenticationProvider;
import eu.eudat.logic.security.validators.b2access.B2AccessTokenValidator;
import eu.eudat.logic.security.validators.b2access.helpers.B2AccessRequest;
import eu.eudat.logic.security.validators.b2access.helpers.B2AccessResponseToken;
import eu.eudat.logic.security.validators.orcid.ORCIDTokenValidator;
import eu.eudat.logic.security.validators.orcid.helpers.ORCIDRequest;
import eu.eudat.logic.security.validators.orcid.helpers.ORCIDResponseToken;
import eu.eudat.logic.security.validators.twitter.TwitterTokenValidator;
import eu.eudat.logic.services.operations.AuthenticationServiceImpl;
import eu.eudat.logic.services.operations.authentication.AuthenticationService;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.login.Credentials;
import eu.eudat.models.data.login.LoginInfo;
@ -29,24 +33,23 @@ import java.security.GeneralSecurityException;
public class Login {
private CustomAuthenticationProvider customAuthenticationProvider;
private AuthenticationServiceImpl authenticationServiceImpl;
private AuthenticationService nonVerifiedUserAuthenticationService;
private TwitterTokenValidator twitterTokenValidator;
private B2AccessTokenValidator b2AccessTokenValidator;
private ORCIDTokenValidator orcidTokenValidator;
private Logger logger;
private UserManager userManager;
@Autowired
public Login(CustomAuthenticationProvider customAuthenticationProvider, AuthenticationServiceImpl authenticationServiceImpl,
TwitterTokenValidator twitterTokenValidator, B2AccessTokenValidator b2AccessTokenValidator,
public Login(CustomAuthenticationProvider customAuthenticationProvider, AuthenticationService nonVerifiedUserAuthenticationService,
TwitterTokenValidator twitterTokenValidator, B2AccessTokenValidator b2AccessTokenValidator, ORCIDTokenValidator orcidTokenValidator,
UserManager userManager ,Logger logger) {
this.customAuthenticationProvider = customAuthenticationProvider;
this.authenticationServiceImpl = authenticationServiceImpl;
this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService;
this.twitterTokenValidator = twitterTokenValidator;
this.b2AccessTokenValidator = b2AccessTokenValidator;
this.orcidTokenValidator = orcidTokenValidator;
this.logger = logger;
this.userManager = userManager;
}
@ -54,7 +57,7 @@ public class Login {
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/externallogin"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Principal>> externallogin(@RequestBody LoginInfo credentials) throws GeneralSecurityException {
ResponseEntity<ResponseItem<Principal>> externallogin(@RequestBody LoginInfo credentials) throws GeneralSecurityException, NullEmailException {
this.logger.info(credentials, "Trying To Login With " + credentials.getProvider());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().payload(customAuthenticationProvider.authenticate(credentials)).status(ApiMessageCode.SUCCESS_MESSAGE));
}
@ -62,9 +65,9 @@ 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) {
ResponseEntity<ResponseItem<Principal>> nativelogin(@RequestBody Credentials credentials) throws NullEmailException {
this.logger.info(credentials.getUsername(), "Trying To Login");
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().payload(userManager.authenticate(this.authenticationServiceImpl, credentials)).status(ApiMessageCode.SUCCESS_MESSAGE));
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().payload(userManager.authenticate(this.nonVerifiedUserAuthenticationService, credentials)).status(ApiMessageCode.SUCCESS_MESSAGE));
}
@RequestMapping(method = RequestMethod.GET, value = {"/twitterRequestToken"}, produces = "application/json")
@ -79,18 +82,24 @@ public class Login {
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<B2AccessResponseToken>().payload(this.b2AccessTokenValidator.getAccessToken(b2AccessRequest)).status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.POST, value = {"/orcidRequestToken"}, produces = "application/json", consumes = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<ORCIDResponseToken>> ORCIDRequestToken(@RequestBody ORCIDRequest orcidRequest) {
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<ORCIDResponseToken>().payload(this.orcidTokenValidator.getAccessToken(orcidRequest)).status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.POST, value = {"/me"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Principal>> authMe(Principal principal) {
ResponseEntity<ResponseItem<Principal>> authMe(Principal principal) throws NullEmailException {
this.logger.info(principal, "Getting Me");
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().payload(this.authenticationServiceImpl.Touch(principal.getToken())).status(ApiMessageCode.NO_MESSAGE));
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().payload(this.nonVerifiedUserAuthenticationService.Touch(principal.getToken())).status(ApiMessageCode.NO_MESSAGE));
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/logout"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Principal>> logout(Principal principal) {
this.authenticationServiceImpl.Logout(principal.getToken());
this.nonVerifiedUserAuthenticationService.Logout(principal.getToken());
this.logger.info(principal, "Logged Out");
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().status(ApiMessageCode.NO_MESSAGE));
}

View File

@ -0,0 +1,19 @@
package eu.eudat.controllers.controllerhandler;
import eu.eudat.exceptions.security.NullEmailException;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.types.ApiMessageCode;
import org.springframework.core.annotation.Order;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
@Order(2)
public class ControllerUserNullEmailHandler {
@ExceptionHandler(NullEmailException.class)
public ResponseEntity nullEmailException(Exception ex) throws Exception {
return ResponseEntity.status(ApiMessageCode.NULL_EMAIL.getValue()).body("");
}
}

View File

@ -0,0 +1,8 @@
package eu.eudat.exceptions.emailconfirmation;
public class HasConfirmedEmailException extends Exception {
public HasConfirmedEmailException(String msg) {
super(msg);
}
}

View File

@ -0,0 +1,8 @@
package eu.eudat.exceptions.emailconfirmation;
public class TokenExpiredException extends Exception {
public TokenExpiredException(String msg) {
super(msg);
}
}

View File

@ -0,0 +1,8 @@
package eu.eudat.exceptions.security;
public class NullEmailException extends RuntimeException {
public NullEmailException() {
super();
}
}

View File

@ -2,13 +2,15 @@ package eu.eudat.logic.handlers;
import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.operations.AuthenticationService;
import eu.eudat.logic.services.operations.authentication.AuthenticationService;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.Authorities;
import org.apache.catalina.connector.RequestFacade;
import org.apache.tomcat.util.buf.MessageBytes;
import org.springframework.core.MethodParameter;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
@ -18,46 +20,51 @@ import java.util.*;
public final class PrincipalArgumentResolver implements HandlerMethodArgumentResolver {
private AuthenticationService authenticationService;
private AuthenticationService verifiedUserAuthenticationService;
private AuthenticationService nonVerifiedUserAuthenticationService;
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.getParameterType().equals(Principal.class);
}
public PrincipalArgumentResolver(AuthenticationService verifiedUserAuthenticationService, AuthenticationService nonVerifiedUserAuthenticationService) {
this.verifiedUserAuthenticationService = verifiedUserAuthenticationService;
this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService;
}
@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 && claimList.size() == 1 && claimList.get(0).equals(Authorities.ANONYMOUS))
return new Principal();
if (token == null) throw new UnauthorisedException("Authentication Information Is Missing");
UUID authToken;
try {
authToken = UUID.fromString(token);
} catch (IllegalArgumentException ex) {
throw new UnauthorisedException("Authentication Information Is Missing");
}
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.getParameterType().equals(Principal.class);
}
Principal principal = this.authenticationService.Touch(authToken);
if (principal == null) throw new UnauthorisedException("Authentication Information Missing");
if (!claimList.contains(Authorities.ANONYMOUS) && !principal.isAuthorized(claimList))
throw new UnauthorisedException("You are not Authorized For this Action");
@Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
String token = nativeWebRequest.getHeader("AuthToken");
return principal;
}
Boolean checkMailNull = ((ServletWebRequest) nativeWebRequest).getRequest().getRequestURI().startsWith("/api/emailConfirmation");
AuthenticationService authenticationService = checkMailNull ? this.nonVerifiedUserAuthenticationService : this.verifiedUserAuthenticationService;
public PrincipalArgumentResolver(AuthenticationService authenticationService) {
this.authenticationService = authenticationService;
}
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 (claimList.size() == 1 && claimList.get(0).equals(Authorities.ANONYMOUS))
return new Principal();
if (token == null) throw new UnauthorisedException("Authentication Information Is Missing");
UUID authToken;
try {
authToken = UUID.fromString(token);
} catch (IllegalArgumentException ex) {
throw new UnauthorisedException("Authentication Information Is Missing");
}
Principal principal = authenticationService.Touch(authToken);
if (principal == null) throw new UnauthorisedException("Authentication Information Missing");
if (!claimList.contains(Authorities.ANONYMOUS) && !principal.isAuthorized(claimList))
throw new UnauthorisedException("You are not Authorized For this Action");
private Date addADay(Date date) {
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.DATE, 1);
dt = c.getTime();
return dt;
}
return principal;
}
private Date addADay(Date date) {
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.DATE, 1);
dt = c.getTime();
return dt;
}
}

View File

@ -49,8 +49,11 @@ import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.Document;
@ -221,18 +224,27 @@ public class DataManagementPlanManager {
// Custom style for the Dataset title.
//wordBuilder.addParagraphContent("Title: " + datasetEntity.getLabel(), document, ParagraphStyle.HEADER1, BigInteger.ZERO);
XWPFParagraph datasetLabelParagraph = document.createParagraph();
XWPFRun runDatasetTitle1 = datasetLabelParagraph.createRun();
runDatasetTitle1.setText("Title: ");
runDatasetTitle1.setBold(true);
runDatasetTitle1.setFontSize(12);
XWPFRun runDatasetTitle = datasetLabelParagraph.createRun();
runDatasetTitle.setText(datasetEntity.getLabel());
runDatasetTitle.setColor("2E75B6");
runDatasetTitle.setBold(true);
runDatasetTitle.setFontSize(12);
XWPFParagraph datasetTemplateParagraph = document.createParagraph();
XWPFRun runDatasetTemplate1 = datasetTemplateParagraph.createRun();
runDatasetTemplate1.setText("Template: ");
runDatasetTemplate1.setBold(true);
runDatasetTemplate1.setFontSize(12);
XWPFRun runDatasetTemplate = datasetTemplateParagraph.createRun();
runDatasetTemplate.setText(datasetEntity.getProfile().getLabel());
runDatasetTemplate.setColor("2E75B6");
runDatasetTemplate.setBold(true);
runDatasetTemplate.setFontSize(12);
wordBuilder.addParagraphContent(datasetEntity.getDescription(), document, ParagraphStyle.TEXT, BigInteger.ZERO);
wordBuilder.addParagraphContent("Dataset Description", document, ParagraphStyle.HEADER1, BigInteger.ZERO);
PagedDatasetProfile pagedDatasetProfile = datasetManager.getPagedProfile(dataset, datasetEntity);
@ -248,7 +260,7 @@ public class DataManagementPlanManager {
});
String fileName = dmpEntity.getLabel();
fileName = fileName.replaceAll("[^a-zA-Z0-9+ ]", "");
File exportFile = new File(environment.getProperty("configuration.exportUrl") + fileName + ".docx");
File exportFile = new File(fileName + ".docx");
FileOutputStream out = new FileOutputStream(exportFile);
document.write(out);
out.close();
@ -958,4 +970,58 @@ public class DataManagementPlanManager {
private boolean isUserOwnerOfDmp(DMP dmp, Principal principal) {
return (dmp.getUsers().stream().filter(userDMP -> userDMP.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue())).findFirst().get().getUser().getId()).equals(principal.getId());
}
public String createZenodoDoi(UUID id, Principal principal) throws Exception {
DMP dmp = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(id);
if (!isUserOwnerOfDmp(dmp, principal))
throw new Exception("User is not authorized to invoke this action");
if (!dmp.getStatus().equals(DMP.DMPStatus.FINALISED.getValue()))
throw new Exception("DMP is not finalized");
if (!dmp.getDoi().trim().isEmpty())
throw new Exception("DMP already has a DOI");
// First step, post call to Zenodo, to create the entry.
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("accept", "application/json");
headers.setContentType(MediaType.APPLICATION_JSON);
String createData = "{\n" +
" \"metadata\": {\n" +
" \"title\": \"" + dmp.getLabel() + "\",\n" +
" \"upload_type\": \"publication\",\n" +
" \"publication_type\": \"datamanagementplan\",\n" +
" \"description\": \"" + dmp.getDescription() + "\",\n" +
" \"creators\": [{\n" +
" \t\t\"name\": \"Kolokythas, Georgios\",\n" +
" \t\t\"affiliation\": \"OpenDMP\"}]\n" +
" }\n" +
"}";
HttpEntity<String> request = new HttpEntity<>(createData, headers);
String createUrl = this.environment.getProperty("zenodo.url") + "deposit/depositions" + "?access_token=" + this.environment.getProperty("zenodo.access_token");
Map createResponse = restTemplate.postForObject(createUrl, request, Map.class);
// Second step, add the file to the entry.
HttpHeaders fileHeaders = new HttpHeaders();
fileHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
LinkedMultiValueMap<String, Object> addFileMap = new LinkedMultiValueMap<>();
File file = getWordDocument(id.toString());
addFileMap.add("filename", file.getName());
FileSystemResource fileSystemResource = new FileSystemResource(file);
addFileMap.add("file", fileSystemResource);
HttpEntity<MultiValueMap<String, Object>> addFileMapRequest = new HttpEntity<>(addFileMap, fileHeaders);
LinkedHashMap<String, String> links = (LinkedHashMap<String, String>) createResponse.get("links");
String addFileUrl = links.get("files") + "?access_token=" + this.environment.getProperty("zenodo.access_token");
ResponseEntity<String> addFileResponse = restTemplate.postForEntity(addFileUrl, addFileMapRequest, String.class);
Files.deleteIfExists(file.toPath());
// Third post call to Zenodo to publish the entry and return the DOI.
String publishUrl = links.get("publish") + "?access_token=" + this.environment.getProperty("zenodo.access_token");
Map<String, Object> publishResponce = restTemplate.postForObject(publishUrl, "", Map.class);
dmp.setDoi((String) publishResponce.get("conceptdoi"));
apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(dmp);
return (String) publishResponce.get("conceptdoi");
}
}

View File

@ -250,7 +250,7 @@ public class DatasetManager {
visibilityRuleService.buildVisibilityContext(pagedDatasetProfile.getRules());
wordBuilder.build(document, pagedDatasetProfile, visibilityRuleService);
String label = datasetEntity.getLabel().replaceAll("[^a-zA-Z0-9+ ]", "");
File exportFile = new File(environment.getProperty("configuration.exportUrl") + label + ".docx");
File exportFile = new File(label + ".docx");
FileOutputStream out = new FileOutputStream(exportFile);
document.write(out);
out.close();
@ -291,7 +291,7 @@ public class DatasetManager {
byte[] queueResult = new RestTemplate().postForObject(environment.getProperty("pdf.converter.url") + "convert/office"
, requestEntity, byte[].class);
File resultPdf = new File(environment.getProperty("configuration.exportUrl") + label + ".pdf");
File resultPdf = new File(label + ".pdf");
FileOutputStream output = new FileOutputStream(resultPdf);
IOUtils.write(queueResult, output);
output.close();

View File

@ -60,7 +60,7 @@ public class DocumentManager {
visibilityRuleService.setProperties(properties);
visibilityRuleService.buildVisibilityContext(pagedDatasetProfile.getRules());
wordBuilder.build(document, pagedDatasetProfile, visibilityRuleService);
File exportFile = new File(environment.getProperty("configuration.exportUrl") + dataset.getLabel() + ".docx");
File exportFile = new File(dataset.getLabel() + ".docx");
FileOutputStream out = new FileOutputStream(exportFile);
document.write(out);
out.close();

View File

@ -0,0 +1,50 @@
package eu.eudat.logic.managers;
import eu.eudat.data.entities.LoginConfirmationEmail;
import eu.eudat.data.entities.UserInfo;
import eu.eudat.exceptions.emailconfirmation.HasConfirmedEmailException;
import eu.eudat.exceptions.emailconfirmation.TokenExpiredException;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.security.Principal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.UUID;
@Component
public class EmailConfirmationManager {
private ApiContext apiContext;
@Autowired
public EmailConfirmationManager(ApiContext apiContext) {
this.apiContext = apiContext;
}
public void confirmEmail(String token) throws TokenExpiredException, HasConfirmedEmailException {
LoginConfirmationEmail loginConfirmationEmail = apiContext.getOperationsContext()
.getDatabaseRepository().getLoginConfirmationEmailDao().asQueryable()
.where((builder, root) -> builder.equal(root.get("token"), UUID.fromString(token))).getSingle();
if (loginConfirmationEmail.getExpiresAt().compareTo(new Date()) < 0)
throw new TokenExpiredException("Token has expired.");
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().asQueryable()
.where((builder, root) -> builder.equal(root.get("id"), loginConfirmationEmail.getUserId())).getSingle();
if (user.getEmail() != null)
throw new HasConfirmedEmailException("User already has confirmed his Email.");
loginConfirmationEmail.setIsConfirmed(true);
user.setEmail(loginConfirmationEmail.getEmail());
apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().createOrUpdate(user);
apiContext.getOperationsContext().getDatabaseRepository().getLoginConfirmationEmailDao().createOrUpdate(loginConfirmationEmail);
}
public void sendConfirmationEmail(String email, Principal principal) throws HasConfirmedEmailException {
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
if (user.getEmail() != null)
throw new HasConfirmedEmailException("User already has confirmed his Email.");
apiContext.getUtilitiesService().getConfirmationEmailService().createConfirmationEmail(
apiContext.getOperationsContext().getDatabaseRepository().getLoginConfirmationEmailDao(),
apiContext.getUtilitiesService().getMailService(),
email,
principal.getId());
}
}

View File

@ -6,11 +6,12 @@ import eu.eudat.data.entities.DMP;
import eu.eudat.data.entities.UserInfo;
import eu.eudat.data.entities.UserRole;
import eu.eudat.data.query.items.table.userinfo.UserInfoTableRequestItem;
import eu.eudat.exceptions.security.NullEmailException;
import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.logic.builders.entity.UserRoleBuilder;
import eu.eudat.logic.builders.model.models.DataTableDataBuilder;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.AuthenticationServiceImpl;
import eu.eudat.logic.services.operations.authentication.AuthenticationService;
import eu.eudat.logic.utilities.builders.XmlBuilder;
import eu.eudat.models.HintedModelFactory;
import eu.eudat.models.data.dmp.DataManagementPlan;
@ -90,7 +91,7 @@ public class UserManager {
.createOrUpdate(userInfo);
}
public Principal authenticate(AuthenticationServiceImpl authenticationServiceImpl, Credentials credentials) {
public Principal authenticate(AuthenticationService authenticationServiceImpl, Credentials credentials) throws NullEmailException {
Principal principal = authenticationServiceImpl.Touch(credentials);
if (principal == null) throw new UnauthorisedException("Could not Sign In User");
return principal;

View File

@ -1,6 +1,7 @@
package eu.eudat.logic.security;
import eu.eudat.exceptions.security.NonValidTokenException;
import eu.eudat.exceptions.security.NullEmailException;
import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.models.data.login.LoginInfo;
import eu.eudat.models.data.security.Principal;
@ -18,7 +19,7 @@ public class CustomAuthenticationProvider {
@Autowired
private TokenValidatorFactory tokenValidatorFactory;
public Principal authenticate(LoginInfo credentials) throws GeneralSecurityException {
public Principal authenticate(LoginInfo credentials) throws GeneralSecurityException, NullEmailException {
String token = credentials.getTicket();
try {
Principal principal = this.tokenValidatorFactory.getProvider(credentials.getProvider()).validateToken(credentials);
@ -30,6 +31,9 @@ public class CustomAuthenticationProvider {
} catch (IOException e) {
e.printStackTrace();
throw new UnauthorisedException("IO Exeption");
} catch (NullEmailException e) {
e.printStackTrace();
throw new NullEmailException();
}
}
}

View File

@ -1,4 +1,4 @@
package eu.eudat.logic.security.customproviders;
package eu.eudat.logic.security.customproviders.B2Access;
import eu.eudat.logic.security.validators.b2access.helpers.B2AccessResponseToken;

View File

@ -1,4 +1,4 @@
package eu.eudat.logic.security.customproviders;
package eu.eudat.logic.security.customproviders.B2Access;
import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64;
import eu.eudat.logic.security.validators.b2access.helpers.B2AccessResponseToken;

View File

@ -1,4 +1,4 @@
package eu.eudat.logic.security.customproviders;
package eu.eudat.logic.security.customproviders.B2Access;
/**
* Created by ikalyvas on 2/22/2018.

View File

@ -0,0 +1,9 @@
package eu.eudat.logic.security.customproviders.ORCID;
import eu.eudat.logic.security.validators.orcid.helpers.ORCIDResponseToken;
public interface ORCIDCustomProvider {
ORCIDUser getUser(String accessToken);
ORCIDResponseToken getAccessToken(String code, String redirectUri, String clientId, String clientSecret);
}

View File

@ -0,0 +1,65 @@
package eu.eudat.logic.security.customproviders.ORCID;
import eu.eudat.logic.security.validators.orcid.helpers.ORCIDResponseToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
@Component("ORCIDCustomProvider")
public class ORCIDCustomProviderImpl implements ORCIDCustomProvider {
private Environment environment;
@Autowired
public ORCIDCustomProviderImpl(Environment environment) {
this.environment = environment;
}
@Override
public ORCIDResponseToken getAccessToken(String code, String redirectUri, String clientId, String clientSecret) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("accept", "application/json");
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("client_id", this.environment.getProperty("orcid.login.client_id"));
map.add("client_secret", this.environment.getProperty("orcid.login.client_secret"));
map.add("grant_type", "authorization_code");
map.add("code", code);
map.add("redirect_uri", redirectUri);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
Map<String, Object> values = restTemplate.postForObject(this.environment.getProperty("orcid.login.access_token_url"), request, Map.class);
ORCIDResponseToken orcidResponseToken = new ORCIDResponseToken();
orcidResponseToken.setOrcidId((String) values.get("orcid"));
orcidResponseToken.setName((String) values.get("name"));
orcidResponseToken.setAccessToken((String) values.get("access_token"));
return orcidResponseToken;
}
@Override
public ORCIDUser getUser(String accessToken) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = this.createBearerAuthHeaders(accessToken);
HttpEntity<String> entity = new HttpEntity<>(headers);
//Map<String, Object> values = restTemplate.exchange(this.environment.getProperty("orcid.login.access_token_url"),);
return null;
}
private HttpHeaders createBearerAuthHeaders(String accessToken) {
return new HttpHeaders() {{
String authHeader = "Bearer " + accessToken;
set("Authorization", authHeader);
}};
}
}

View File

@ -0,0 +1,38 @@
package eu.eudat.logic.security.customproviders.ORCID;
import java.util.Map;
public class ORCIDUser {
private String orcidId;
private String name;
private String email;
public String getOrcidId() {
return orcidId;
}
public void setOrcidId(String orcidId) {
this.orcidId = orcidId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public ORCIDUser getOrcidUser(Object data) {
this.orcidId = (String) ((Map) data).get("orcidId");
this.name = (String) ((Map) data).get("name");
this.email = (String) ((Map) data).get("email");
return this;
}
}

View File

@ -1,6 +1,7 @@
package eu.eudat.logic.security.validators;
import eu.eudat.exceptions.security.NonValidTokenException;
import eu.eudat.exceptions.security.NullEmailException;
import eu.eudat.models.data.login.LoginInfo;
import eu.eudat.models.data.security.Principal;
@ -9,6 +10,6 @@ import java.security.GeneralSecurityException;
public interface TokenValidator {
Principal validateToken(LoginInfo credentials) throws NonValidTokenException, IOException, GeneralSecurityException;
Principal validateToken(LoginInfo credentials) throws NonValidTokenException, IOException, GeneralSecurityException, NullEmailException;
}

View File

@ -1,14 +1,15 @@
package eu.eudat.logic.security.validators;
import eu.eudat.logic.security.customproviders.B2AccessCustomProvider;
import eu.eudat.logic.security.customproviders.B2Access.B2AccessCustomProvider;
import eu.eudat.logic.security.customproviders.ORCID.ORCIDCustomProvider;
import eu.eudat.logic.security.validators.b2access.B2AccessTokenValidator;
import eu.eudat.logic.security.validators.facebook.FacebookTokenValidator;
import eu.eudat.logic.security.validators.google.GoogleTokenValidator;
import eu.eudat.logic.security.validators.linkedin.LinkedInTokenValidator;
import eu.eudat.logic.security.validators.orcid.ORCIDTokenValidator;
import eu.eudat.logic.security.validators.twitter.TwitterTokenValidator;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.AuthenticationService;
import eu.eudat.logic.services.operations.AuthenticationServiceImpl;
import eu.eudat.logic.services.operations.authentication.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
@ -17,7 +18,7 @@ import org.springframework.stereotype.Service;
@Service("tokenValidatorFactory")
public class TokenValidatorFactoryImpl implements TokenValidatorFactory {
public enum LoginProvider {
GOOGLE(1), FACEBOOK(2), TWITTER(3), LINKEDIN(4), NATIVELOGIN(5), B2_ACCESS(6);
GOOGLE(1), FACEBOOK(2), TWITTER(3), LINKEDIN(4), NATIVELOGIN(5), B2_ACCESS(6), ORCID(7);
private int value;
@ -43,6 +44,8 @@ public class TokenValidatorFactoryImpl implements TokenValidatorFactory {
return NATIVELOGIN;
case 6:
return B2_ACCESS;
case 7:
return ORCID;
default:
throw new RuntimeException("Unsupported LoginProvider");
}
@ -51,32 +54,35 @@ public class TokenValidatorFactoryImpl implements TokenValidatorFactory {
private ApiContext apiContext;
private Environment environment;
private AuthenticationServiceImpl authenticationService;
private AuthenticationService nonVerifiedUserAuthenticationService;
private B2AccessCustomProvider b2AccessCustomProvider;
private ORCIDCustomProvider orcidCustomProvider;
@Autowired
public TokenValidatorFactoryImpl(ApiContext apiContext, Environment environment, AuthenticationServiceImpl authenticationService, B2AccessCustomProvider b2AccessCustomProvider) {
public TokenValidatorFactoryImpl(ApiContext apiContext, Environment environment, AuthenticationService nonVerifiedUserAuthenticationService, B2AccessCustomProvider b2AccessCustomProvider, ORCIDCustomProvider orcidCustomProvider) {
this.apiContext = apiContext;
this.environment = environment;
this.authenticationService = authenticationService;
this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService;
this.b2AccessCustomProvider = b2AccessCustomProvider;
this.orcidCustomProvider = orcidCustomProvider;
}
public TokenValidator getProvider(LoginProvider provider) {
switch (provider) {
case GOOGLE:
return new GoogleTokenValidator(this.apiContext, this.environment, this.authenticationService);
return new GoogleTokenValidator(this.apiContext, this.environment, this.nonVerifiedUserAuthenticationService);
case FACEBOOK:
return new FacebookTokenValidator(this.apiContext, this.environment, this.authenticationService);
return new FacebookTokenValidator(this.apiContext, this.environment, this.nonVerifiedUserAuthenticationService);
case LINKEDIN:
return new LinkedInTokenValidator(this.apiContext, this.environment, this.authenticationService);
return new LinkedInTokenValidator(this.apiContext, this.environment, this.nonVerifiedUserAuthenticationService);
case TWITTER:
return new TwitterTokenValidator(this.apiContext, this.environment, this.authenticationService);
return new TwitterTokenValidator(this.apiContext, this.environment, this.nonVerifiedUserAuthenticationService);
case B2_ACCESS:
return new B2AccessTokenValidator(this.environment, this.authenticationService, this.b2AccessCustomProvider);
return new B2AccessTokenValidator(this.environment, this.nonVerifiedUserAuthenticationService, this.b2AccessCustomProvider);
case ORCID:
return new ORCIDTokenValidator(this.environment, this.nonVerifiedUserAuthenticationService, this.orcidCustomProvider, this.apiContext);
default:
throw new RuntimeException("Login Provider Not Implemented");
}
}
}

View File

@ -1,15 +1,16 @@
package eu.eudat.logic.security.validators.b2access;
import eu.eudat.exceptions.security.NonValidTokenException;
import eu.eudat.exceptions.security.NullEmailException;
import eu.eudat.logic.services.operations.authentication.AuthenticationService;
import eu.eudat.models.data.login.LoginInfo;
import eu.eudat.models.data.loginprovider.LoginProviderUser;
import eu.eudat.models.data.security.Principal;
import eu.eudat.logic.security.customproviders.B2AccessCustomProvider;
import eu.eudat.logic.security.customproviders.B2AccessUser;
import eu.eudat.logic.security.customproviders.B2Access.B2AccessCustomProvider;
import eu.eudat.logic.security.customproviders.B2Access.B2AccessUser;
import eu.eudat.logic.security.validators.TokenValidator;
import eu.eudat.logic.security.validators.b2access.helpers.B2AccessRequest;
import eu.eudat.logic.security.validators.b2access.helpers.B2AccessResponseToken;
import eu.eudat.logic.services.operations.AuthenticationServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@ -24,18 +25,18 @@ import java.security.GeneralSecurityException;
public class B2AccessTokenValidator implements TokenValidator {
private B2AccessCustomProvider b2AccessCustomProvider;
private AuthenticationServiceImpl authenticationServiceImpl;
private AuthenticationService nonVerifiedUserAuthenticationService;
private Environment environment;
@Autowired
public B2AccessTokenValidator(Environment environment, AuthenticationServiceImpl authenticationServiceImpl, B2AccessCustomProvider b2AccessCustomProvider) {
this.authenticationServiceImpl = authenticationServiceImpl;
public B2AccessTokenValidator(Environment environment, AuthenticationService nonVerifiedUserAuthenticationService, B2AccessCustomProvider b2AccessCustomProvider) {
this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService;
this.environment = environment;
this.b2AccessCustomProvider = b2AccessCustomProvider;
}
@Override
public Principal validateToken(LoginInfo credentials) throws NonValidTokenException, IOException, GeneralSecurityException {
public Principal validateToken(LoginInfo credentials) throws NonValidTokenException, IOException, GeneralSecurityException, NullEmailException {
B2AccessUser b2AccessUser = this.b2AccessCustomProvider.getUser(credentials.getTicket());
LoginProviderUser user = new LoginProviderUser();
user.setId(b2AccessUser.getId());
@ -43,7 +44,7 @@ public class B2AccessTokenValidator implements TokenValidator {
user.setName(b2AccessUser.getName());
user.setProvider(credentials.getProvider());
user.setSecret(credentials.getTicket());
return this.authenticationServiceImpl.Touch(user);
return this.nonVerifiedUserAuthenticationService.Touch(user);
}
public B2AccessResponseToken getAccessToken(B2AccessRequest b2AccessRequest) {

View File

@ -1,22 +1,19 @@
package eu.eudat.logic.security.validators.facebook;
import eu.eudat.exceptions.security.NonValidTokenException;
import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.models.data.login.LoginInfo;
import eu.eudat.models.data.loginprovider.LoginProviderUser;
import eu.eudat.models.data.security.Principal;
import eu.eudat.logic.security.validators.TokenValidator;
import eu.eudat.logic.security.validators.TokenValidatorFactoryImpl;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.AuthenticationServiceImpl;
import eu.eudat.logic.services.operations.authentication.AuthenticationService;
import eu.eudat.models.data.login.LoginInfo;
import eu.eudat.models.data.loginprovider.LoginProviderUser;
import eu.eudat.models.data.security.Principal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.social.facebook.api.User;
import org.springframework.social.facebook.connect.FacebookServiceProvider;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
@ -25,50 +22,50 @@ import java.util.Map;
@Component("facebookTokenValidator")
public class FacebookTokenValidator implements TokenValidator {
private Environment environment;
private ApiContext apiContext;
private AuthenticationServiceImpl authenticationServiceImpl;
private FacebookServiceProvider facebookServiceProvider;
private Environment environment;
private ApiContext apiContext;
private AuthenticationService nonVerifiedUserAuthenticationService;
private FacebookServiceProvider facebookServiceProvider;
@Autowired
public FacebookTokenValidator(ApiContext apiContext, Environment environment, AuthenticationServiceImpl authenticationServiceImpl) {
this.environment = environment;
this.apiContext = apiContext;
this.authenticationServiceImpl = authenticationServiceImpl;
this.facebookServiceProvider = new FacebookServiceProvider(this.environment.getProperty("facebook.login.clientId"), this.environment.getProperty("facebook.login.clientSecret"), this.environment.getProperty("facebook.login.namespace"));
}
@Autowired
public FacebookTokenValidator(ApiContext apiContext, Environment environment, AuthenticationService nonVerifiedUserAuthenticationService) {
this.environment = environment;
this.apiContext = apiContext;
this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService;
this.facebookServiceProvider = new FacebookServiceProvider(this.environment.getProperty("facebook.login.clientId"), this.environment.getProperty("facebook.login.clientSecret"), this.environment.getProperty("facebook.login.namespace"));
}
@Override
public Principal validateToken(LoginInfo credentials) throws NonValidTokenException, IOException, GeneralSecurityException {
User profile = getFacebookUser(credentials.getTicket());
LoginProviderUser user = new LoginProviderUser();
if (profile.getEmail() == null)
throw new UnauthorisedException("Cannot login user.Facebook account did not provide email");
@Override
public Principal validateToken(LoginInfo credentials) {
User profile = getFacebookUser(credentials.getTicket());
LoginProviderUser user = new LoginProviderUser();
if (profile.getEmail() == null)
throw new UnauthorisedException("Cannot login user.Facebook account did not provide email");
user.setEmail(profile.getEmail());
user.setId(profile.getId());
//user.setIsVerified(profile.isVerified());
user.setName(profile.getName());
user.setProvider(TokenValidatorFactoryImpl.LoginProvider.FACEBOOK);
String url = (String)((Map<String,Object> )((Map<String,Object> )profile.getExtraData().get("picture")).get("data")).get("url");
user.setAvatarUrl(url);
user.setSecret(credentials.getTicket());
return this.authenticationServiceImpl.Touch(user);
}
user.setEmail(profile.getEmail());
user.setId(profile.getId());
//user.setIsVerified(profile.isVerified());
user.setName(profile.getName());
user.setProvider(TokenValidatorFactoryImpl.LoginProvider.FACEBOOK);
String url = (String) ((Map<String, Object>) ((Map<String, Object>) profile.getExtraData().get("picture")).get("data")).get("url");
user.setAvatarUrl(url);
user.setSecret(credentials.getTicket());
return this.nonVerifiedUserAuthenticationService.Touch(user);
}
private User getFacebookUser(String accessToken) {
String[] fields = {"id", "email", "first_name", "last_name", "name", "verified","picture"};
User profile = this.facebookServiceProvider.getApi(accessToken).fetchObject("me", User.class, fields);
return profile;
}
private User getFacebookUser(String accessToken) {
String[] fields = {"id", "email", "first_name", "last_name", "name", "verified", "picture"};
User profile = this.facebookServiceProvider.getApi(accessToken).fetchObject("me", User.class, fields);
return profile;
}
private Date addADay(Date date) {
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.DATE, 1);
dt = c.getTime();
return dt;
}
private Date addADay(Date date) {
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.DATE, 1);
dt = c.getTime();
return dt;
}
}

View File

@ -6,13 +6,12 @@ import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import eu.eudat.exceptions.security.NonValidTokenException;
import eu.eudat.models.data.login.LoginInfo;
import eu.eudat.models.data.loginprovider.LoginProviderUser;
import eu.eudat.logic.security.validators.TokenValidator;
import eu.eudat.logic.security.validators.TokenValidatorFactoryImpl;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.AuthenticationServiceImpl;
import eu.eudat.logic.services.operations.authentication.AuthenticationService;
import eu.eudat.models.data.login.LoginInfo;
import eu.eudat.models.data.loginprovider.LoginProviderUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@ -24,40 +23,40 @@ import java.util.Collections;
@Component("googleTokenValidator")
public class GoogleTokenValidator implements TokenValidator {
private static final HttpTransport transport = new NetHttpTransport();
private ApiContext apiContext;
private AuthenticationServiceImpl authenticationServiceImpl;
private GoogleIdTokenVerifier verifier;
private Environment environment;
private static final HttpTransport transport = new NetHttpTransport();
private ApiContext apiContext;
private AuthenticationService nonVerifiedUserAuthenticationService;
private GoogleIdTokenVerifier verifier;
private Environment environment;
@Autowired
public GoogleTokenValidator(ApiContext apiContext, Environment environment, AuthenticationServiceImpl authenticationServiceImpl) {
this.apiContext = apiContext;
this.environment = environment;
this.authenticationServiceImpl = authenticationServiceImpl;
verifier = new GoogleIdTokenVerifier.Builder(transport, JacksonFactory.getDefaultInstance())
.setAudience(Collections.singletonList(this.environment.getProperty("google.login.clientId")))
.build();
}
@Autowired
public GoogleTokenValidator(ApiContext apiContext, Environment environment, AuthenticationService nonVerifiedUserAuthenticationService) {
this.apiContext = apiContext;
this.environment = environment;
this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService;
verifier = new GoogleIdTokenVerifier.Builder(transport, JacksonFactory.getDefaultInstance())
.setAudience(Collections.singletonList(this.environment.getProperty("google.login.clientId")))
.build();
}
private GoogleIdToken verifyUserAndGetUser(String idTokenString) throws IOException, GeneralSecurityException {
GoogleIdToken idToken = verifier.verify(idTokenString);
return idToken;
}
private GoogleIdToken verifyUserAndGetUser(String idTokenString) throws IOException, GeneralSecurityException {
GoogleIdToken idToken = verifier.verify(idTokenString);
return idToken;
}
@Override
public eu.eudat.models.data.security.Principal validateToken(LoginInfo credentials) throws NonValidTokenException, IOException, GeneralSecurityException {
GoogleIdToken idToken = this.verifyUserAndGetUser(credentials.getTicket());
Payload payload = idToken.getPayload();
LoginProviderUser user = new LoginProviderUser();
user.setAvatarUrl((String) payload.get("picture"));
user.setSecret(credentials.getTicket());
user.setId( payload.getSubject());
user.setProvider(TokenValidatorFactoryImpl.LoginProvider.GOOGLE);
user.setName((String) payload.get("name"));
user.setEmail(payload.getEmail());
user.setIsVerified(payload.getEmailVerified());
return this.authenticationServiceImpl.Touch(user);
}
@Override
public eu.eudat.models.data.security.Principal validateToken(LoginInfo credentials) throws IOException, GeneralSecurityException {
GoogleIdToken idToken = this.verifyUserAndGetUser(credentials.getTicket());
Payload payload = idToken.getPayload();
LoginProviderUser user = new LoginProviderUser();
user.setAvatarUrl((String) payload.get("picture"));
user.setSecret(credentials.getTicket());
user.setId(payload.getSubject());
user.setProvider(TokenValidatorFactoryImpl.LoginProvider.GOOGLE);
user.setName((String) payload.get("name"));
user.setEmail(payload.getEmail());
user.setIsVerified(payload.getEmailVerified());
return this.nonVerifiedUserAuthenticationService.Touch(user);
}
}

View File

@ -1,11 +1,10 @@
package eu.eudat.logic.security.validators.linkedin;
import eu.eudat.exceptions.security.NonValidTokenException;
import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.logic.security.validators.TokenValidator;
import eu.eudat.logic.security.validators.TokenValidatorFactoryImpl;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.AuthenticationServiceImpl;
import eu.eudat.logic.services.operations.authentication.AuthenticationService;
import eu.eudat.models.data.login.LoginInfo;
import eu.eudat.models.data.loginprovider.LoginProviderUser;
import eu.eudat.models.data.security.Principal;
@ -17,28 +16,25 @@ import org.springframework.social.linkedin.connect.LinkedInServiceProvider;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.security.GeneralSecurityException;
@Component("linkedInTokenValidator")
public class LinkedInTokenValidator implements TokenValidator {
private Environment environment;
private ApiContext apiContext;
private AuthenticationServiceImpl authenticationServiceImpl;
private AuthenticationService nonVerifiedUserAuthenticationService;
private LinkedInServiceProvider linkedInServiceProvider;
@Autowired
public LinkedInTokenValidator(ApiContext apiContext, Environment environment, AuthenticationServiceImpl authenticationServiceImpl) {
public LinkedInTokenValidator(ApiContext apiContext, Environment environment, AuthenticationService nonVerifiedUserAuthenticationService) {
this.environment = environment;
this.apiContext = apiContext;
this.authenticationServiceImpl = authenticationServiceImpl;
this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService;
this.linkedInServiceProvider = new LinkedInServiceProvider(this.environment.getProperty("linkedin.login.clientId"), this.environment.getProperty("linkedin.login.clientSecret"));
}
@Override
public Principal validateToken(LoginInfo credentials) throws NonValidTokenException, IOException, GeneralSecurityException {
public Principal validateToken(LoginInfo credentials) {
AccessGrant accessGrant = this.linkedInServiceProvider.getOAuthOperations().exchangeForAccess(credentials.getTicket(), this.environment.getProperty("linkedin.login.redirect_uri"), null);
LinkedIn linkedInService = this.linkedInServiceProvider.getApi(accessGrant.getAccessToken());
LinkedInProfile linkedInProfile = linkedInService.profileOperations().getUserProfile();
@ -53,6 +49,6 @@ public class LinkedInTokenValidator implements TokenValidator {
user.setName(linkedInProfile.getFirstName() + " " + linkedInProfile.getLastName());
user.setProvider(TokenValidatorFactoryImpl.LoginProvider.LINKEDIN);
user.setSecret(accessGrant.getAccessToken());
return this.authenticationServiceImpl.Touch(user);
return this.nonVerifiedUserAuthenticationService.Touch(user);
}
}

View File

@ -0,0 +1,54 @@
package eu.eudat.logic.security.validators.orcid;
import eu.eudat.exceptions.security.NonValidTokenException;
import eu.eudat.exceptions.security.NullEmailException;
import eu.eudat.logic.security.customproviders.ORCID.ORCIDCustomProvider;
import eu.eudat.logic.security.customproviders.ORCID.ORCIDUser;
import eu.eudat.logic.security.validators.TokenValidator;
import eu.eudat.logic.security.validators.orcid.helpers.ORCIDRequest;
import eu.eudat.logic.security.validators.orcid.helpers.ORCIDResponseToken;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.authentication.AuthenticationService;
import eu.eudat.models.data.login.LoginInfo;
import eu.eudat.models.data.loginprovider.LoginProviderUser;
import eu.eudat.models.data.security.Principal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.security.GeneralSecurityException;
@Component("orcidTokenValidator")
public class ORCIDTokenValidator implements TokenValidator {
private ORCIDCustomProvider orcidCustomProvider;
private Environment environment;
private AuthenticationService nonVerifiedUserAuthenticationService;
private ApiContext apiContext;
@Autowired
public ORCIDTokenValidator(Environment environment, AuthenticationService nonVerifiedUserAuthenticationService, ORCIDCustomProvider orcidCustomProvider, ApiContext apiContext) {
this.environment = environment;
this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService;
this.orcidCustomProvider = orcidCustomProvider;
this.apiContext = apiContext;
}
@Override
public Principal validateToken(LoginInfo credentials) throws NonValidTokenException, IOException, GeneralSecurityException, NullEmailException {
ORCIDUser orcidUser = new ORCIDUser().getOrcidUser(credentials.getData());
LoginProviderUser user = new LoginProviderUser();
user.setId(orcidUser.getOrcidId());
user.setName(orcidUser.getName());
user.setProvider(credentials.getProvider());
user.setSecret(credentials.getTicket());
return this.nonVerifiedUserAuthenticationService.Touch(user);
}
public ORCIDResponseToken getAccessToken(ORCIDRequest orcidRequest) {
return this.orcidCustomProvider.getAccessToken(orcidRequest.getCode(), this.environment.getProperty("orcid.login.redirect_uri")
, this.environment.getProperty("orcid.login.client_id")
, this.environment.getProperty("orcid.login.client_secret"));
}
}

View File

@ -0,0 +1,12 @@
package eu.eudat.logic.security.validators.orcid.helpers;
public class ORCIDRequest {
private String code;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}

View File

@ -0,0 +1,28 @@
package eu.eudat.logic.security.validators.orcid.helpers;
public class ORCIDResponseToken {
private String orcidId;
private String name;
private String accessToken;
public String getOrcidId() {
return orcidId;
}
public void setOrcidId(String orcidId) {
this.orcidId = orcidId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
}

View File

@ -1,11 +1,12 @@
package eu.eudat.logic.security.validators.twitter;
import eu.eudat.exceptions.security.NonValidTokenException;
import eu.eudat.exceptions.security.NullEmailException;
import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.logic.security.validators.TokenValidator;
import eu.eudat.logic.security.validators.TokenValidatorFactoryImpl;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.AuthenticationServiceImpl;
import eu.eudat.logic.services.operations.authentication.AuthenticationService;
import eu.eudat.models.data.login.LoginInfo;
import eu.eudat.models.data.loginprovider.LoginProviderUser;
import eu.eudat.models.data.security.Principal;
@ -28,19 +29,19 @@ public class TwitterTokenValidator implements TokenValidator {
private Environment environment;
private ApiContext apiContext;
private AuthenticationServiceImpl authenticationServiceImpl;
private AuthenticationService nonVerifiedUserAuthenticationService;
private TwitterServiceProvider twitterServiceProvider;
@Autowired
public TwitterTokenValidator(ApiContext apiContext, Environment environment, AuthenticationServiceImpl authenticationServiceImpl) {
public TwitterTokenValidator(ApiContext apiContext, Environment environment, AuthenticationService nonVerifiedUserAuthenticationService) {
this.environment = environment;
this.apiContext = apiContext;
this.authenticationServiceImpl = authenticationServiceImpl;
this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService;
this.twitterServiceProvider = new TwitterServiceProvider(this.environment.getProperty("twitter.login.clientId"), this.environment.getProperty("twitter.login.clientSecret"));
}
@Override
public Principal validateToken(LoginInfo credentials) throws NonValidTokenException, IOException, GeneralSecurityException {
public Principal validateToken(LoginInfo credentials) throws NonValidTokenException, IOException, GeneralSecurityException, NullEmailException {
String verifier = (String) credentials.getData();
OAuthToken oAuthToken = new OAuthToken(credentials.getTicket(), verifier);
AuthorizedRequestToken authorizedRequestToken = new AuthorizedRequestToken(oAuthToken, verifier);
@ -59,7 +60,7 @@ public class TwitterTokenValidator implements TokenValidator {
user.setName(profile.getName());
user.setProvider(TokenValidatorFactoryImpl.LoginProvider.TWITTER);
user.setSecret(finalOauthToken.getValue());
return this.authenticationServiceImpl.Touch(user);
return this.nonVerifiedUserAuthenticationService.Touch(user);
}
public OAuthToken getRequestToken() {

View File

@ -1,21 +0,0 @@
package eu.eudat.logic.services.operations;
import eu.eudat.models.data.login.Credentials;
import eu.eudat.models.data.loginprovider.LoginProviderUser;
import eu.eudat.models.data.security.Principal;
import java.util.UUID;
/**
* Created by ikalyvas on 3/1/2018.
*/
public interface AuthenticationService {
Principal Touch(LoginProviderUser profile);
Principal Touch(Credentials credentials);
void Logout(UUID token);
Principal Touch(UUID token);
}

View File

@ -1,224 +0,0 @@
package eu.eudat.logic.services.operations;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.data.dao.criteria.UserInfoCriteria;
import eu.eudat.data.entities.Credential;
import eu.eudat.data.entities.UserInfo;
import eu.eudat.data.entities.UserRole;
import eu.eudat.data.entities.UserToken;
import eu.eudat.logic.builders.entity.CredentialBuilder;
import eu.eudat.logic.builders.entity.UserInfoBuilder;
import eu.eudat.logic.builders.entity.UserTokenBuilder;
import eu.eudat.logic.builders.model.models.PrincipalBuilder;
import eu.eudat.logic.security.validators.TokenValidatorFactoryImpl;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.login.Credentials;
import eu.eudat.models.data.loginprovider.LoginProviderUser;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.Authorities;
import org.json.JSONObject;
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 java.io.IOException;
import java.util.*;
@Service("authenticationService")
public class AuthenticationServiceImpl implements AuthenticationService {
private ApiContext apiContext;
private Environment environment;
@Autowired
public AuthenticationServiceImpl(ApiContext apiContext, Environment environment) {
this.environment = environment;
this.apiContext = apiContext;
}
public Principal Touch(UUID token) {
UserToken tokenEntry = this.apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().find(token);
if (tokenEntry == null || tokenEntry.getExpiresAt().before(new Date())) return null;
return this.Touch(tokenEntry);
}
public void Logout(UUID token) {
UserToken tokenEntry = this.apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().find(token);
this.apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().delete(tokenEntry);
}
private Principal Touch(UserToken token) {
if (token == null || token.getExpiresAt().before(new Date())) return null;
UserInfo user = this.apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(token.getUser().getId());
if (user == null) return null;
String avatarUrl;
try {
avatarUrl = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("avatarUrl").asText() : "";
} catch (Exception e) {
avatarUrl = "";
}
String culture;
try {
culture = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("culture").get("name").asText() : "";
} catch (Exception e) {
culture = "";
}
String language;
try {
language = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("language").get("value").asText() : "";
} catch (Exception e) {
language = "";
}
String timezone;
try {
timezone = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("timezone").asText() : "";
} catch (Exception e) {
timezone = "";
}
Principal principal = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(PrincipalBuilder.class)
.id(user.getId()).token(token.getToken())
.expiresAt(token.getExpiresAt()).name(user.getName())
.avatarUrl(avatarUrl)
.culture(culture)
.language(language)
.timezone(timezone)
.build();
List<UserRole> userRoles = apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().getUserRoles(user);
for (UserRole item : userRoles) {
if (principal.getAuthz() == null) principal.setAuthorities(new HashSet<>());
principal.getAuthz().add(Authorities.fromInteger(item.getRole()));
}
return principal;
}
public Principal Touch(Credentials credentials) {
Credential credential = this.apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao().getLoggedInCredentials(credentials.getUsername(), credentials.getSecret(), TokenValidatorFactoryImpl.LoginProvider.NATIVELOGIN.getValue());
if (credential == null && credentials.getUsername().equals(environment.getProperty("autouser.root.username"))) {
try {
credential = this.autoCreateUser(credentials.getUsername(), credentials.getSecret());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
if (credential == null) return null;
UserToken userToken = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserTokenBuilder.class)
.issuedAt(new Date()).user(credential.getUserInfo())
.token(UUID.randomUUID()).expiresAt(addADay(new Date()))
.build();
userToken = apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().createOrUpdate(userToken);
return this.Touch(userToken);
}
public Principal Touch(LoginProviderUser profile) {
UserInfoCriteria criteria = new UserInfoCriteria();
criteria.setEmail(profile.getEmail());
UserInfo userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().asQueryable().withHint("userInfo").where((builder, root) -> builder.equal(root.get("email"), profile.getEmail())).getSingleOrDefault();
if (userInfo == null) {
Optional<Credential> optionalCredential = Optional.ofNullable(apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao()
.asQueryable().withHint("credentialUserInfo")
.where((builder, root) -> builder.and(builder.equal(root.get("provider"), profile.getProvider().getValue()), builder.equal(root.get("externalId"), profile.getId())))
.getSingleOrDefault());
userInfo = optionalCredential.map(Credential::getUserInfo).orElse(null);
}
final Credential credential = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(CredentialBuilder.class)
.id(UUID.randomUUID()).creationTime(new Date()).status(1)
.lastUpdateTime(new Date()).provider(profile.getProvider().getValue())
.secret(profile.getSecret()).externalId(profile.getId())
.build();
if (userInfo == null) {
userInfo = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class)
.name(profile.getName()).verified_email(profile.getIsVerified())
.email(profile.getEmail()).created(new Date()).lastloggedin(new Date())
.additionalinfo("{\"data\":{\"avatar\":{\"url\":\"" + profile.getAvatarUrl() + "\"}}}")
.authorization_level((short) 1).usertype((short) 1)
.build();
userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().createOrUpdate(userInfo);
credential.setPublicValue(userInfo.getName());
credential.setUserInfo(userInfo);
apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao().createOrUpdate(credential);
UserRole role = new UserRole();
role.setRole(Authorities.USER.getValue());
role.setUserInfo(userInfo);
apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().createOrUpdate(role);
} else {
Map<String, Object> additionalInfo = userInfo.getAdditionalinfo() != null ?
new JSONObject(userInfo.getAdditionalinfo()).toMap() : new HashMap<>();
additionalInfo.put("avatarUrl", profile.getAvatarUrl());
userInfo.setLastloggedin(new Date());
userInfo.setAdditionalinfo(new JSONObject(additionalInfo).toString());
Set<Credential> credentials = userInfo.getCredentials();
if (credentials.contains(credential)) {
Credential oldCredential = credentials.stream().filter(item -> credential.getProvider().equals(item.getProvider())).findFirst().get();
credential.setId(oldCredential.getId());
} else {
credential.setUserInfo(userInfo);
credential.setId(UUID.randomUUID());
credential.setPublicValue(userInfo.getName());
apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao().createOrUpdate(credential);
userInfo.getCredentials().add(credential);
}
userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().createOrUpdate(userInfo);
}
UserToken userToken = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserTokenBuilder.class)
.token(UUID.randomUUID()).user(userInfo)
.expiresAt(addADay(new Date())).issuedAt(new Date())
.build();
apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().createOrUpdate(userToken);
return Touch(userToken.getToken());
}
private Date addADay(Date date) {
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.DATE, 1);
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 = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class)
.name(username).email(environment.getProperty("autouser.root.email")).created(new Date())
.lastloggedin(new Date()).authorization_level((short) 1).usertype((short) 1)
.build();
userInfo = this.apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().createOrUpdate(userInfo);
UserRole role = new UserRole();
role.setRole(Authorities.ADMIN.getValue());
role.setUserInfo(userInfo);
this.apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().createOrUpdate(role);
Credential credential = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(CredentialBuilder.class)
.id(UUID.randomUUID()).userInfo(userInfo).publicValue(username).secret(password)
.provider((int) TokenValidatorFactoryImpl.LoginProvider.NATIVELOGIN.getValue())
.creationTime(new Date()).lastUpdateTime(new Date()).status(0)
.build();
return this.apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao().createOrUpdate(credential);
}
}

View File

@ -46,5 +46,7 @@ public interface DatabaseRepository {
DatasetServiceDao getDatasetServiceDao();
LoginConfirmationEmailDao getLoginConfirmationEmailDao();
<T> void detachEntity(T entity);
}

View File

@ -32,6 +32,7 @@ public class DatabaseRepositoryImpl implements DatabaseRepository {
private DMPProfileDao dmpProfileDao;
private DatasetExternalDatasetDao datasetExternalDatasetDao;
private DatasetServiceDao datasetServiceDao;
private LoginConfirmationEmailDao loginConfirmationEmailDao;
private EntityManager entityManager;
@ -240,6 +241,16 @@ public class DatabaseRepositoryImpl implements DatabaseRepository {
this.datasetServiceDao = datasetServiceDao;
}
@Override
public LoginConfirmationEmailDao getLoginConfirmationEmailDao() {
return loginConfirmationEmailDao;
}
@Autowired
public void setLoginConfirmationEmailDao(LoginConfirmationEmailDao loginConfirmationEmailDao) {
this.loginConfirmationEmailDao = loginConfirmationEmailDao;
}
public <T> void detachEntity(T entity) {
this.entityManager.detach(entity);
}

View File

@ -0,0 +1,174 @@
package eu.eudat.logic.services.operations.authentication;
import eu.eudat.data.entities.Credential;
import eu.eudat.data.entities.UserInfo;
import eu.eudat.data.entities.UserRole;
import eu.eudat.data.entities.UserToken;
import eu.eudat.exceptions.security.NullEmailException;
import eu.eudat.logic.builders.entity.CredentialBuilder;
import eu.eudat.logic.builders.entity.UserInfoBuilder;
import eu.eudat.logic.builders.entity.UserTokenBuilder;
import eu.eudat.logic.security.validators.TokenValidatorFactoryImpl;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.login.Credentials;
import eu.eudat.models.data.loginprovider.LoginProviderUser;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.Authorities;
import org.json.JSONObject;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
public abstract class AbstractAuthenticationService implements AuthenticationService {
protected ApiContext apiContext;
protected Environment environment;
public AbstractAuthenticationService(ApiContext apiContext, Environment environment) {
this.apiContext = apiContext;
this.environment = environment;
}
protected Date addADay(Date date) {
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.DATE, 1);
dt = c.getTime();
return dt;
}
abstract Principal Touch(UserToken token);
@Transactional
protected 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 = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class)
.name(username).email(environment.getProperty("autouser.root.email")).created(new Date())
.lastloggedin(new Date()).authorization_level((short) 1).usertype((short) 1)
.build();
userInfo = this.apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().createOrUpdate(userInfo);
UserRole role = new UserRole();
role.setRole(Authorities.ADMIN.getValue());
role.setUserInfo(userInfo);
this.apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().createOrUpdate(role);
Credential credential = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(CredentialBuilder.class)
.id(UUID.randomUUID()).userInfo(userInfo).publicValue(username).secret(password)
.provider((int) TokenValidatorFactoryImpl.LoginProvider.NATIVELOGIN.getValue())
.creationTime(new Date()).lastUpdateTime(new Date()).status(0)
.build();
return this.apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao().createOrUpdate(credential);
}
public Principal Touch(UUID token) {
UserToken tokenEntry = this.apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().find(token);
if (tokenEntry == null || tokenEntry.getExpiresAt().before(new Date())) return null;
return this.Touch(tokenEntry);
}
public void Logout(UUID token) {
UserToken tokenEntry = this.apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().find(token);
this.apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().delete(tokenEntry);
}
public Principal Touch(Credentials credentials) throws NullEmailException {
Credential credential = this.apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao().getLoggedInCredentials(credentials.getUsername(), credentials.getSecret(), TokenValidatorFactoryImpl.LoginProvider.NATIVELOGIN.getValue());
if (credential == null && credentials.getUsername().equals(environment.getProperty("autouser.root.username"))) {
try {
credential = this.autoCreateUser(credentials.getUsername(), credentials.getSecret());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
if (credential == null) return null;
UserToken userToken = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserTokenBuilder.class)
.issuedAt(new Date()).user(credential.getUserInfo())
.token(UUID.randomUUID()).expiresAt(addADay(new Date()))
.build();
userToken = apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().createOrUpdate(userToken);
return this.Touch(userToken);
}
public Principal Touch(LoginProviderUser profile) throws NullEmailException {
UserInfo userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().asQueryable().withHint("userInfo").where((builder, root) -> builder.equal(root.get("email"), profile.getEmail())).getSingleOrDefault();
if (userInfo == null) {
Optional<Credential> optionalCredential = Optional.ofNullable(apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao()
.asQueryable().withHint("credentialUserInfo")
.where((builder, root) -> builder.and(builder.equal(root.get("provider"), profile.getProvider().getValue()), builder.equal(root.get("externalId"), profile.getId())))
.getSingleOrDefault());
userInfo = optionalCredential.map(Credential::getUserInfo).orElse(null);
}
final Credential credential = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(CredentialBuilder.class)
.id(UUID.randomUUID())
.creationTime(new Date())
.status(1)
.lastUpdateTime(new Date())
.provider(profile.getProvider().getValue())
.secret(profile.getSecret())
.externalId(profile.getId())
.build();
if (userInfo == null) {
userInfo = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class)
.name(profile.getName()).verified_email(profile.getIsVerified())
.email(profile.getEmail()).created(new Date()).lastloggedin(new Date())
.additionalinfo("{\"data\":{\"avatar\":{\"url\":\"" + profile.getAvatarUrl() + "\"}}}")
.authorization_level((short) 1).usertype((short) 1)
.build();
userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().createOrUpdate(userInfo);
credential.setPublicValue(userInfo.getName());
credential.setUserInfo(userInfo);
apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao().createOrUpdate(credential);
UserRole role = new UserRole();
role.setRole(Authorities.USER.getValue());
role.setUserInfo(userInfo);
apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().createOrUpdate(role);
} else {
Map<String, Object> additionalInfo = userInfo.getAdditionalinfo() != null ?
new JSONObject(userInfo.getAdditionalinfo()).toMap() : new HashMap<>();
additionalInfo.put("avatarUrl", profile.getAvatarUrl());
userInfo.setLastloggedin(new Date());
userInfo.setAdditionalinfo(new JSONObject(additionalInfo).toString());
Set<Credential> credentials = userInfo.getCredentials();
if (credentials.contains(credential)) {
Credential oldCredential = credentials.stream().filter(item -> credential.getProvider().equals(item.getProvider())).findFirst().get();
credential.setId(oldCredential.getId());
} else {
credential.setUserInfo(userInfo);
credential.setId(UUID.randomUUID());
credential.setPublicValue(userInfo.getName());
apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao().createOrUpdate(credential);
userInfo.getCredentials().add(credential);
}
userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().createOrUpdate(userInfo);
}
UserToken userToken = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserTokenBuilder.class)
.token(UUID.randomUUID()).user(userInfo)
.expiresAt(addADay(new Date())).issuedAt(new Date())
.build();
apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().createOrUpdate(userToken);
return Touch(userToken.getToken());
}
}

View File

@ -0,0 +1,22 @@
package eu.eudat.logic.services.operations.authentication;
import eu.eudat.exceptions.security.NullEmailException;
import eu.eudat.models.data.login.Credentials;
import eu.eudat.models.data.loginprovider.LoginProviderUser;
import eu.eudat.models.data.security.Principal;
import java.util.UUID;
/**
* Created by ikalyvas on 3/1/2018.
*/
public interface AuthenticationService {
Principal Touch(LoginProviderUser profile) throws NullEmailException;
Principal Touch(Credentials credentials) throws NullEmailException;
void Logout(UUID token);
Principal Touch(UUID token) throws NullEmailException;
}

View File

@ -0,0 +1,70 @@
package eu.eudat.logic.services.operations.authentication;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.data.entities.UserInfo;
import eu.eudat.data.entities.UserRole;
import eu.eudat.data.entities.UserToken;
import eu.eudat.logic.builders.model.models.PrincipalBuilder;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.Authorities;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
@Service("nonVerifiedUserAuthenticationService")
public class NonVerifiedUserEmailAuthenticationService extends AbstractAuthenticationService {
public NonVerifiedUserEmailAuthenticationService(ApiContext apiContext, Environment environment) {
super(apiContext, environment);
}
public Principal Touch(UserToken token) {
if (token == null || token.getExpiresAt().before(new Date())) return null;
UserInfo user = this.apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(token.getUser().getId());
if (user == null) return null;
String avatarUrl;
try {
avatarUrl = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("avatarUrl").asText() : "";
} catch (Exception e) {
avatarUrl = "";
}
String culture;
try {
culture = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("culture").get("name").asText() : "";
} catch (Exception e) {
culture = "";
}
String language;
try {
language = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("language").get("value").asText() : "";
} catch (Exception e) {
language = "";
}
String timezone;
try {
timezone = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("timezone").asText() : "";
} catch (Exception e) {
timezone = "";
}
Principal principal = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(PrincipalBuilder.class)
.id(user.getId()).token(token.getToken())
.expiresAt(token.getExpiresAt()).name(user.getName())
.avatarUrl(avatarUrl)
.culture(culture)
.language(language)
.timezone(timezone)
.build();
List<UserRole> userRoles = apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().getUserRoles(user);
for (UserRole item : userRoles) {
if (principal.getAuthz() == null) principal.setAuthorities(new HashSet<>());
principal.getAuthz().add(Authorities.fromInteger(item.getRole()));
}
return principal;
}
}

View File

@ -0,0 +1,79 @@
package eu.eudat.logic.services.operations.authentication;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.data.entities.Credential;
import eu.eudat.data.entities.UserInfo;
import eu.eudat.data.entities.UserRole;
import eu.eudat.data.entities.UserToken;
import eu.eudat.exceptions.security.NullEmailException;
import eu.eudat.logic.builders.entity.CredentialBuilder;
import eu.eudat.logic.builders.entity.UserInfoBuilder;
import eu.eudat.logic.builders.entity.UserTokenBuilder;
import eu.eudat.logic.builders.model.models.PrincipalBuilder;
import eu.eudat.logic.security.validators.TokenValidatorFactoryImpl;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.login.Credentials;
import eu.eudat.models.data.loginprovider.LoginProviderUser;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.Authorities;
import org.json.JSONObject;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import java.util.*;
@Service("verifiedUserAuthenticationService")
public class VerifiedUserAuthenticationService extends AbstractAuthenticationService {
public VerifiedUserAuthenticationService(ApiContext apiContext, Environment environment) {
super(apiContext, environment);
}
public Principal Touch(UserToken token) {
if (token == null || token.getExpiresAt().before(new Date())) return null;
UserInfo user = this.apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(token.getUser().getId());
if (user == null) return null;
if (user.getEmail() == null) throw new NullEmailException();
String avatarUrl;
try {
avatarUrl = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("avatarUrl").asText() : "";
} catch (Exception e) {
avatarUrl = "";
}
String culture;
try {
culture = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("culture").get("name").asText() : "";
} catch (Exception e) {
culture = "";
}
String language;
try {
language = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("language").get("value").asText() : "";
} catch (Exception e) {
language = "";
}
String timezone;
try {
timezone = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("timezone").asText() : "";
} catch (Exception e) {
timezone = "";
}
Principal principal = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(PrincipalBuilder.class)
.id(user.getId()).token(token.getToken())
.expiresAt(token.getExpiresAt()).name(user.getName())
.avatarUrl(avatarUrl)
.culture(culture)
.language(language)
.timezone(timezone)
.build();
List<UserRole> userRoles = apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().getUserRoles(user);
for (UserRole item : userRoles) {
if (principal.getAuthz() == null) principal.setAuthorities(new HashSet<>());
principal.getAuthz().add(Authorities.fromInteger(item.getRole()));
}
return principal;
}
}

View File

@ -0,0 +1,13 @@
package eu.eudat.logic.services.utilities;
import eu.eudat.data.dao.entities.LoginConfirmationEmailDao;
import eu.eudat.data.entities.LoginConfirmationEmail;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public interface ConfirmationEmailService {
public void createConfirmationEmail(LoginConfirmationEmailDao loginConfirmationEmailDao, MailService mailService, String email, UUID userId);
public CompletableFuture sentConfirmationEmail(LoginConfirmationEmail confirmationEmail, MailService mailService);
}

View File

@ -0,0 +1,73 @@
package eu.eudat.logic.services.utilities;
import eu.eudat.core.logger.Logger;
import eu.eudat.data.dao.entities.LoginConfirmationEmailDao;
import eu.eudat.data.entities.LoginConfirmationEmail;
import eu.eudat.models.data.mail.SimpleMail;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@Service("ConfirmationEmailService")
public class ConfirmationEmailServiceImpl implements ConfirmationEmailService {
private Logger logger;
private Environment environment;
public ConfirmationEmailServiceImpl(Logger logger, Environment environment) {
this.logger = logger;
this.environment = environment;
}
@Override
public void createConfirmationEmail(LoginConfirmationEmailDao loginConfirmationEmailDao, MailService mailService, String email, UUID userId) {
LoginConfirmationEmail confirmationEmail = new LoginConfirmationEmail();
confirmationEmail.setEmail(email);
confirmationEmail.setExpiresAt(Date
.from(new Date()
.toInstant()
.plusSeconds(Long.parseLong(this.environment.getProperty("conf_email.expiration_time_seconds")))
)
);
confirmationEmail.setUserId(userId);
confirmationEmail.setIsConfirmed(false);
confirmationEmail.setToken(UUID.randomUUID());
confirmationEmail = loginConfirmationEmailDao.createOrUpdate(confirmationEmail);
sentConfirmationEmail(confirmationEmail, mailService);
}
@Override
public CompletableFuture sentConfirmationEmail(LoginConfirmationEmail confirmationEmail, MailService mailService) {
return CompletableFuture.runAsync(() -> {
SimpleMail mail = new SimpleMail();
mail.setSubject(environment.getProperty("conf_email.subject"));
mail.setContent(createContent(confirmationEmail.getToken(), mailService));
mail.setTo(confirmationEmail.getEmail());
try {
mailService.sendSimpleMail(mail);
} catch (Exception ex) {
ex.printStackTrace();
this.logger.error(ex, ex.getMessage());
}
});
}
private String createContent(UUID confirmationToken, MailService mailService) {
String content = mailService.getMailTemplateContent("classpath:emailConfirmation.html");
content = content.replace("{confirmationToken}", confirmationToken.toString());
content = content.replace("{expiration_time}", secondsToTime(Integer.parseInt(this.environment.getProperty("conf_email.expiration_time_seconds"))));
content = content.replace("{host}", this.environment.getProperty("dmp.domain"));
return content;
}
private String secondsToTime(int seconds) {
int sec = seconds % 60;
int hour = seconds / 60;
int min = hour % 60;
hour = hour / 60;
return (hour + ":" + min + ":" + sec);
}
}

View File

@ -70,7 +70,7 @@ public class InvitationServiceImpl implements InvitationService {
return CompletableFuture.runAsync(() -> {
SimpleMail mail = new SimpleMail();
mail.setSubject(createSubject(dmp, mailService.getMailTemplateSubject()));
mail.setContent(createContent(invitation.getId(), dmp, recipient, mailService.getMailTemplateContent()));
mail.setContent(createContent(invitation.getId(), dmp, recipient, mailService.getMailTemplateContent("classpath:email.html")));
mail.setTo(invitation.getInvitationEmail());
try {
mailService.sendSimpleMail(mail);

View File

@ -8,7 +8,7 @@ import javax.mail.MessagingException;
public interface MailService {
void sendSimpleMail(SimpleMail mail) throws MessagingException;
String getMailTemplateContent();
String getMailTemplateContent(String resourceTemplate);
String getMailTemplateSubject();
}

View File

@ -46,8 +46,8 @@ public class MailServiceImpl implements MailService {
}
@Override
public String getMailTemplateContent() {
Resource resource = applicationContext.getResource("classpath:email.html");
public String getMailTemplateContent(String resourceTemplate) {
Resource resource = applicationContext.getResource(resourceTemplate);
try {
InputStream inputStream = resource.getInputStream();
StringWriter writer = new StringWriter();

View File

@ -12,4 +12,6 @@ public interface UtilitiesService {
MailService getMailService();
VisibilityRuleService getVisibilityRuleService();
ConfirmationEmailService getConfirmationEmailService();
}

View File

@ -13,12 +13,14 @@ public class UtilitiesServiceImpl implements UtilitiesService {
private InvitationService invitationService;
private MailService mailService;
private VisibilityRuleService visibilityRuleService;
private ConfirmationEmailService confirmationEmailService;
@Autowired
public UtilitiesServiceImpl(InvitationService invitationService, MailService mailService, VisibilityRuleService visibilityRuleService) {
public UtilitiesServiceImpl(InvitationService invitationService, MailService mailService, VisibilityRuleService visibilityRuleService, ConfirmationEmailService confirmationEmailService) {
this.invitationService = invitationService;
this.mailService = mailService;
this.visibilityRuleService = visibilityRuleService;
this.confirmationEmailService = confirmationEmailService;
}
@Override
@ -26,6 +28,11 @@ public class UtilitiesServiceImpl implements UtilitiesService {
return visibilityRuleService;
}
@Override
public ConfirmationEmailService getConfirmationEmailService() {
return confirmationEmailService;
}
@Override
public InvitationService getInvitationService() {
return invitationService;

View File

@ -41,6 +41,7 @@ public class DataManagementPlan implements DataModel<DMP, DataManagementPlan> {
private List<DynamicFieldWithValue> dynamicFields;
private Map<String, Object> properties;
private List<UserInfoListingModel> users;
private String doi;
public UUID getId() {
return id;
@ -189,6 +190,13 @@ public class DataManagementPlan implements DataModel<DMP, DataManagementPlan> {
this.users = users;
}
public String getDoi() {
return doi;
}
public void setDoi(String doi) {
this.doi = doi;
}
@Override
public DataManagementPlan fromDataModel(DMP entity) {
this.id = entity.getId();
@ -228,6 +236,7 @@ public class DataManagementPlan implements DataModel<DMP, DataManagementPlan> {
this.status = entity.getStatus();
this.associatedUsers = entity.getUsers().stream().map(item -> new UserListingModel().fromDataModel(item.getUser())).collect(Collectors.toList());
this.users = entity.getUsers().stream().map(item -> new UserInfoListingModel().fromDataModel(item)).collect(Collectors.toList());
this.doi = entity.getDoi();
return this;
}

View File

@ -41,6 +41,7 @@ public class DataManagementPlanOverviewModel implements DataModel<DMP, DataManag
private String description;
private boolean isPublic;
private Date publishedAt;
private String doi;
public String getId() {
@ -169,6 +170,13 @@ public class DataManagementPlanOverviewModel implements DataModel<DMP, DataManag
this.publishedAt = publishedAt;
}
public String getDoi() {
return doi;
}
public void setDoi(String doi) {
this.doi = doi;
}
@Override
public DataManagementPlanOverviewModel fromDataModel(DMP entity) {
this.id = entity.getId().toString();
@ -201,6 +209,7 @@ public class DataManagementPlanOverviewModel implements DataModel<DMP, DataManag
}
this.isPublic = entity.isPublic();
this.publishedAt = entity.getPublishedAt();
this.doi = entity.getDoi();
return this;
}

View File

@ -2,7 +2,7 @@ package eu.eudat.types;
public enum ApiMessageCode {
NO_MESSAGE(0), SUCCESS_MESSAGE(200), WARN_MESSAGE(300), ERROR_MESSAGE(400),
DEFAULT_ERROR_MESSAGE(444), VALIDATION_MESSAGE(445), UNSUCCESS_DELETE(674);
DEFAULT_ERROR_MESSAGE(444), VALIDATION_MESSAGE(445),NULL_EMAIL(480), UNSUCCESS_DELETE(674);
private Integer value;
@ -26,6 +26,8 @@ public enum ApiMessageCode {
return ERROR_MESSAGE;
case 444:
return DEFAULT_ERROR_MESSAGE;
case 480:
return NULL_EMAIL;
case 674:
return UNSUCCESS_DELETE;
default:

View File

@ -18,7 +18,6 @@ pdf.converter.url=http://localhost:88/
configuration.externalUrls=/tmp/ExternalUrls.xml
configuration.dynamicProjectUrl=/tmp/ProjectConfiguration.xml
configuration.h2020template=C:\\Users\\gkolokythas\\Documents\\openDmp\\dmp-backend\\web\\src\\main\\resources\\documents\\h2020.docx
configuration.exportUrl=C:\\Users\\gkolokythas\\Documents\\openDmp\\dmp-backend\\web\\src\\main\\exportFiles\\
#############TWITTER LOGIN CONFIGURATIONS#########
twitter.login.redirect_uri=http://127.0.0.1:4200/login/twitter
@ -35,3 +34,17 @@ facebook.login.namespace=
b2access.externallogin.user_info_url=https://b2access-integration.fz-juelich.de:443/oauth2/userinfo
b2access.externallogin.access_token_url=https://b2access-integration.fz-juelich.de:443/oauth2/token
b2access.externallogin.redirect_uri=http://opendmp.eu/api/oauth/authorized/b2access
#############ORCID CONFIGURATIONS#########
orcid.login.client_id=APP-766DI5LP8T75FC4R
orcid.login.client_secret=f6ddc717-f49e-4bce-b302-2e479b226a24
orcid.login.access_token_url=https://orcid.org/oauth/token
orcid.login.redirect_uri=http://localhost:4200/login/external/orcid
#############CONFIRMATION EMAIL CONFIGURATIONS#########
conf_email.expiration_time_seconds=14400
conf_email.subject=OpenDMP email confirmation
#############ZENODO CONFIGURATIONS#########
zenodo.url=https://sandbox.zenodo.org/api/
zenodo.access_token=

View File

@ -0,0 +1,304 @@
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Simple Transactional Email</title>
<style>
/* -------------------------------------
GLOBAL RESETS
------------------------------------- */
img {
border: none;
-ms-interpolation-mode: bicubic;
max-width: 100%; }
body {
background-color: #f6f6f6;
font-family: sans-serif;
-webkit-font-smoothing: antialiased;
font-size: 14px;
line-height: 1.4;
margin: 0;
padding: 0;
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%; }
table {
border-collapse: separate;
mso-table-lspace: 0pt;
mso-table-rspace: 0pt;
width: 100%; }
table td {
font-family: sans-serif;
font-size: 14px;
vertical-align: top; }
/* -------------------------------------
BODY & CONTAINER
------------------------------------- */
.body {
background-color: #f6f6f6;
width: 100%; }
/* Set a max-width, and make it display as block so it will automatically stretch to that width, but will also shrink down on a phone or something */
.container {
display: block;
Margin: 0 auto !important;
/* makes it centered */
max-width: 580px;
padding: 10px;
width: 580px; }
/* This should also be a block element, so that it will fill 100% of the .container */
.content {
box-sizing: border-box;
display: block;
Margin: 0 auto;
max-width: 580px;
padding: 10px; }
/* -------------------------------------
HEADER, FOOTER, MAIN
------------------------------------- */
.main {
background: #ffffff;
border-radius: 3px;
width: 100%; }
.wrapper {
box-sizing: border-box;
padding: 20px; }
.content-block {
padding-bottom: 10px;
padding-top: 10px;
}
.footer {
clear: both;
Margin-top: 10px;
text-align: center;
width: 100%; }
.footer td,
.footer p,
.footer span,
.footer a {
color: #999999;
font-size: 12px;
text-align: center; }
/* -------------------------------------
TYPOGRAPHY
------------------------------------- */
h1,
h2,
h3,
h4 {
color: #000000;
font-family: sans-serif;
font-weight: 400;
line-height: 1.4;
margin: 0;
Margin-bottom: 30px; }
h1 {
font-size: 35px;
font-weight: 300;
text-align: center;
text-transform: capitalize; }
p,
ul,
ol {
font-family: sans-serif;
font-size: 14px;
font-weight: normal;
margin: 0;
Margin-bottom: 15px; }
p li,
ul li,
ol li {
list-style-position: inside;
margin-left: 5px; }
a {
color: #3498db;
text-decoration: underline; }
/* -------------------------------------
BUTTONS
------------------------------------- */
.btn {
box-sizing: border-box;
width: 100%; }
.btn > tbody > tr > td {
padding-bottom: 15px; }
.btn table {
width: auto; }
.btn table td {
background-color: #ffffff;
border-radius: 5px;
text-align: center; }
.btn a {
background-color: #ffffff;
border: solid 1px #3498db;
border-radius: 5px;
box-sizing: border-box;
color: #3498db;
cursor: pointer;
display: inline-block;
font-size: 14px;
font-weight: bold;
margin: 0;
padding: 12px 25px;
text-decoration: none;
text-transform: capitalize; }
.btn-primary table td {
background-color: #3498db; }
.btn-primary a {
background-color: #3498db;
border-color: #3498db;
color: #ffffff; }
/* -------------------------------------
OTHER STYLES THAT MIGHT BE USEFUL
------------------------------------- */
.last {
margin-bottom: 0; }
.first {
margin-top: 0; }
.align-center {
text-align: center; }
.align-right {
text-align: right; }
.align-left {
text-align: left; }
.clear {
clear: both; }
.mt0 {
margin-top: 0; }
.mb0 {
margin-bottom: 0; }
.preheader {
color: transparent;
display: none;
height: 0;
max-height: 0;
max-width: 0;
opacity: 0;
overflow: hidden;
mso-hide: all;
visibility: hidden;
width: 0; }
.powered-by a {
text-decoration: none; }
hr {
border: 0;
border-bottom: 1px solid #f6f6f6;
Margin: 20px 0; }
/* -------------------------------------
RESPONSIVE AND MOBILE FRIENDLY STYLES
------------------------------------- */
@media only screen and (max-width: 620px) {
table[class=body] h1 {
font-size: 28px !important;
margin-bottom: 10px !important; }
table[class=body] p,
table[class=body] ul,
table[class=body] ol,
table[class=body] td,
table[class=body] span,
table[class=body] a {
font-size: 16px !important; }
table[class=body] .wrapper,
table[class=body] .article {
padding: 10px !important; }
table[class=body] .content {
padding: 0 !important; }
table[class=body] .container {
padding: 0 !important;
width: 100% !important; }
table[class=body] .main {
border-left-width: 0 !important;
border-radius: 0 !important;
border-right-width: 0 !important; }
table[class=body] .btn table {
width: 100% !important; }
table[class=body] .btn a {
width: 100% !important; }
table[class=body] .img-responsive {
height: auto !important;
max-width: 100% !important;
width: auto !important; }}
/* -------------------------------------
PRESERVE THESE STYLES IN THE HEAD
------------------------------------- */
@media all {
.ExternalClass {
width: 100%; }
.ExternalClass,
.ExternalClass p,
.ExternalClass span,
.ExternalClass font,
.ExternalClass td,
.ExternalClass div {
line-height: 100%; }
.apple-link a {
color: inherit !important;
font-family: inherit !important;
font-size: inherit !important;
font-weight: inherit !important;
line-height: inherit !important;
text-decoration: none !important; }
.btn-primary table td:hover {
background-color: #34495e !important; }
.btn-primary a:hover {
background-color: #34495e !important;
border-color: #34495e !important; } }
</style>
</head>
<body class="">
<table border="0" cellpadding="0" cellspacing="0" class="body">
<tr>
<td>&nbsp;</td>
<td class="container">
<div class="content">
<!-- START CENTERED WHITE CONTAINER -->
<span class="preheader">This is preheader text. Some clients will show this text as a preview.</span>
<table class="main">
<!-- START MAIN CONTENT AREA -->
<tr>
<td class="wrapper">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<img src=".\images\OpenDMP.png" alt="OpenDMP" width="100" height="81">
<h2>Thank you for joining OpenDMP!</h2>
<p>Please confirm that your email address is correct to continue.
<br/>The link will expire in {expiration_time}.</p>
<table border="0" cellpadding="0" cellspacing="0" class="btn btn-primary">
<tbody>
<tr>
<td align="left">
<table border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td> <a href="{host}/confirmation/{confirmationToken}" target="_blank">Confirm Email Address</a> </td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</table>
</td>
</tr>
<!-- END MAIN CONTENT AREA -->
</table>
<!-- START FOOTER -->
<div class="footer">
</div>
<!-- END FOOTER -->
<!-- END CENTERED WHITE CONTAINER -->
</div>
</td>
<td>&nbsp;</td>
</tr>
</table>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

View File

@ -0,0 +1,2 @@
ALTER TABLE public."DMP"
ADD COLUMN "DOI" text

View File

@ -0,0 +1,17 @@
CREATE TABLE public."LoginConfirmationEmail"
(
"ID" uuid NOT NULL,
email character varying COLLATE pg_catalog."default" NOT NULL,
"isConfirmed" boolean NOT NULL,
token uuid NOT NULL,
userId uuid NOT NULL,
"expiresAt" timestamp(4) with time zone NOT NULL,
CONSTRAINT "LoginConfirmationEmail_pkey" PRIMARY KEY ("ID")
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default;
ALTER TABLE public."LoginConfirmationEmail"
OWNER to dmtadm;

View File

@ -0,0 +1,3 @@
ALTER TABLE public."UserInfo"
ALTER COLUMN "email"
DROP NOT NULL

View File

@ -7,6 +7,7 @@ import { ProgressIndicationInterceptor } from './interceptors/progress-indicatio
import { RequestTimingInterceptor } from './interceptors/request-timing.interceptor';
import { ResponsePayloadInterceptor } from './interceptors/response-payload.interceptor';
import { UnauthorizedResponseInterceptor } from './interceptors/unauthorized-response.interceptor';
import { StatusCodeInterceptor } from './interceptors/status-code.interceptor';
@NgModule({
imports: [
@ -48,6 +49,11 @@ import { UnauthorizedResponseInterceptor } from './interceptors/unauthorized-res
provide: HTTP_INTERCEPTORS,
useClass: ResponsePayloadInterceptor,
multi: true,
},
{
provide: HTTP_INTERCEPTORS,
useClass: StatusCodeInterceptor,
multi: true,
}
]
})

View File

@ -6,4 +6,5 @@ export enum InterceptorType {
RequestTiming = 4,
UnauthorizedResponse = 5,
ResponsePayload = 5,
StatusCode = 6
}

View File

@ -0,0 +1,23 @@
import { Injectable } from "@angular/core";
import { BaseInterceptor } from "./base.interceptor";
import { InterceptorType } from "./interceptor-type";
import { HttpHandler, HttpRequest, HttpEvent } from "@angular/common/http";
import { Observable } from "rxjs";
import { Router } from "@angular/router";
@Injectable()
export class StatusCodeInterceptor extends BaseInterceptor {
type: InterceptorType;
interceptRequest(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent <any>> {
return next.handle(req).do(event => { }, err => {
if (err.status === 480) {
this.router.navigate(['confirmation']);
}
});
}
constructor(
private router: Router,
) { super(); }
}

View File

@ -4,5 +4,6 @@ export enum AuthProvider {
Twitter = 3,
LinkedIn = 4,
//NativeLogin=5,
B2Access = 6
B2Access = 6,
ORCID = 7
}

View File

@ -33,6 +33,7 @@ import { CollectionUtils } from './services/utilities/collection-utils.service';
import { TypeUtils } from './services/utilities/type-utils.service';
import { QuickWizardService } from './services/quick-wizard/quick-wizard.service';
import { OrganisationService } from './services/organisation/organisation.service';
import { EmailConfirmationService } from './services/email-confirmation/email-confirmation.service';
//
//
// This is shared module that provides all the services. Its imported only once on the AppModule.
@ -85,7 +86,8 @@ export class CoreServiceModule {
DmpInvitationService,
DatasetExternalAutocompleteService,
QuickWizardService,
OrganisationService
OrganisationService,
EmailConfirmationService
],
};
}

View File

@ -26,4 +26,5 @@ export interface DmpOverviewModel {
researchers: ResearcherModel[];
finalizedAt: Date;
publishedAt: Date;
doi: string;
}

View File

@ -0,0 +1,5 @@
export class OrcidUser {
orcidId: string;
name: string;
email: string;
}

View File

@ -92,6 +92,10 @@ export class DmpService {
return this.http.post<DmpModel>(this.actionUrl + 'finalize/' + id, datasetsToBeFinalized, { headers: this.headers });
}
getDoi(id: string): Observable<string> {
return this.http.post<string>(this.actionUrl + 'createZenodoDoi/' + id, {headers: this.headers});
}
getDynamicField(requestItem: RequestItem<DynamicFieldProjectCriteria>): any {
return this.http.post<any>(this.actionUrl + 'dynamic', requestItem, { headers: this.headers });
}

View File

@ -0,0 +1,22 @@
import { Injectable } from "@angular/core";
import { HttpHeaders } from "@angular/common/http/src/headers";
import { BaseHttpService } from "../http/base-http.service";
import { environment } from "../../../../environments/environment";
@Injectable()
export class EmailConfirmationService {
private actioUrl: string;
private headers: HttpHeaders
constructor(private http: BaseHttpService) {
this.actioUrl = environment.Server + 'emailConfirmation/';
}
public emailConfirmation(token: string) {
return this.http.get<String>(this.actioUrl + token, { headers: this.headers });
}
public sendConfirmationEmail(email: string) {
return this.http.post<String>(this.actioUrl, email, {headers: this.headers});
}
}

View File

@ -5,10 +5,14 @@
</div>
<div class="col-auto close-btn" (click)="close()"><mat-icon>close</mat-icon></div>
</div>
<div class="row d-flex flex-row">
<div *ngIf="!isFinalized()" class="row d-flex flex-row">
<div class="col-3"><button mat-raised-button type="button" (click)="downloadXML()" >{{ data.XMLButton }}</button></div>
<div class="col-3"><button mat-raised-button type="button" (click)="downloadDocument()">{{ data.documentButton }}</button></div>
<div class="col-3"><button mat-raised-button type="button" (click)="downloadPdf()">{{ data.pdfButton }}</button></div>
<div class="col-3"><button mat-raised-button type="button" (click)="downloadJson()">{{ data.jsonButton }}</button></div>
</div>
<div *ngIf="isFinalized()" class="row d-flex flex-row">
<div class="col-6"><button mat-raised-button type="button" (click)="downloadDocument()">{{ data.documentButton }}</button></div>
<div class="col-6"><button mat-raised-button type="button" (click)="downloadPdf()">{{ data.pdfButton }}</button></div>
</div>
</div>

View File

@ -36,4 +36,8 @@ export class ExportMethodDialogComponent implements OnInit {
downloadJson() {
this.dialogRef.close("json");
}
isFinalized() {
return this.data.isFinalized;
}
}

View File

@ -0,0 +1,22 @@
<div class="main-content" *ngIf="showForm">
<div class="container-fluid">
<div class="card">
<div class="card-header card-header-plain d-flex">
<h4 class="card-title">{{ 'EMAIL-CONFIRMATION.CARD-TITLE' | translate }}</h4>
</div>
<div class="card-body table-responsive">
<form class="form" *ngIf="!mailSent">
<h5>{{ 'EMAIL-CONFIRMATION.REQUEST-EMAIL-HEADER' | translate }}</h5>
<p>{{ 'EMAIL-CONFIRMATION.REQUEST-EMAIL-TEXT' | translate }}</p>
<mat-form-field class="full-width">
<input matInput placeholder="Your Email" [formControl]="emailFormControl">
</mat-form-field>
<button mat-raised-button color="primary" (click)="sendConfirmationEmail()" class="lightblue-btn">
{{ 'EMAIL-CONFIRMATION.SUBMIT' | translate }}
</button>
</form>
<h5 *ngIf="mailSent">{{ 'EMAIL-CONFIRMATION.SENT-EMAIL-HEADER' | translate }}</h5>
</div>
</div>
</div>
</div>

View File

@ -0,0 +1,5 @@
.form {
min-width: 150px;
max-width: 500px;
width: 100%;
}

View File

@ -0,0 +1,68 @@
import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Params, Router } from "@angular/router";
import { takeUntil } from "rxjs/operators";
import { BaseComponent } from "../../../../core/common/base/base.component";
import { EmailConfirmationService } from "../../../../core/services/email-confirmation/email-confirmation.service";
import { UiNotificationService, SnackBarNotificationLevel } from "../../../../core/services/notification/ui-notification-service";
import { TranslateService } from "@ngx-translate/core";
import { FormControl } from "@angular/forms";
@Component({
selector: 'app-email-confirmation-component',
templateUrl: './email-confirmation.component.html'
})
export class EmailConfirmation extends BaseComponent implements OnInit {
private emailFormControl = new FormControl('');
private showForm: boolean = false;
private mailSent: boolean = false;
constructor(
private emailConfirmationService: EmailConfirmationService,
private route: ActivatedRoute,
private router: Router,
private language: TranslateService,
private uiNotificationService: UiNotificationService
) { super(); }
ngOnInit() {
this.route.params
.pipe(takeUntil(this._destroyed))
.subscribe(params => {
const token = params['token']
if (token != null) {
this.showForm = false;
this.emailConfirmationService.emailConfirmation(token)
.pipe(takeUntil(this._destroyed))
.subscribe(
result => this.onCallbackEmailConfirmationSuccess(),
error => this.onCallbackError(error)
)
} else {
this.showForm = true;
}
});
}
sendConfirmationEmail() {
this.emailConfirmationService.sendConfirmationEmail(this.emailFormControl.value)
.pipe(takeUntil(this._destroyed))
.subscribe(
result => this.onCallbackSuccess(),
error => this.onCallbackError(error)
)
}
onCallbackSuccess() {
this.mailSent = true;
}
onCallbackEmailConfirmationSuccess() {
this.router.navigate(['home']);
}
onCallbackError(error: any) {
this.uiNotificationService.snackBarNotification(this.language.instant('EMAIL-CONFIRMATION.EXPIRED-EMAIL'), SnackBarNotificationLevel.Error);
this.router.navigate(['login']);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@ -2,29 +2,40 @@
<div class="login-logo"></div>
<div class="card login-card">
<div class="card-header">
<div class="social-btns d-flex">
<button *ngIf="hasGoogleOauth()" mat-icon-button id="googleSignInButton" class="login-social-button">
<i class="fa fa-google"></i>
</button>
<button *ngIf="hasLinkedInOauth()" mat-icon-button class="login-social-button">
<i class="fa fa-linkedin" (click)="linkedInLogin()"></i>
</button>
<button *ngIf="hasFacebookOauth()" mat-icon-button (click)="facebookLogin()" class="login-social-button">
<i class="fa fa-facebook-square"></i>
</button>
<button *ngIf="hasTwitterOauth()" mat-icon-button (click)="twitterLogin()" class="login-social-button">
<i class="fa fa-twitter"></i>
</button>
<button *ngIf="hasB2AccessOauth()" class="b2access-button" mat-icon-button (click)="b2AccessLogin()" class="login-social-button">
<span class="iconmedium"></span>
<span></span>
</button>
<div class="social-btns d-flex flex-column">
<div class="row">
<button *ngIf="hasGoogleOauth()" mat-icon-button id="googleSignInButton" class="login-social-button">
<i class="fa fa-google"></i>
</button>
<button *ngIf="hasLinkedInOauth()" mat-icon-button class="login-social-button">
<i class="fa fa-linkedin" (click)="linkedInLogin()"></i>
</button>
<button *ngIf="hasFacebookOauth()" mat-icon-button (click)="facebookLogin()" class="login-social-button">
<i class="fa fa-facebook-square"></i>
</button>
<button *ngIf="hasTwitterOauth()" mat-icon-button (click)="twitterLogin()" class="login-social-button">
<i class="fa fa-twitter"></i>
</button>
</div>
<div class="row justify-content-center">
<button *ngIf="hasB2AccessOauth()" class="b2access-button" mat-icon-button (click)="b2AccessLogin()" class="login-social-button">
<span class="iconmedium"></span>
<span></span>
</button>
<button *ngIf="hasOrcidOauth()" class="orcid-button" mat-icon-button (click)="orcidLogin()" class="login-social-button">
<span class="orcidIconMedium"></span>
<span></span>
</button>
</div>
</div>
</div>
<div class="card-footer">
<h4 class="text-uppercase"><strong>Login</strong></h4>
<h4 class="text-uppercase">
<strong>{{ 'HOME.LOGIN.TITLE' | translate }}</strong>
</h4>
<br />
<h5>{{ 'HOME.LOGIN' | translate }}</h5>
<h5>{{ 'HOME.LOGIN.TEXT' | translate }}</h5>
</div>
</div>
</div>

View File

@ -175,11 +175,26 @@ span.iconmedium {
margin-right: 2em;
}
span.orcidIconMedium {
background: url(img/ORCIDiD_medium.png) no-repeat;
background-position: center;
float: right;
width: 100px;
height: 56px;
margin-left: 2em;
margin-right: 2em;
}
.b2access-button {
margin-top: 10px;
width: fit-content;
}
.orcid-button {
margin-top: 10px;
width: fit-content;
}
.login-logo {
background: url(img/open-dmp.png) no-repeat;
width: 370px;

View File

@ -51,7 +51,11 @@ export class LoginComponent extends BaseComponent implements OnInit, AfterViewIn
}
public b2AccessLogin() {
this.router.navigate(['/api/oauth/authorized/b2access']);
this.router.navigate(['/login/external/b2access']);
}
public orcidLogin() {
this.router.navigate(['/login/external/orcid']);
}
public hasFacebookOauth(): boolean {
@ -74,6 +78,10 @@ export class LoginComponent extends BaseComponent implements OnInit, AfterViewIn
return this.hasProvider(AuthProvider.B2Access);
}
public hasOrcidOauth(): boolean {
return this.hasProvider(AuthProvider.ORCID);
}
public initProviders() {
if (this.hasProvider(AuthProvider.Google)) { this.initializeGoogleOauth(); }
if (this.hasProvider(AuthProvider.Facebook)) { this.initializeFacebookOauth(); }
@ -93,6 +101,7 @@ export class LoginComponent extends BaseComponent implements OnInit, AfterViewIn
case AuthProvider.LinkedIn: return this.hasAllRequiredFieldsConfigured(environment.loginProviders.linkedInConfiguration);
case AuthProvider.Twitter: return this.hasAllRequiredFieldsConfigured(environment.loginProviders.twitterConfiguration);
case AuthProvider.B2Access: return this.hasAllRequiredFieldsConfigured(environment.loginProviders.b2accessConfiguration);
case AuthProvider.ORCID: return this.hasAllRequiredFieldsConfigured(environment.loginProviders.orcidConfiguration);
default: throw new Error('Unsupported Provider Type');
}
}

View File

@ -7,6 +7,8 @@ import { LoginRoutingModule } from './login.routing';
import { TwitterLoginComponent } from './twitter-login/twitter-login.component';
import { LoginService } from './utilities/login.service';
import { B2AccessLoginComponent } from './b2access/b2access-login.component';
import { OrcidLoginComponent } from './orcid-login/orcid-login.component';
import { EmailConfirmation } from './email-confirmation/email-confirmation.component';
@NgModule({
imports: [
@ -18,7 +20,9 @@ import { B2AccessLoginComponent } from './b2access/b2access-login.component';
LoginComponent,
LinkedInLoginComponent,
TwitterLoginComponent,
B2AccessLoginComponent
B2AccessLoginComponent,
OrcidLoginComponent,
EmailConfirmation
],
providers: [LoginService]
})

View File

@ -3,15 +3,20 @@ import { RouterModule, Routes } from '@angular/router';
import { LinkedInLoginComponent } from './linkedin-login/linkedin-login.component';
import { LoginComponent } from './login.component';
import { TwitterLoginComponent } from './twitter-login/twitter-login.component';
import { EmailConfirmation } from './email-confirmation/email-confirmation.component';
import { OrcidLoginComponent } from './orcid-login/orcid-login.component';
const routes: Routes = [
{ path: '', component: LoginComponent },
{ path: 'linkedin', component: LinkedInLoginComponent },
{ path: 'twitter', component: TwitterLoginComponent }
{ path: 'twitter', component: TwitterLoginComponent },
{ path: 'external/orcid', component: OrcidLoginComponent },
{ path: 'confirmation/:token', component: EmailConfirmation },
{ path: 'confirmation', component: EmailConfirmation }
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class LoginRoutingModule { }
export class LoginRoutingModule { }

View File

@ -0,0 +1,81 @@
import { Component, OnInit } from '@angular/core';
import { BaseComponent } from '../../../../core/common/base/base.component';
import { LoginService } from '../utilities/login.service';
import { ActivatedRoute, Params } from '@angular/router';
import { takeUntil } from 'rxjs/operators';
import { environment } from '../../../../../environments/environment';
import { AuthService } from '../../../../core/services/auth/auth.service';
import { AuthProvider } from '../../../../core/common/enum/auth-provider';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { OrcidUser } from '../../../../core/model/orcid/orcidUser';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-orcid-login',
templateUrl: './orcid-login.component.html',
styleUrls: ['./orcid-login.component.scss']
})
export class OrcidLoginComponent extends BaseComponent implements OnInit {
private returnUrl: string;
private orcidUser: OrcidUser
private accessToken: string;
private emailFormControl = new FormControl('');
constructor(
private route: ActivatedRoute,
private authService: AuthService,
private loginService: LoginService,
private httpClient: HttpClient
) {
super();
this.orcidUser = new OrcidUser;
}
ngOnInit(): void {
this.route.queryParams
.pipe(takeUntil(this._destroyed))
.subscribe((params: Params) => {
const returnUrl = params['returnUrl'];
if (returnUrl) { this.returnUrl = returnUrl; }
if (!params['code']) { this.orcidAccessGetAuthCode(); } else { this.orcidLogin(params['code']); }
});
}
public orcidAccessGetAuthCode() {
window.location.href = environment.loginProviders.orcidConfiguration.oauthUrl
+ '?client_id='
+ environment.loginProviders.orcidConfiguration.clientId
+ '&response_type=code&scope=/authenticate&redirect_uri='
+ environment.loginProviders.orcidConfiguration.redirectUri;
}
public orcidLogin(code: string) {
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json');
headers = headers.set('Accept', 'application/json');
this.httpClient.post(environment.Server + 'auth/orcidRequestToken', { code: code }, { headers: headers })
.pipe(takeUntil(this._destroyed))
.subscribe((responseData: any) => {
this.orcidUser.orcidId = responseData.payload.orcidId
this.orcidUser.name = responseData.payload.name
this.accessToken = responseData.payload.accessToken;
this.authService.login({ ticket: this.accessToken, provider: AuthProvider.ORCID, data: this.orcidUser })
.pipe(takeUntil(this._destroyed))
.subscribe(
res => this.loginService.onLogInSuccess(res, this.returnUrl),
error => this.loginService.onLogInError(error)
);
});
}
public login() {
this.orcidUser.email = this.emailFormControl.value;
this.authService.login({ ticket: this.accessToken, provider: AuthProvider.ORCID, data: this.orcidUser })
.pipe(takeUntil(this._destroyed))
.subscribe(
res => this.loginService.onLogInSuccess(res, this.returnUrl),
error => this.loginService.onLogInError(error)
);
}
}

View File

@ -4,6 +4,9 @@
<div class="card-header card-header-plain d-flex">
<div class="card-desc d-flex flex-column justify-content-center">
<h4 class="card-title">{{ dmp.label }}</h4>
<mat-card-subtitle *ngIf="!hasDoi(dmp)">
{{ 'DMP-EDITOR.TITLE.SUBTITLE' | translate }}: {{ dmp.doi }}
</mat-card-subtitle>
</div>
<div class="d-flex ml-auto p-2">
<button *ngIf="isDraftDmp(dmp)" mat-icon-button [matMenuTriggerFor]="actionsMenu" class="ml-auto more-icon"
@ -24,6 +27,15 @@
<mat-icon>save_alt</mat-icon>{{ 'DMP-LISTING.ACTIONS.ADV-EXP' | translate }}
</button>
</mat-menu>
<button *ngIf="isFinalizedDmp(dmp)" mat-icon-button [matMenuTriggerFor]="actionsMenuFinalized" class="ml-auto more-icon"
(click)="$event.stopImmediatePropagation();">
<mat-icon class="more-horiz">more_horiz</mat-icon>
</button>
<mat-menu #actionsMenuFinalized="matMenu">
<button mat-menu-item (click)="advancedClickedFinalized()" class="menu-item">
<mat-icon>save_alt</mat-icon>{{ 'DMP-LISTING.ACTIONS.ADV-EXP' | translate }}
</button>
</mat-menu>
<button mat-raised-button color="primary" (click)="downloadPDF(dmp.id)" class="lightblue-btn ml-2">
<mat-icon>save_alt</mat-icon> {{ 'DMP-LISTING.ACTIONS.EXPORT' | translate }}
</button>
@ -33,6 +45,9 @@
<button *ngIf="isDraftDmp(dmp)" mat-raised-button color="primary" (click)="finalize(dmp)" class="lightblue-btn ml-2">
<mat-icon>done_all</mat-icon> {{ 'DMP-LISTING.ACTIONS.FINALIZE' | translate }}
</button>
<button *ngIf="hasDoi(dmp) && isFinalizedDmp(dmp)" mat-raised-button color="primary" (click)="getDoi(dmp)" class="lightblue-btn ml-2">
<mat-icon>archive</mat-icon> {{ 'DMP-LISTING.ACTIONS.GETDOI' | translate }}
</button>
</div>
</div>
<div class="row ml-2">

View File

@ -126,8 +126,8 @@ export class DmpOverviewComponent extends BaseComponent implements OnInit {
this.dmpService.delete(this.dmp.id)
.pipe(takeUntil(this._destroyed))
.subscribe(
complete => { this.onCallbackSuccess() },
error => this.onDeleteCallbackError(error)
complete => { this.onCallbackSuccess() },
error => this.onDeleteCallbackError(error)
);
}
});
@ -157,6 +157,25 @@ export class DmpOverviewComponent extends BaseComponent implements OnInit {
});
}
advancedClickedFinalized() {
const dialogRef = this.dialog.open(ExportMethodDialogComponent, {
maxWidth: '250px',
data: {
message: "Download as:",
documentButton: "Document",
pdfButton: "PDF",
isFinalized: true
}
});
dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
if (result == "pdf") {
this.downloadPDF(this.dmp.id);
} else if (result == "doc") {
this.downloadDocx(this.dmp.id);
}
});
}
onCallbackSuccess(): void {
this.uiNotificationService.snackBarNotification(this.isNew ? this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-CREATION') : this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-UPDATE'), SnackBarNotificationLevel.Success);
this.router.navigate(['/plans']);
@ -260,6 +279,42 @@ export class DmpOverviewComponent extends BaseComponent implements OnInit {
return dmp.status == DmpStatus.Finalized;
}
hasDoi(dmp: DmpOverviewModel) {
return dmp.doi == null ? true : false;
}
getDoi(dmp: DmpOverviewModel) {
const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
maxWidth: '600px',
data: {
message: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ZENODO-DOI'),
confirmButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CONFIRM'),
cancelButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CANCEL'),
}
});
dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
if (result) {
this.dmpService.getDoi(dmp.id)
.pipe(takeUntil(this._destroyed))
.subscribe(
complete => {
this.onDOICallbackSuccess();
this.dmp.doi = complete;
},
error => this.onDeleteCallbackError(error)
);
}
});
}
onDOICallbackSuccess(): void {
this.uiNotificationService.snackBarNotification(this.language.instant('DMP-EDITOR.SNACK-BAR.SUCCESSFUL-DOI'), SnackBarNotificationLevel.Success);
}
onDOICallbackError(error) {
this.uiNotificationService.snackBarNotification(error.error.message ? error.error.message : this.language.instant('DMP-EDITOR.SNACK-BAR.UNSUCCESSFUL-DOI'), SnackBarNotificationLevel.Error);
}
showPublishButton(dmp: DmpOverviewModel) {
return this.isFinalizedDmp(dmp) && !dmp.isPublic && this.hasPublishButton;
}
@ -291,16 +346,23 @@ export class DmpOverviewComponent extends BaseComponent implements OnInit {
});
dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe((result: DmpFinalizeDialogOutput) => {
if (result && !result.cancelled) {
this.dmp.status = DmpStatus.Finalized;
var datasetsToBeFinalized: DatasetsToBeFinalized = {
uuids: result.datasetsToBeFinalized
};
this.dmpService.finalize(datasetsToBeFinalized, this.dmp.id)
.pipe(takeUntil(this._destroyed))
.subscribe(
complete => this.onCallbackSuccess()
complete => {
this.dmp.status = DmpStatus.Finalized;
this.onCallbackSuccess()
},
error => this.onFinalizeCallbackError(error)
);
}
});
}
onFinalizeCallbackError(error) {
this.uiNotificationService.snackBarNotification(error.error.message ? error.error.message : this.language.instant('DMP-EDITOR.SNACK-BAR.UNSUCCESSFUL-FINALIZE'), SnackBarNotificationLevel.Error);
}
}

View File

@ -62,7 +62,6 @@ export class DmpWizardComponent extends BaseComponent implements OnInit, IBreadC
breadCrumbs.push({ parentComponentName: null, label: this.language.instant('NAV-BAR.MY-DMPS'), url: "/plans" });
breadCrumbs.push({ parentComponentName: 'DmpListingComponent', label: this.dmp.label, url: '/plans/clone/' + this.dmp.id });
this.breadCrumbs = Observable.of(breadCrumbs);
console.log(this.breadCrumbs);
});
});
}

View File

@ -154,7 +154,6 @@ export class ExploreDmpFiltersComponent extends BaseCriteriaComponent implements
}
projectStatusChanged(event) {
console.log(event);
this.facetCriteria.projectStatus = event.value;
// this.facetCriteria.projectStatus = +event.source.ariaLabel; // For checkboxes
// this.facetCriteria.projectStatus = event.option.value.value; // For <app-explore-dmp-filter-item-component>

View File

@ -37,6 +37,7 @@
"DELETE-USER": "Remove this collaborator?",
"FINALIZE-ITEM": "Finalize this item?",
"ADD-DATASET": "Proceed on adding new Dataset?",
"ZENODO-DOI": "Would you like to create digital object identifier (DOI) for the DMP?",
"ACTIONS": {
"CONFIRM": "Yes",
"No": "No",
@ -51,10 +52,21 @@
"LOG-IN": "Log in"
}
},
"EMAIL-CONFIRMATION": {
"EXPIRED-EMAIL": "Mail invitation expired",
"CARD-TITLE": "E-mail",
"REQUEST-EMAIL-HEADER": "We are almost done! Please fill your e-mail.",
"REQUEST-EMAIL-TEXT": "You will need to confirm it to use the application.",
"SUBMIT": "Submit",
"SENT-EMAIL-HEADER": "Email was send!"
},
"HOME": {
"DMPS": "DMPs",
"DATASETS": "Datasets",
"LOGIN": "You dont need to have a registered account for OpenDMP"
"LOGIN": {
"TITLE": "Login",
"TEXT": "You dont need to have a registered account for OpenDMP"
}
},
"NAV-BAR": {
"BREADCRUMB-ROOT": "Dashboard",
@ -282,7 +294,8 @@
"DOWNLOAD-XML": "Download XML",
"DOWNLOAD-DOCX": "Download Document",
"DOWNLOAD-PDF": "Download PDF",
"SETTINGS": "Settings"
"SETTINGS": "Settings",
"GETDOI": "Get DOI"
}
},
"DMP-PUBLIC-LISTING": {
@ -478,7 +491,8 @@
"DMP-EDITOR": {
"TITLE": {
"NEW": "New Data Management Plan",
"EDIT": "Edit"
"EDIT": "Edit",
"SUBTITLE": "DOI"
},
"FIELDS": {
"NAME": "Title",
@ -503,6 +517,11 @@
"CANCEL": "Cancel",
"DELETE": "Delete",
"FINALISE": "Finalize"
},
"SNACK-BAR": {
"UNSUCCESSFUL-DOI": "Unsuccessful DOI creation",
"SUCCESSFUL-DOI": "Successful DOI creation",
"UNSUCCESSFUL-FINALIZE": "Unsuccessful DMP finalization"
}
},
"DMP-PROFILE-LISTING": {

View File

@ -8,7 +8,7 @@ export const environment = {
},
defaultCulture: 'en-US',
loginProviders: {
enabled: [1, 2, 3, 4, 5],
enabled: [1, 2, 3, 4, 5, 6],
facebookConfiguration: { clientId: '' },
googleConfiguration: { clientId: '' },
linkedInConfiguration: {
@ -24,6 +24,11 @@ export const environment = {
clientId: '',
oauthUrl: 'https://b2access-integration.fz-juelich.de:443/oauth2-as/oauth2-authz',
redirectUri: 'http://opendmp.eu/api/oauth/authorized/b2access'
},
orcidConfiguration: {
clientId: 'APP-766DI5LP8T75FC4R',
oauthUrl: 'https://sandbox.orcid.org/oauth/authorize',
redirectUri: 'http://opendmp.eu/api/oauth/authorized/orcid'
}
},
logging: {

View File

@ -8,7 +8,7 @@ export const environment = {
},
defaultCulture: 'en-US',
loginProviders: {
enabled: [1, 2, 3, 4, 5],
enabled: [1, 2, 3, 4, 5, 6],
facebookConfiguration: { clientId: '' },
googleConfiguration: { clientId: '596924546661-83nhl986pnrpug5h624i5kptuao03dcd.apps.googleusercontent.com' },
linkedInConfiguration: {
@ -24,6 +24,11 @@ export const environment = {
clientId: '',
oauthUrl: 'https://b2access-integration.fz-juelich.de:443/oauth2-as/oauth2-authz',
redirectUri: 'http://devel.opendmp.eu/api/oauth/authorized/b2access'
},
orcidConfiguration: {
clientId: '',
oauthUrl: 'https://sandbox.orcid.org/oauth/authorize',
redirectUri: 'http://opendmp.eu/api/oauth/authorized/orcid'
}
},
logging: {

View File

@ -8,7 +8,7 @@ export const environment = {
},
defaultCulture: 'en-US',
loginProviders: {
enabled: [1, 2, 3, 4, 5, 6],
enabled: [1, 2, 3, 4, 5, 6, 7],
facebookConfiguration: { clientId: '' },
googleConfiguration: { clientId: '' },
linkedInConfiguration: {
@ -24,6 +24,11 @@ export const environment = {
clientId: '',
oauthUrl: 'https://b2access-integration.fz-juelich.de:443/oauth2-as/oauth2-authz',
redirectUri: 'http://opendmp.eu/api/oauth/authorized/b2access'
},
orcidConfiguration: {
clientId: 'APP-766DI5LP8T75FC4R',
oauthUrl: 'https://orcid.org/oauth/authorize',
redirectUri: 'http://localhost:4200/login/external/orcid'
}
},
logging: {