Merge pull request #53 from Kitzanos/feature/GEPAFINBE-19

GEPAFINBE-19(Implemented hub)
This commit is contained in:
rbonazzo-KZ
2024-10-20 10:13:33 +02:00
committed by GitHub
52 changed files with 1310 additions and 328 deletions

View File

@@ -29,6 +29,7 @@ import org.opensaml.xmlsec.signature.support.SignatureConstants;
import org.opensaml.xmlsec.signature.support.Signer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -45,6 +46,9 @@ import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.entities.SamlResponseEntity;
import net.gepafin.tendermanagement.enums.SamlResponseStatusEnum;
import net.gepafin.tendermanagement.repositories.SamlResponseRepository;
@Configuration
public class SamlConfig {
@@ -60,6 +64,9 @@ public class SamlConfig {
@Value("${active.profile.folder}")
String activeProfileFolder;
@Autowired
private SamlResponseRepository samlResponseRepository;
@Bean
public RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() {
@@ -135,18 +142,24 @@ public class SamlConfig {
authenticationRequestResolver.setAuthnRequestCustomizer((context) -> {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
String hubId = (String) request.getAttribute("hubId");
String hubUuid = (String) request.getAttribute("hubId");
logger.info("Hub id " + hubId);
logger.info("Hub id " + hubUuid);
String inResponseTo = "_" + UUID.randomUUID().toString();
// Continue with normal AuthnRequest configuration
AuthnRequest authnRequest = context.getAuthnRequest();
authnRequest.setID("_" + UUID.randomUUID().toString()+":"+hubId);
authnRequest.setID(inResponseTo);
authnRequest.setVersion(SAMLVersion.VERSION_20);
authnRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI);
authnRequest.setRequestedAuthnContext(buildRequestedAuthnContext());
SamlResponseEntity samlResponse = new SamlResponseEntity();
samlResponse.setHubUuid(hubUuid);
samlResponse.setInResponseTo(inResponseTo);
samlResponse.setStatus(SamlResponseStatusEnum.INITIATED.getValue());
samlResponseRepository.save(samlResponse);
// Log the SAML AuthnRequest after setting context
String samlRequest = SamlRequestLogger.convertSAMLObjectToString(authnRequest);
logger.info("SAML AuthnRequest after setting context: " + samlRequest);
@@ -156,21 +169,21 @@ public class SamlConfig {
}
private RequestedAuthnContext buildRequestedAuthnContext() {
AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder.buildObject(
SAMLConstants.SAML20_NS, AuthnContextClassRef.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX
);
// Set the SPID Level 2 authentication context
authnContextClassRef.setURI("urn:oasis:names:tc:SAML:2.0:ac:classes:SecureRemotePassword");
private RequestedAuthnContext buildRequestedAuthnContext() {
AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder.buildObject(
SAMLConstants.SAML20_NS, AuthnContextClassRef.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX
);
// Set the SPID Level 2 authentication context
authnContextClassRef.setURI("urn:oasis:names:tc:SAML:2.0:ac:classes:SecureRemotePassword");
RequestedAuthnContextBuilder requestedAuthnContextBuilder = new RequestedAuthnContextBuilder();
RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);
RequestedAuthnContextBuilder requestedAuthnContextBuilder = new RequestedAuthnContextBuilder();
RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);
return requestedAuthnContext;
}
return requestedAuthnContext;
}
public PrivateKey readPrivateKey() throws Exception {
// Path to your private key PEM file

View File

@@ -1,9 +1,13 @@
package net.gepafin.tendermanagement.config;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
@@ -11,6 +15,12 @@ import org.springframework.stereotype.Component;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.SamlResponseEntity;
import net.gepafin.tendermanagement.enums.SamlResponseStatusEnum;
import net.gepafin.tendermanagement.repositories.SamlResponseRepository;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
@Component
public class SamlFailureHandler implements AuthenticationFailureHandler {
@@ -20,16 +30,40 @@ public class SamlFailureHandler implements AuthenticationFailureHandler {
@Value("${fe.base.url}")
private String feBaseUrl;
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException {
try {
logger.error("SAML login failed: " + exception.getMessage());
@Autowired
private SamlResponseRepository samlResponseRepository;
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException {
try {
logger.error("SAML login failed: " + exception.getMessage());
String inResponseTo = extractInResponseTo(feBaseUrl);
if (Boolean.FALSE.equals(StringUtils.isEmpty(inResponseTo))) {
SamlResponseEntity samlResponseLogEntity = samlResponseRepository
.findByInResponseToAndStatus(inResponseTo, SamlResponseStatusEnum.INITIATED.getValue())
.orElseThrow(() -> new CustomValidationException(Status.BAD_REQUEST,
Translator.toLocale(GepafinConstant.INVALID_REQUEST)));
samlResponseLogEntity.setStatus(SamlResponseStatusEnum.FAILED.getValue());
samlResponseRepository.save(samlResponseLogEntity);
}
response.sendRedirect(feBaseUrl + "/login");
} catch (Exception e) {
logger.error("Error processing SAML failure handler", e);
}
}
} catch (Exception e) {
logger.error("Error processing SAML failure handler", e);
}
}
public static String extractInResponseTo(String message) {
String regex = "InResponseTo attribute \\[([a-zA-Z0-9\\-]+)\\]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(message);
if (matcher.find()) {
return matcher.group(1);
} else {
return null;
}
}
}

View File

@@ -2,13 +2,13 @@ package net.gepafin.tendermanagement.config;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -26,10 +26,13 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.HubEntity;
import net.gepafin.tendermanagement.entities.SamlResponseEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.enums.SamlResponseStatusEnum;
import net.gepafin.tendermanagement.repositories.SamlResponseRepository;
import net.gepafin.tendermanagement.repositories.UserRepository;
import net.gepafin.tendermanagement.service.HubService;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
@@ -48,6 +51,9 @@ public class SamlSuccessHandler implements AuthenticationSuccessHandler {
@Value("${fe.base.url}")
private String feBaseUrl;
@Autowired
private HubService hubService;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException {
@@ -60,16 +66,6 @@ public class SamlSuccessHandler implements AuthenticationSuccessHandler {
String token = Utils.generateSecureToken();
logger.info("SAML User Attributes: " + userAttributes);
SamlResponseEntity samlResponseLogEntity = new SamlResponseEntity();
samlResponseLogEntity.setAuthenticationObject(authentication.toString());
ObjectMapper objectMapper = new ObjectMapper();
String userAttributesJson = objectMapper.writeValueAsString(userAttributes);
samlResponseLogEntity.setAuthenticationObject(userAttributesJson);
samlResponseLogEntity.setToken(token);
samlResponseLogRepository.save(samlResponseLogEntity);
// Extracting raw SAML response
String samlResponse = samlAuth.getSaml2Response();
logger.info("Raw SAML Response: " + samlResponse);
@@ -90,7 +86,27 @@ public class SamlSuccessHandler implements AuthenticationSuccessHandler {
logger.info("InResponseTo: " + inResponseTo);
logger.info("IssueInstant: " + issueInstant);
SamlResponseEntity samlResponseLogEntity = samlResponseLogRepository
.findByInResponseToAndStatus(inResponseTo, SamlResponseStatusEnum.INITIATED.getValue())
.orElseThrow(() -> new CustomValidationException(Status.BAD_REQUEST,
Translator.toLocale(GepafinConstant.INVALID_REQUEST)));
ObjectMapper objectMapper = new ObjectMapper();
String userAttributesJson = objectMapper.writeValueAsString(userAttributes);
samlResponseLogEntity.setAuthenticationObject(userAttributesJson);
samlResponseLogEntity.setToken(token);
samlResponseLogEntity.setStatus(SamlResponseStatusEnum.SUCCESS.getValue());
samlResponseLogEntity.setInResponseTo(inResponseTo);
samlResponseLogEntity.setSamlId(responseId);
samlResponseLogEntity.setIssueInstant(issueInstant);
samlResponseLogRepository.save(samlResponseLogEntity);
HubEntity hub = hubService.getHubByUuid(samlResponseLogEntity.getHubUuid());
String redirectUrl = feBaseUrl;
if (Boolean.FALSE.equals(StringUtils.isEmpty(hub.getDomainName()))) {
redirectUrl = hub.getDomainName();
}
logger.info("SAML login successful for user: " + principal.getName());
String cf = userAttributes.get("CodiceFiscale").get(0).toString();
@@ -107,9 +123,9 @@ public class SamlSuccessHandler implements AuthenticationSuccessHandler {
}
}
public void validateToken(String token, String codiceFiscale) {
public void validateToken(String token, String codiceFiscale, String hubUuid) {
SamlResponseEntity samlResponseLogEntity = samlResponseLogRepository.findByToken(token);
if (samlResponseLogEntity == null) {
if (samlResponseLogEntity == null || Boolean.FALSE.equals(hubUuid.equals(samlResponseLogEntity.getHubUuid()))) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.INVALID_TOKEN_MSG));
}
@@ -120,7 +136,6 @@ public class SamlSuccessHandler implements AuthenticationSuccessHandler {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.INVALID_TOKEN_MSG));
}
samlResponseLogRepository.delete(samlResponseLogEntity);
}
}

View File

@@ -105,6 +105,10 @@ public class TokenProvider {
payload += ":"+user.getId();
}
if(user != null) {
payload += ":"+user.getHub().getId();
}
String token = Jwts.builder()
.setSubject(payload)
.claim("auth", authorities)

View File

@@ -233,6 +233,13 @@ public class GepafinConstant {
public static final String CANNOT_DELETE_COMPANY_WITH_APPLICATION_SUBMITT = "application.in.submit.status.cannot.delete.company";
public static final String GET_USERS_SUCCESS_MSG = "get.users.success.msg";
public static final String CANNOT_CREATE_BENEFICIARY_USER="cannot.create.beneficiary.user";
public static final String HUB_CREATE_SUCCESS = "hub_create_success";
public static final String HUB_UPDATE_SUCCESS = "hub_update_success";
public static final String HUB_GET_SUCCESS = "hub_get_success";
public static final String HUB_GET_ALL_SUCCESS = "hub_get_all_success";
public static final String HUB_DELETE_SUCCESS = "hub_delete_success";
public static final String HUB_NOT_FOUND = "hub_not_found";
public static final String EVALUATIONCRITERIA_INVALID = "evaluationCriteria.invalid";
}

View File

@@ -120,12 +120,16 @@ public class ApplicationDao {
@Value("${aws.s3.url.folder.signed.document}")
private String signedDocumentS3Folder;
@Value("${default.hub.uuid}")
private String defaultHubUuid;
public ApplicationResponseBean createApplication(ApplicationRequestBean applicationRequestBean, UserEntity userEntity, Long formId, Long applicationId) {
public ApplicationResponseBean createApplication(HttpServletRequest request, ApplicationRequestBean applicationRequestBean, Long formId, Long applicationId) {
FormEntity formEntity = formService.validateForm(formId);
// callService.validatePublishedCall(formEntity.getCall().getId());
validateFormFields(applicationRequestBean,formEntity);
ApplicationEntity applicationEntity = validateApplication(applicationId);
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
if(Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.SUBMIT.getValue()))) {
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_SUBMITTED));
}
@@ -229,10 +233,11 @@ public class ApplicationDao {
return applicationFormFieldResponseBeans;
}
public void deleteById(Long id) {
public void deleteById(HttpServletRequest request, Long id) {
log.info("Deleting application with ID: {}", id);
ApplicationEntity applicationEntity= validateApplication(id);
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
applicationEntity.setIsDeleted(true);
applicationEntity=saveApplicationEntity(applicationEntity);
log.info("Application deleted with ID: {}", id);
@@ -467,9 +472,10 @@ public class ApplicationDao {
return applicationEntity;
}
public ApplicationGetResponseBean getApplicationByFormId( Long applicationId, Long formId, UserEntity userEntity) {
public ApplicationGetResponseBean getApplicationByFormId(HttpServletRequest request, Long applicationId, Long formId) {
List<FormApplicationResponse> formApplicationResponses = new ArrayList<>();
List<FormEntity> formEntities = new ArrayList<>();
UserEntity userEntity = validator.validateUser(request);
boolean isBeneficiary = isBeneficiary(userEntity);
ApplicationEntity applicationEntity = isBeneficiary
? applicationRepository.findByIdAndUserIdAndIsDeletedFalse(applicationId, userEntity.getId())
@@ -574,8 +580,10 @@ public class ApplicationDao {
}
}
public ApplicationResponse updateApplicationStatus(UserEntity userEntity, Long applicationId, ApplicationStatusTypeEnum status) {
public ApplicationResponse updateApplicationStatus(HttpServletRequest request, Long applicationId, ApplicationStatusTypeEnum status) {
UserEntity userEntity = validator.validateUser(request);
ApplicationEntity applicationEntity = validateApplication(applicationId);
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
if (ApplicationStatusTypeEnum.SUBMIT.getValue().equals(applicationEntity.getStatus())) {
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_SUBMITTED_CANNOT_CHANGE));
}
@@ -602,8 +610,7 @@ public class ApplicationDao {
if (totalSteps.intValue() != completedSteps) {
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_IS_INCOMPLETE_MSG));
}
Integer maxProtocolNumber=protocolRepository.findMaxProtocolNumber();
Integer protocolNumber = (maxProtocolNumber != null) ? maxProtocolNumber + 1 : 1;
Long protocolNumber = getProtocolNumber(userEntity.getHub());
ProtocolEntity protocolEntity=createProtocolEntity(applicationEntity,protocolNumber);
applicationEntity.setProtocol(protocolEntity);
applicationEntity.setStatus(ApplicationStatusTypeEnum.SUBMIT.getValue());
@@ -618,6 +625,14 @@ public class ApplicationDao {
return getApplicationResponse(applicationEntity);
}
private Long getProtocolNumber(HubEntity hubEntity) {
Long maxProtocolNumber = protocolRepository.findMaxProtocolNumberAndHubId(hubEntity.getId());
Long startNumber = 10000001L;
if(Boolean.FALSE.equals(defaultHubUuid.equals(hubEntity.getUniqueUuid()))) {
startNumber = 20000001L;
}
return (maxProtocolNumber != null) ? maxProtocolNumber + 1 : startNumber;
}
public Integer calculateProgress(Long totalSteps, Long completedSteps) {
if (FieldValidator.isNullOrZero(totalSteps)) {
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.TOTAL_STEPS_NOT_BE_ZERO));
@@ -691,12 +706,12 @@ public class ApplicationDao {
}
}
public ProtocolEntity createProtocolEntity(ApplicationEntity applicationEntity,Integer protocolNumber){
public ProtocolEntity createProtocolEntity(ApplicationEntity applicationEntity,Long protocolNumber){
ProtocolEntity protocolEntity=new ProtocolEntity();
protocolEntity.setCall(applicationEntity.getCall().getId());
LocalDateTime utcDateTime = DateTimeUtil.DateServerToUTC(LocalDateTime.now());
protocolEntity.setYear(utcDateTime.getYear());
protocolEntity.setProtocolNumber(Long.valueOf(protocolNumber));
protocolEntity.setProtocolNumber(protocolNumber);
protocolEntity.setTime(LocalTime.now());
protocolEntity.setApplicationId(applicationEntity.getId());
protocolRepository.save(protocolEntity);

View File

@@ -85,9 +85,6 @@ public class CallDao {
@Autowired
private CallTargetAudienceChecklistRepository callTargetAudienceChecklistRepository;
@Autowired
private UserService userService;
@Autowired
private FaqService faqService;
@@ -106,10 +103,9 @@ public class CallDao {
@Autowired
private CriteriaFormFieldRepository criteriaFormFieldRepository;
public CallResponse createCallStep1(CreateCallRequestStep1 createCallRequest, Long userId) {
UserEntity userEntity = userService.validateUser(userId);
public CallResponse createCallStep1(CreateCallRequestStep1 createCallRequest, UserEntity userEntity) {
createCallRequest.setRegionId(userEntity.getRoleEntity().getRegion().getId());
CallEntity callEntity = convertToCallEntity(createCallRequest);
CallEntity callEntity = convertToCallEntity(createCallRequest, userEntity);
updateFaq(createCallRequest.getFaq(), callEntity, userEntity,LookUpDataTypeEnum.FAQ);
@@ -151,7 +147,7 @@ public class CallDao {
public CallEntity convertToCallEntity(CreateCallRequestStep1 createCallRequest) {
public CallEntity convertToCallEntity(CreateCallRequestStep1 createCallRequest, UserEntity userEntity) {
CallEntity callEntity = new CallEntity();
// validateCallEntity(createCallRequest);
RegionEntity region = regionRepository.findById(createCallRequest.getRegionId())
@@ -187,6 +183,7 @@ public class CallDao {
callEntity.setPhoneNumber(createCallRequest.getPhoneNumber());
callEntity.setStartTime(DateTimeUtil.parseTime(createCallRequest.getStartTime()));
callEntity.setEndTime(DateTimeUtil.parseTime(createCallRequest.getEndTime()));
callEntity.setHub(userEntity.getHub());
callEntity = callRepository.save(callEntity);
return callEntity;
}
@@ -433,13 +430,11 @@ public class CallDao {
Translator.toLocale(GepafinConstant.CALL_NOT_FOUND)));
}
public CallResponse getCallById(Long callId) {
CallEntity callEntity = validateCall(callId);
public CallResponse getCallById(CallEntity callEntity) {
return getCallResponseBean(callEntity);
}
public CallResponse createCallStep2(Long callId, CreateCallRequestStep2 createCallRequest, Long userId) {
CallEntity callEntity = validateCall(callId);
public CallResponse createCallStep2(CallEntity callEntity, CreateCallRequestStep2 createCallRequest, UserEntity user) {
validateUpdate(callEntity);
setIfUpdated(callEntity::getThreshold, callEntity::setThreshold, createCallRequest.getThreshold());
callRepository.save(callEntity);
@@ -499,8 +494,7 @@ public class CallDao {
}
}
public CallResponse updateCallStep1(Long callId, UpdateCallRequestStep1 updateCallRequest, Long userId) {
CallEntity callEntity = validateCall(callId);
public CallResponse updateCallStep1(CallEntity callEntity, UpdateCallRequestStep1 updateCallRequest, UserEntity userEntity) {
if(Boolean.TRUE.equals(callEntity.getStatus().equals(CallStatusEnum.PUBLISH.getValue()))) {
try {
Utils.retainOnlySpecificFields(updateCallRequest, Collections.singletonList("faq"));
@@ -508,7 +502,6 @@ public class CallDao {
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.FAILED_RETAIN_FIELD));
}
}
UserEntity userEntity = userService.validateUser(userId);
isValidDateRange(updateCallRequest, callEntity);
setIfUpdated(callEntity::getName, callEntity::setName, updateCallRequest.getName());
setIfUpdated(callEntity::getDescriptionShort, callEntity::setDescriptionShort,
@@ -667,7 +660,7 @@ public class CallDao {
validateUpdate(callEntity);
CallResponse callResponseBean = getCallResponseBean(callEntity);
FlowResponseBean flowResponseBean = flowDao.getFlowByCallId(callEntity.getId());
List<FormResponseBean> formResponseBean = formDao.getFormsByCallId(callEntity.getId());
List<FormResponseBean> formResponseBean = formDao.getFormsByCallId(callEntity);
CallValidatorServiceImpl.validateResponse(callResponseBean,flowResponseBean,formResponseBean);
callEntity.setStatus(CallStatusEnum.READY_TO_PUBLISH.getValue());
callRepository.save(callEntity);
@@ -683,8 +676,7 @@ public class CallDao {
return callEntity;
}
public CallResponse updateCallStatus(Long callId, CallStatusEnum statusReq) {
CallEntity callEntity = validateCall(callId);
public CallResponse updateCallStatus(CallEntity callEntity, CallStatusEnum statusReq) {
CallStatusEnum currentStatus = CallStatusEnum.valueOf(callEntity.getStatus());
validateStatusChange(currentStatus, statusReq);
callEntity.setStatus(statusReq.getValue());

View File

@@ -32,23 +32,23 @@ public class DashboardDao {
@Autowired
private CompanyRepository companyRepository;
public SuperAdminWidgetResponseBean getDashboardWidget() {
public SuperAdminWidgetResponseBean getDashboardWidget(UserEntity requestedUserEntity) {
SuperAdminWidgetResponseBean widgetResponseBean = new SuperAdminWidgetResponseBean();
widgetResponseBean.setWidget1(createWidget1());
widgetResponseBean.setWidget1(createWidget1(requestedUserEntity));
// List<Object[]> widgetBars = callRepository.findApplicationsPerCall();
// widgetResponseBean.setWidgetBars(widgetBars);
return widgetResponseBean;
}
private Widget1 createWidget1() {
private Widget1 createWidget1(UserEntity requestedUserEntity) {
Widget1 widget1 = initializeWidget1();
setActiveCalls(widget1);
setRegisteredUsers(widget1);
setTotalActiveFinancing(widget1);
setSubmittedApplications(widget1);
setDraftApplications(widget1);
setNumberOfCompanies(widget1);
setActiveCalls(widget1, requestedUserEntity);
setRegisteredUsers(widget1, requestedUserEntity);
setTotalActiveFinancing(widget1, requestedUserEntity);
setSubmittedApplications(widget1, requestedUserEntity);
setDraftApplications(widget1, requestedUserEntity);
setNumberOfCompanies(widget1, requestedUserEntity);
return widget1;
}
@@ -59,41 +59,41 @@ public class DashboardDao {
.build();
}
private void setActiveCalls(Widget1 widget1) {
private void setActiveCalls(Widget1 widget1, UserEntity requestedUserEntity) {
Long activeCalls = callRepository.countByStatus(CallStatusEnum.PUBLISH.getValue());
if (activeCalls != null) {
widget1.setNumberOfActiveCalls(activeCalls);
}
}
private void setRegisteredUsers(Widget1 widget1) {
Long activeUsers = userRepository.countByStatusAndRoleEntity_RoleType(UserStatusEnum.ACTIVE.getValue(),
RoleStatusEnum.ROLE_BENEFICIARY.getValue());
private void setRegisteredUsers(Widget1 widget1, UserEntity requestedUserEntity) {
Long activeUsers = userRepository.countByStatusAndRoleEntityRoleTypeAndHubId(UserStatusEnum.ACTIVE.getValue(),
RoleStatusEnum.ROLE_BENEFICIARY.getValue(), requestedUserEntity.getHub().getId());
if (activeUsers != null) {
widget1.setNumberOfResgisteredUsers(activeUsers);
}
}
private void setTotalActiveFinancing(Widget1 widget1) {
private void setTotalActiveFinancing(Widget1 widget1, UserEntity requestedUserEntity) {
BigDecimal totalActiveFinancing = callRepository.findTotalAmountOfPublishedCalls();
widget1.setTotalActiveFinancing(totalActiveFinancing);
}
private void setSubmittedApplications(Widget1 widget1) {
private void setSubmittedApplications(Widget1 widget1, UserEntity requestedUserEntity) {
Long submittedApplications = applicationRepository.countSubmittedApplications();
if (submittedApplications != null) {
widget1.setNumberOfSubmittedApplications(submittedApplications);
}
}
private void setDraftApplications(Widget1 widget1) {
private void setDraftApplications(Widget1 widget1, UserEntity requestedUserEntity) {
Long draftApplications = applicationRepository.countDraftApplications();
if (draftApplications != null) {
widget1.setNumberOfDraftApplications(draftApplications);
}
}
private void setNumberOfCompanies(Widget1 widget1) {
private void setNumberOfCompanies(Widget1 widget1, UserEntity requestedUserEntity) {
Long numberOfCompanies = companyRepository.countTotalCompanies();
if (numberOfCompanies != null) {
widget1.setNumberOfCompany(numberOfCompanies);

View File

@@ -7,18 +7,17 @@ import net.gepafin.tendermanagement.model.request.*;
import net.gepafin.tendermanagement.model.response.ContentResponseBean;
import net.gepafin.tendermanagement.model.response.FormResponseBean;
import net.gepafin.tendermanagement.repositories.*;
import net.gepafin.tendermanagement.service.CallService;
import net.gepafin.tendermanagement.service.EvaluationCriteriaService;
import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.util.FieldValidator;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.text.MessageFormat;
import java.time.LocalDateTime;
@@ -36,9 +35,6 @@ public class FormDao {
@Autowired
private FormRepository formRepository;
@Autowired
private CallService callService;
@Autowired
private ApplicationFormRepository applicationFormRepository;
@@ -57,6 +53,9 @@ public class FormDao {
@Autowired
private CallRepository callRepository;
@Autowired
private Validator validator;
@Autowired
private CriteriaFormFieldRepository criteriaFormFieldRepository;
@@ -68,9 +67,8 @@ public class FormDao {
return formEntity;
}
public FormEntity convertFormRequestToFormEntity(Long callId,FormRequest formRequest) {
public FormEntity convertFormRequestToFormEntity(CallEntity callEntity, FormRequest formRequest){
FormEntity formEntity=new FormEntity();
CallEntity callEntity=callService.getCallEntityById(callId);
formEntity.setCall(callEntity);
formEntity.setLabel(formRequest.getLabel());
formEntity.setContent(setContentResponseBean(formRequest.getContent()));
@@ -99,11 +97,10 @@ public class FormDao {
return contentList;
}
public FormResponseBean createForm(Long callId,FormRequest formRequest){
public FormResponseBean createForm(CallEntity callEntity,FormRequest formRequest){
validateForm(formRequest);
CallEntity callEntity=callService.validateCall(callId);
List<FlowDataEntity> flowDataEntities=flowDataRepository.findByCallId(callId);
List<FlowEdgesEntity> flowEdgesEntities=flowEdgesRepository.findByCallId(callId);
List<FlowDataEntity> flowDataEntities=flowDataRepository.findByCallId(callEntity.getId());
List<FlowEdgesEntity> flowEdgesEntities=flowEdgesRepository.findByCallId(callEntity.getId());
if(Boolean.FALSE.equals(flowDataEntities.isEmpty() || flowDataEntities==null ) || Boolean.FALSE.equals(flowEdgesEntities.isEmpty() || flowEdgesEntities==null) ){
flowDataRepository.deleteAll(flowDataEntities);
flowEdgesRepository.deleteAll(flowEdgesEntities);
@@ -111,7 +108,7 @@ public class FormDao {
callEntity.setFinalForm(null);
callRepository.save(callEntity);
}
FormEntity formEntity=convertFormRequestToFormEntity(callId,formRequest);
FormEntity formEntity=convertFormRequestToFormEntity(callEntity, formRequest);
validateAndSaveCriteriaFormField(callEntity, formEntity, formRequest.getContent());
return convertFormEntityToFormResponseBean(formEntity);
}
@@ -170,87 +167,76 @@ public class FormDao {
if(formRequest.getContent()==null || formRequest.getLabel()==null ){
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.REQUIRED_PARAMETER_NOT_FOUND_FOR_FORM));
}
}
public FormResponseBean updateForm(Long formId, FormRequest formRequest, Boolean forceDeleteFlow) {
ContentRequestBean contentRequestBean2 = null;
String choosenField = null;
FormEntity formEntity = validateForm(formId);
callDao.validateUpdate(formEntity.getCall());
List<ContentRequestBean> contentRequestBean = Utils.convertJsonStringToList(formEntity.getContent(),
ContentRequestBean.class);
for (ContentRequestBean contentRequestBean1 : contentRequestBean) {
FlowDataEntity flowDataEntity = flowDataRepository.findByFormIdAndChoosenField(formEntity.getId(),
contentRequestBean1.getId());
if (flowDataEntity != null) {
choosenField = flowDataEntity.getChoosenField();
if (Boolean.TRUE.equals(contentRequestBean1.getId().equals(choosenField))) {
contentRequestBean2 = contentRequestBean1;
break;
}
}
}
if (contentRequestBean2 != null) {
List<SettingRequestBean> settingRequestBeansDB = contentRequestBean2.getSettings();
for (ContentRequestBean contentRequestBeanRequest : formRequest.getContent()) {
if (contentRequestBeanRequest.getId().equals(contentRequestBean2.getId())) {
for (SettingRequestBean settingRequestBeanRequest : contentRequestBeanRequest
.getSettings()) {
for (SettingRequestBean settingRequestBeanDB : settingRequestBeansDB) {
if (settingRequestBeanRequest.getName().equals(settingRequestBeanDB.getName())) {
if (!settingRequestBeanRequest.getValue()
.equals(settingRequestBeanDB.getValue())) {
if (Boolean.TRUE.equals(forceDeleteFlow)) {
Utils.setIfUpdated(formEntity::getLabel, formEntity::setLabel,
formRequest.getLabel());
Utils.setIfUpdated(formEntity::getContent, formEntity::setContent,
setContentResponseBean(formRequest.getContent()));
formEntity.setUpdatedDate(
DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
formEntity = saveFormEntity(formEntity);
List<FlowDataEntity> flowDataEntities = flowDataRepository
.findByCallId(formEntity.getCall().getId());
List<FlowEdgesEntity> flowEdgesEntities = flowEdgesRepository
.findByCallId(formEntity.getCall().getId());
flowDataRepository.deleteAll(flowDataEntities);
flowEdgesRepository.deleteAll(flowEdgesEntities);
CallEntity callEntity = formEntity.getCall();
callEntity.setInitialForm(null);
callEntity.setFinalForm(null);
callRepository.save(callEntity);
return convertFormEntityToFormResponseBean(formEntity);
} else {
throw new CustomValidationException(Status.BAD_REQUEST,
Translator.toLocale(
GepafinConstant.UPDATING_FORM_VALUE_IMPACT_ON_FLOW,
choosenField));
}
} else {
Utils.setIfUpdated(formEntity::getLabel, formEntity::setLabel,
formRequest.getLabel());
Utils.setIfUpdated(formEntity::getContent, formEntity::setContent,
setContentResponseBean(formRequest.getContent()));
formEntity
.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
formEntity = saveFormEntity(formEntity);
return convertFormEntityToFormResponseBean(formEntity);
}
}
}
}
}
}
} else {
Utils.setIfUpdated(formEntity::getLabel, formEntity::setLabel, formRequest.getLabel());
Utils.setIfUpdated(formEntity::getContent, formEntity::setContent,
setContentResponseBean(formRequest.getContent()));
formEntity.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
formEntity = saveFormEntity(formEntity);
validateAndSaveCriteriaFormField(formEntity.getCall(), formEntity, formRequest.getContent());
return convertFormEntityToFormResponseBean(formEntity);
}
return convertFormEntityToFormResponseBean(formEntity);
}
}
public FormResponseBean updateForm(UserEntity user, Long formId, FormRequest formRequest,Boolean forceDeleteFlow){
ContentRequestBean contentRequestBean2=null;
String choosenField=null;
FormEntity formEntity = validateForm(formId);
validator.validateUserWithCall(user, formEntity.getCall().getId());
callDao.validateUpdate(formEntity.getCall());
List<ContentRequestBean> contentRequestBean = Utils.convertJsonStringToList(formEntity.getContent(), ContentRequestBean.class);
for (ContentRequestBean contentRequestBean1 : contentRequestBean) {
FlowDataEntity flowDataEntity = flowDataRepository.findByFormIdAndChoosenField(formEntity.getId(), contentRequestBean1.getId());
if (flowDataEntity != null) {
choosenField = flowDataEntity.getChoosenField();
if (Boolean.TRUE.equals(contentRequestBean1.getId().equals(choosenField))) {
contentRequestBean2 = contentRequestBean1;
break;
}
}
}
if (contentRequestBean2 != null) {
List<SettingRequestBean> settingRequestBeansDB = contentRequestBean2.getSettings();
for (ContentRequestBean contentRequestBeanRequest : formRequest.getContent()) {
if (contentRequestBeanRequest.getId().equals(contentRequestBean2.getId())) {
for (SettingRequestBean settingRequestBeanRequest : contentRequestBeanRequest.getSettings()) {
for (SettingRequestBean settingRequestBeanDB : settingRequestBeansDB) {
if (settingRequestBeanRequest.getName().equals(settingRequestBeanDB.getName())) {
if (!settingRequestBeanRequest.getValue().equals(settingRequestBeanDB.getValue())) {
if (Boolean.TRUE.equals(forceDeleteFlow)) {
Utils.setIfUpdated(formEntity::getLabel, formEntity::setLabel, formRequest.getLabel());
Utils.setIfUpdated(formEntity::getContent, formEntity::setContent, setContentResponseBean(formRequest.getContent()));
formEntity.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
formEntity = saveFormEntity(formEntity);
List<FlowDataEntity> flowDataEntities = flowDataRepository.findByCallId(formEntity.getCall().getId());
List<FlowEdgesEntity> flowEdgesEntities = flowEdgesRepository.findByCallId(formEntity.getCall().getId());
flowDataRepository.deleteAll(flowDataEntities);
flowEdgesRepository.deleteAll(flowEdgesEntities);
CallEntity callEntity = formEntity.getCall();
callEntity.setInitialForm(null);
callEntity.setFinalForm(null);
callRepository.save(callEntity);
return convertFormEntityToFormResponseBean(formEntity);
} else {
throw new CustomValidationException(
Status.BAD_REQUEST,
Translator.toLocale(GepafinConstant.UPDATING_FORM_VALUE_IMPACT_ON_FLOW, choosenField)
);
}
}
else {
Utils.setIfUpdated(formEntity::getLabel, formEntity::setLabel, formRequest.getLabel());
Utils.setIfUpdated(formEntity::getContent, formEntity::setContent, setContentResponseBean(formRequest.getContent()));
formEntity.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
formEntity = saveFormEntity(formEntity);
return convertFormEntityToFormResponseBean(formEntity);
}
}
}
}
}
}
}
else {
Utils.setIfUpdated(formEntity::getLabel, formEntity::setLabel, formRequest.getLabel());
Utils.setIfUpdated(formEntity::getContent, formEntity::setContent, setContentResponseBean(formRequest.getContent()));
formEntity.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
formEntity = saveFormEntity(formEntity);
validateAndSaveCriteriaFormField(formEntity.getCall(), formEntity, formRequest.getContent());
return convertFormEntityToFormResponseBean(formEntity);
}
return convertFormEntityToFormResponseBean(formEntity);
}
public FormEntity validateForm(Long formId) {
FormEntity formEntity = formRepository.findById(formId)
@@ -258,12 +244,14 @@ public class FormDao {
return formEntity;
}
public FormResponseBean getFormEntityById(Long formId) {
public FormResponseBean getFormEntityById(UserEntity user, Long formId) {
FormEntity formEntity = validateForm(formId);
validator.validateUserWithCall(user, formEntity.getCall().getId());
return convertFormEntityToFormResponseBean(formEntity);
}
public void deleteFormById(Long formId){
public void deleteFormById(UserEntity user, Long formId){
FormEntity formEntity = validateForm(formId);
validator.validateUserWithCall(user, formEntity.getCall().getId());
List<FlowDataEntity> flowDataEntities=flowDataRepository.findByCallId(formEntity.getCall().getId());
List<FlowEdgesEntity> flowEdgesEntities=flowEdgesRepository.findByCallId(formEntity.getCall().getId());
flowDataRepository.deleteAll(flowDataEntities);
@@ -274,13 +262,12 @@ public class FormDao {
callRepository.save(callEntity);
formRepository.delete(formEntity);
}
public List<FormResponseBean> getFormsByCallId(Long callId){
CallEntity callEntity=callService.validateCall(callId);
public List<FormResponseBean> getFormsByCallId(CallEntity callEntity){
if(callEntity== null){
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.CALL_NOT_FOUND));
}
List<FormEntity> formEntities=formRepository.findByCallId(callId);
List<FormEntity> formEntities=formRepository.findByCallId(callEntity.getId());
List<FormResponseBean> formResponseBeanList = formEntities.stream()
.map(req -> convertFormEntityToFormResponseBean(req))
.collect(Collectors.toList());
@@ -385,12 +372,13 @@ public class FormDao {
String error=null;
if (value!=null && value.matches("^\\d{1,11}$")) {
Map<String, Object> customData=null;
// Map<String, Object> customData=null;
try {
Map<String, Object> vatCheckResponse = vatCheckDao.checkVatNumberApi(value);
if (Boolean.FALSE.equals(CollectionUtils.isEmpty(vatCheckResponse))) {
customData = vatCheckResponse;
}
// Map<String, Object> vatCheckResponse = vatCheckDao.checkVatNumberApi(value);
vatCheckDao.checkVatNumberApi(value);
// if (Boolean.FALSE.equals(CollectionUtils.isEmpty(vatCheckResponse))) {
// customData = vatCheckResponse;
// }
} catch (Exception e) {
error=(MessageFormat.format(Translator.toLocale(GepafinConstant.VALIDATION_VALID_PIVA), fieldId));
}

View File

@@ -0,0 +1,100 @@
package net.gepafin.tendermanagement.dao;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.HubEntity;
import net.gepafin.tendermanagement.model.request.HubReq;
import net.gepafin.tendermanagement.model.response.HubResponseBean;
import net.gepafin.tendermanagement.model.util.NanoIdUtils;
import net.gepafin.tendermanagement.repositories.HubRepository;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List;
@Component
public class HubDao {
@Autowired
private HubRepository hubRepository;
public HubResponseBean createHub(HubReq hubReq) {
HubEntity hubEntity = createOrUpdateHubEntity(new HubEntity(), hubReq);
hubRepository.save(hubEntity);
return convertToHubResponseBean(hubEntity);
}
public HubResponseBean updateHub(Long hubId, HubReq hubReq) {
HubEntity hubEntity = validateHub(hubId);
createOrUpdateHubEntity(hubEntity, hubReq);
return convertToHubResponseBean(hubEntity);
}
public HubResponseBean getHubById(Long hubId) {
return convertToHubResponseBean(validateHub(hubId));
}
public List<HubResponseBean> getAllHubs() {
List<HubEntity> hubs = hubRepository.findAll();
return hubs.stream().map(this::convertToHubResponseBean).toList();
}
public void deleteHub(Long hubId) {
HubEntity hubEntity = validateHub(hubId);
hubRepository.deleteById(hubId);
hubRepository.save(hubEntity);
}
private HubEntity validateHub(Long hubId) {
return hubRepository.findById(hubId)
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.HUB_NOT_FOUND)));
}
private HubEntity createOrUpdateHubEntity(HubEntity hubEntity, HubReq hubReq) {
hubEntity.setCompanyName(hubReq.getCompanyName());
hubEntity.setFirstName(hubReq.getFirstName());
hubEntity.setLastName(hubReq.getLastName());
hubEntity.setEmail(hubReq.getEmail());
hubEntity.setCity(hubReq.getCity());
hubEntity.setCountry(hubReq.getCountry());
hubEntity.setVatNumber(hubReq.getVatNumber());
hubEntity.setUniqueUuid(NanoIdUtils.randomNanoId());
hubEntity.setDomainName(hubReq.getDomainName());
hubEntity.setAppConfig(hubReq.getAppConfig() != null ? hubReq.getAppConfig().toString() : null);
hubEntity.setCreatedDate(hubEntity.getCreatedDate() == null ? LocalDateTime.now() : hubEntity.getCreatedDate());
hubEntity.setUpdatedDate(LocalDateTime.now());
return hubEntity;
}
private HubResponseBean convertToHubResponseBean(HubEntity hubEntity) {
HubResponseBean responseBean = new HubResponseBean();
responseBean.setId(hubEntity.getId());
responseBean.setCompanyName(hubEntity.getCompanyName());
responseBean.setFirstName(hubEntity.getFirstName());
responseBean.setLastName(hubEntity.getLastName());
responseBean.setEmail(hubEntity.getEmail());
responseBean.setCity(hubEntity.getCity());
responseBean.setCountry(hubEntity.getCountry());
responseBean.setVatNumber(hubEntity.getVatNumber());
responseBean.setUniqueUuid(hubEntity.getUniqueUuid());
responseBean.setDomainName(hubEntity.getDomainName());
responseBean.setAppConfig(hubEntity.getAppConfig());
responseBean.setCreatedDate(hubEntity.getCreatedDate());
responseBean.setUpdatedDate(hubEntity.getUpdatedDate());
return responseBean;
}
public HubEntity getHubByUuid(String hubUuid) {
return hubRepository.findByUniqueUuid(hubUuid).orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.HUB_NOT_FOUND)));
}
public HubResponseBean getHubByHubUuid(String uuid) {
return convertToHubResponseBean(getHubByUuid(uuid));
}
}

View File

@@ -2,12 +2,6 @@ package net.gepafin.tendermanagement.dao;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.properties.UnitValue;
import com.itextpdf.layout.renderer.CellRenderer;
import com.itextpdf.layout.renderer.DrawContext;
import com.itextpdf.text.*;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
@@ -16,28 +10,17 @@ import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.*;
import net.gepafin.tendermanagement.model.request.CustomPageEvent;
import net.gepafin.tendermanagement.model.request.FieldLabelValuePairRequest;
import net.gepafin.tendermanagement.model.response.*;
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
import net.gepafin.tendermanagement.service.CallService;
import net.gepafin.tendermanagement.util.Validator;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.element.Cell;
//import com.itextpdf.layout.element.
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
@@ -128,7 +111,7 @@ public class PdfDao {
// addLabelValuePair(document, "Con il titolo di", "Rappresentante legale", regularFont);
document.add(new Paragraph(" "));
ApplicationGetResponseBean applicationGetResponseBean=applicationDao.getApplicationByFormId(applicationId,null, userEntity);
ApplicationGetResponseBean applicationGetResponseBean=applicationDao.getApplicationByFormId(request, applicationId, null);
for(FormApplicationResponse formApplicationResponse: applicationGetResponseBean.getForm()) {
document.add(new Paragraph(formApplicationResponse.getLabel(),sectionFont));
document.add(new Paragraph(" ")); // Add line break

View File

@@ -2,6 +2,7 @@ package net.gepafin.tendermanagement.dao;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.config.SamlSuccessHandler;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.BeneficiaryEntity;
@@ -17,10 +18,10 @@ import net.gepafin.tendermanagement.model.response.UserResponseBean;
import net.gepafin.tendermanagement.model.util.JWTToken;
import net.gepafin.tendermanagement.repositories.BeneficiaryRepository;
import net.gepafin.tendermanagement.repositories.UserRepository;
import net.gepafin.tendermanagement.service.CompanyService;
import net.gepafin.tendermanagement.service.RoleService;
import net.gepafin.tendermanagement.service.impl.AuthenticationService;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
@@ -29,11 +30,12 @@ import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
@@ -45,8 +47,10 @@ public class UserDao {
@Autowired
private UserRepository userRepository;
@Autowired
private CompanyDao companyDao;
@Autowired
private AuthenticationService authService;
@@ -58,13 +62,25 @@ public class UserDao {
@Autowired
private BeneficiaryRepository beneficiaryRepository;
@Autowired
private RoleService roleService;
@Value("${default.hub.uuid}")
private String defaultHubUuid;
@Autowired
private Validator validator;
@Autowired
private SamlSuccessHandler samlSuccessHandler;
public JWTToken createUser(HttpServletRequest request, String tempToken, UserReq userReq) {
validateUserRequest(tempToken, userReq);
if(StringUtils.isEmpty(userReq.getHubUuid())) {
userReq.setHubUuid(defaultHubUuid);
}
validateUserRequest(request, tempToken, userReq);
validatePassword(userReq.getPassword(), userReq.getConfPassword(), tempToken);
RoleEntity roleEntity = getRoleEntity(userReq.getRoleId());
@@ -99,14 +115,21 @@ public class UserDao {
return beneficiaryEntity;
}
private void validateUserRequest(String tempToken, UserReq userReq) {
private void validateUserRequest(HttpServletRequest request, String tempToken, UserReq userReq) {
if (tempToken == null) {
validator.validateRequest(request,RoleStatusEnum.ROLE_SUPER_ADMIN);
}else {
samlSuccessHandler.validateToken(tempToken, userReq.getCodiceFiscale(), userReq.getHubUuid());
}
RoleEntity role = roleService.validateRole(userReq.getRoleId());
if (Boolean.FALSE.equals(Utils.isValidEmail(userReq.getEmail()))) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VALIDATE_EMAIL));
}
log.info("Creating user with email: {}", userReq.getEmail());
if (userRepository.existsByEmailIgnoreCase(userReq.getEmail())) {
if (userRepository.existsByEmailIgnoreCaseAndHubUniqueUuid(userReq.getEmail(), userReq.getHubUuid())) {
log.error("User creation failed: Email {} already exists", userReq.getEmail());
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.EMAIL_ALREADY_EXISTS));
@@ -269,6 +292,9 @@ public class UserDao {
public JWTToken login(LoginReq loginReq,HttpServletRequest request) {
log.info("User login attempt for email: {}", loginReq.getEmail());
if(StringUtils.isEmpty(loginReq.getHubUuid())) {
loginReq.setHubUuid(defaultHubUuid);
}
JWTToken jwtToken = authService.login(loginReq,request);
log.info("Login successful for email: {}", loginReq.getEmail());
return jwtToken;
@@ -289,11 +315,11 @@ public class UserDao {
}
public String initiatePasswordReset(InitiatePasswordResetReq resetReq) {
UserEntity user = userRepository.findByEmail(resetReq.getEmail());
if (user == null) {
log.info("Password reset attempt for non-existent user: {}", resetReq.getEmail());
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG));
}
UserEntity user = userRepository
.findByEmailIgnoreCaseAndHubUniqueUuid(resetReq.getEmail(), resetReq.getHubUuid())
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
String token = Utils.generateSecureToken();
user.setResetPasswordToken(token);
userRepository.save(user);
@@ -302,11 +328,11 @@ public class UserDao {
}
public Boolean resetPassword(ResetPasswordReq resetPasswordReq) {
UserEntity user = userRepository.findByEmail(resetPasswordReq.getEmail());
if (user == null) {
log.info("Password reset attempt for non-existent user: {}", resetPasswordReq.getEmail());
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG));
}
UserEntity user = userRepository
.findByEmailIgnoreCaseAndHubUniqueUuid(resetPasswordReq.getEmail(), resetPasswordReq.getHubUuid())
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
if (!resetPasswordReq.getNewPassword().equals(resetPasswordReq.getConfirmPassword())) {
log.info("User creation failed: Passwords do not match for email {}", user.getEmail());
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.PASSWORD_DOESNT_MATCH));
@@ -325,12 +351,12 @@ public class UserDao {
return true;
}
public Boolean changePassword(ChangePasswordRequest request) {
UserEntity user = userRepository.findByEmail(request.getEmail());
if (user == null) {
log.info("Password reset attempt for non-existent user: {}", request.getEmail());
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG));
}
public Boolean changePassword(UserEntity userEntity, ChangePasswordRequest request) {
UserEntity user = userRepository
.findByEmailIgnoreCaseAndHubUniqueUuid(request.getEmail(), userEntity.getHub().getUniqueUuid())
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.CURRENT_PASSWORD_INCORRECT));
}
@@ -355,6 +381,16 @@ public class UserDao {
log.info("User status updated to {} for user ID: {}", statusReq, userId);
return convertUserEntityToUserResponse(userEntity);
}
public List<UserResponseBean> getUserByHubId(String hubId) {
// log.info("Fetching users for hub ID: {}", hubId);
// List<UserHubEntity> userHubMappings = userHubRepository.findByHubId(hubId);
List<UserResponseBean> userResponseBeans = new ArrayList<>();
// for (UserHubEntity mapping : userHubMappings) {
// UserEntity userEntity = validateUser(mapping.getUserId());
// userResponseBeans.add(convertUserEntityToUserResponse(userEntity));
// }
return userResponseBeans;
}
public JWTToken validateExistingUserToken(String token) {
return authService.validateExistingUserToken(token);
@@ -364,15 +400,15 @@ public class UserDao {
return authService.validateNewUserToken(token);
}
public List<UserResponseBean> getAllUsers(Long roleId) {
public List<UserResponseBean> getAllUsers(UserEntity user, Long roleId) {
List<UserEntity> users;
if (roleId != null) {
log.info("Fetching users by role ID: {}", roleId);
RoleEntity roleEntity=roleService.validateRole(roleId);
users = userRepository.findByRoleEntityId(roleEntity.getId());
users = userRepository.findByRoleEntityIdAndHubId(roleEntity.getId(), user.getHub().getId());
} else {
log.info("Fetching all users");
users = userRepository.findAll();
users = userRepository.findByHubId(user.getHub().getId());
}
List<UserResponseBean> userResponseBeans = users.stream()
.map(this::convertUserEntityToUserResponse)

View File

@@ -84,5 +84,9 @@ public class CallEntity extends BaseEntity {
@Column(name = "END_TIME")
private LocalTime endTime;
@ManyToOne
@JoinColumn(name = "HUB_ID")
private HubEntity hub;
}

View File

@@ -0,0 +1,45 @@
package net.gepafin.tendermanagement.entities;
import jakarta.persistence.*;
import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;
@Entity
@Table(name="hub")
@Setter
@Getter
public class HubEntity extends BaseEntity{
@Column(name = "COMPANY_NAME")
private String companyName;
@Column(name = "FIRST_NAME")
private String firstName;
@Column(name = "LAST_NAME")
private String lastName;
@Column(name = "EMAIL")
private String email;
@Column(name = "CITY")
private String city;
@Column(name = "COUNTRY")
private String country;
@Size(min=5,max=15)
@Column(name = "VAT_NUMBER")
private String vatNumber;
@Column(name = "DOMAIN_NAME")
private String domainName;
@Column(name = "APP_CONFIG")
private String appConfig;
@Column(name = "UNIQUE_UUID")
private String uniqueUuid;
}

View File

@@ -0,0 +1,22 @@
package net.gepafin.tendermanagement.entities;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
@Entity
@Table(name = "hub_user")
@Getter
@Setter
public class HubUserEntity extends BaseEntity{
@ManyToOne
@JoinColumn(name = "hub_id", nullable = false)
private HubEntity hub;
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
private UserEntity user;
}

View File

@@ -25,4 +25,7 @@ public class ProtocolEntity extends BaseEntity {
@Column(name="APPLICATION_ID")
private Long applicationId;
@Column(name="HUB_ID")
private Long hubId;
}

View File

@@ -13,6 +13,21 @@ public class SamlResponseEntity extends BaseEntity{
@Column(name = "AUTHENTICATION_OBJECT")
private String authenticationObject;
@Column(name = "IN_RESPONSE_TO")
private String inResponseTo;
@Column(name = "ISSUE_INSTANT")
private String issueInstant;
@Column(name = "SAML_ID")
private String samlId;
@Column(name = "HUB_UUID")
private String hubUuid;
@Column(name = "STATUS")
private String status;
@Column(name = "TOKEN")
private String token;

View File

@@ -65,4 +65,8 @@ public class UserEntity extends BaseEntity {
@OneToOne
@JoinColumn(name = "BENEFICIARY_ID")
private BeneficiaryEntity beneficiary;
@ManyToOne
@JoinColumn(name = "HUB_ID")
private HubEntity hub;
}

View File

@@ -0,0 +1,21 @@
package net.gepafin.tendermanagement.enums;
import com.fasterxml.jackson.annotation.JsonValue;
public enum SamlResponseStatusEnum {
SUCCESS("SUCCESS"),
FAILED("FAILED"),
INITIATED("INITIATED");
private String value;
SamlResponseStatusEnum(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
}

View File

@@ -0,0 +1,38 @@
package net.gepafin.tendermanagement.model.request;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import java.util.Map;
@Getter
@Setter
public class HubReq {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
private String companyName;
private String firstName;
private String lastName;
private String email;
private String city;
private String country;
private String vatNumber;
private String domainName;
private Map<String, Object> appConfig;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private String uniqueUuid;
}

View File

@@ -5,4 +5,5 @@ import lombok.Data;
@Data
public class InitiatePasswordResetReq {
private String email;
private String hubUuid;
}

View File

@@ -14,5 +14,6 @@ public class LoginReq {
private String email;
@NotEmpty
private String password;
private String hubUuid;
private Boolean rememberMe;
}

View File

@@ -8,6 +8,6 @@ public class ResetPasswordReq {
private String token;
private String newPassword;
private String confirmPassword;
private String hubUuid;
}

View File

@@ -39,4 +39,8 @@ public class UserReq {
private Boolean thirdParty;
private String emailPec;
private String hubUuid;
}

View File

@@ -0,0 +1,34 @@
package net.gepafin.tendermanagement.model.response;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import net.gepafin.tendermanagement.model.BaseBean;
import java.util.Map;
@Getter
@Setter
public class HubResponseBean extends BaseBean {
private String companyName;
private String firstName;
private String lastName;
private String email;
private String city;
private String country;
private String vatNumber;
private String appConfig;
private String domainName;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private String uniqueUuid;
}

View File

@@ -0,0 +1,129 @@
/**
* Copyright (c) 2017 The JNanoID Authors
* Copyright (c) 2017 Aventrix LLC
* Copyright (c) 2017 Andrey Sitnik
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package net.gepafin.tendermanagement.model.util;
import java.security.SecureRandom;
import java.util.Random;
public final class NanoIdUtils {
/**
* <code>NanoIdUtils</code> instances should NOT be constructed in standard programming.
* Instead, the class should be used as <code>NanoIdUtils.randomNanoId();</code>.
*/
private NanoIdUtils() {
//Do Nothing
}
/**
* The default random number generator used by this class.
* Creates cryptographically strong NanoId Strings.
*/
public static final SecureRandom DEFAULT_NUMBER_GENERATOR = new SecureRandom();
/**
* The default alphabet used by this class.
* Creates url-friendly NanoId Strings using 64 unique symbols.
*/
public static final char[] DEFAULT_ALPHABET =
"_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
/**
* The default size used by this class.
* Creates NanoId Strings with slightly more unique values than UUID v4.
*/
public static final int DEFAULT_SIZE = 21;
/**
* Static factory to retrieve a url-friendly, pseudo randomly generated, NanoId String.
*
* The generated NanoId String will have 21 symbols.
*
* The NanoId String is generated using a cryptographically strong pseudo random number
* generator.
*
* @return A randomly generated NanoId String.
*/
public static String randomNanoId() {
return randomNanoId(DEFAULT_NUMBER_GENERATOR, DEFAULT_ALPHABET, DEFAULT_SIZE);
}
/**
* Static factory to retrieve a NanoId String.
*
* The string is generated using the given random number generator.
*
* @param random The random number generator.
* @param alphabet The symbols used in the NanoId String.
* @param size The number of symbols in the NanoId String.
* @return A randomly generated NanoId String.
*/
public static String randomNanoId(final Random random, final char[] alphabet, final int size) {
if (random == null) {
throw new IllegalArgumentException("random cannot be null.");
}
if (alphabet == null) {
throw new IllegalArgumentException("alphabet cannot be null.");
}
if (alphabet.length == 0 || alphabet.length >= 256) {
throw new IllegalArgumentException("alphabet must contain between 1 and 255 symbols.");
}
if (size <= 0) {
throw new IllegalArgumentException("size must be greater than zero.");
}
double value = (double) (alphabet.length - 1);
final int mask = (2 << (int) Math.floor(Math.log(value) / Math.log(2))) - 1;
final int step = (int) Math.ceil(1.6 * mask * size / alphabet.length);
final StringBuilder idBuilder = new StringBuilder();
while (true) {
final byte[] bytes = new byte[step];
random.nextBytes(bytes);
for (int i = 0; i < step; i++) {
final int alphabetIndex = bytes[i] & mask;
if (alphabetIndex < alphabet.length) {
idBuilder.append(alphabet[alphabetIndex]);
if (idBuilder.length() == size) {
return idBuilder.toString();
}
}
}
}
}
}

View File

@@ -0,0 +1,15 @@
package net.gepafin.tendermanagement.repositories;
import net.gepafin.tendermanagement.entities.HubEntity;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface HubRepository extends JpaRepository<HubEntity, Long> {
Optional<HubEntity> findByUniqueUuid(String hubUuid);
}

View File

@@ -3,11 +3,12 @@ package net.gepafin.tendermanagement.repositories;
import net.gepafin.tendermanagement.entities.ProtocolEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface ProtocolRepository extends JpaRepository<ProtocolEntity,Long> {
@Query("SELECT MAX(p.protocolNumber) FROM ProtocolEntity p")
Integer findMaxProtocolNumber();
@Query("SELECT MAX(p.protocolNumber) FROM ProtocolEntity p where p.hubId = :hubId")
Long findMaxProtocolNumberAndHubId(@Param("hubId") Long hubId);
}

View File

@@ -1,5 +1,7 @@
package net.gepafin.tendermanagement.repositories;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@@ -10,4 +12,6 @@ public interface SamlResponseRepository extends JpaRepository<SamlResponseEntity
SamlResponseEntity findByToken(String token);
Optional<SamlResponseEntity> findByInResponseToAndStatus(String inResponseTo, String status);
}

View File

@@ -1,7 +1,6 @@
package net.gepafin.tendermanagement.repositories;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.model.response.UserResponseBean;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@@ -11,17 +10,27 @@ import java.util.Optional;
@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {
Optional<UserEntity> findByEmailIgnoreCase(String email);
// Optional<UserEntity> findByEmailIgnoreCase(String email);
boolean existsByEmailIgnoreCase(String email);
// boolean existsByEmailIgnoreCase(String email);
UserEntity findByEmail(String email);
// UserEntity findByEmail(String email);
Optional<UserEntity> findByBeneficiaryCodiceFiscale(String codiceFiscale);
boolean existsByBeneficiaryCodiceFiscale(String codiceFiscale);
UserEntity findByBeneficiaryId(Long beneficiaryId);
Long countByStatusAndRoleEntity_RoleType(String status, String roleName);
List<UserEntity> findByRoleEntityId(Long roleId);
Long countByStatusAndRoleEntityRoleType(String status, String roleName);
Optional<UserEntity> findByEmailIgnoreCaseAndHubUniqueUuid(String email, String hubId);
boolean existsByEmailIgnoreCaseAndHubUniqueUuid(String email, String hubUuid);
List<UserEntity> findByRoleEntityIdAndHubId(Long roleId, Long hubId);
List<UserEntity> findByHubId(Long hubId);
Long countByStatusAndRoleEntityRoleTypeAndHubId(String status, String roleName, Long hubId);
}

View File

@@ -19,13 +19,11 @@ public interface CallService {
CallResponse updateCallStep1(HttpServletRequest request, Long callId, UpdateCallRequestStep1 updateCallRequest);
CallResponse getCallById (Long callId);
CallResponse getCallById (HttpServletRequest request, Long callId);
List<CallDetailsResponseBean> getAllCalls(HttpServletRequest request);
CallResponse validateCallData(Long callId);
CallEntity getCallEntityById(Long id);
CallResponse validateCallData(HttpServletRequest request, Long callId);
CallResponse updateCallStatus(HttpServletRequest request, Long callId, CallStatusEnum statusReq);

View File

@@ -0,0 +1,18 @@
package net.gepafin.tendermanagement.service;
import net.gepafin.tendermanagement.entities.HubEntity;
import net.gepafin.tendermanagement.model.request.HubReq;
import net.gepafin.tendermanagement.model.response.HubResponseBean;
import java.util.List;
public interface HubService {
HubResponseBean createHub(HubReq hubReq);
HubResponseBean updateHub(Long hubId, HubReq hubReq);
HubResponseBean getHubById(Long hubId);
List<HubResponseBean> getAllHubs();
void deleteHub(Long hubId);
HubEntity getHubByUuid(String hubUuid);
HubResponseBean getHubByHubUuid(String uuid);
}

View File

@@ -31,7 +31,7 @@ public interface UserService {
Boolean resetPassword(ResetPasswordReq resetPasswordReq);
Boolean changePassword(ChangePasswordRequest request);
Boolean changePassword(HttpServletRequest httpServletRequest, ChangePasswordRequest request);
void logoutUser(HttpServletRequest request, HttpServletResponse response);
@@ -45,6 +45,6 @@ public interface UserService {
UserEntity getUserByBeneficiaryId(Long beneficiaryId);
public UserEntity getUserEntityById(Long userId);
List<UserResponseBean> getAllUsers(Long roleId);
List<UserResponseBean> getAllUsers(HttpServletRequest request, Long roleId);
}

View File

@@ -40,21 +40,19 @@ public class ApplicationServiceImpl implements ApplicationService {
@Transactional(rollbackFor = Exception.class)
public ApplicationResponseBean createApplication(HttpServletRequest request,
ApplicationRequestBean applicationRequestBean, Long applicationId, Long formId) {
UserEntity userEntity = validator.validateUser(request);
return applicationDao.createApplication(applicationRequestBean, userEntity, formId, applicationId);
return applicationDao.createApplication(request, applicationRequestBean, formId, applicationId);
}
@Override
@Transactional(readOnly = true)
public ApplicationGetResponseBean getApplicationByFormId(HttpServletRequest request, Long applicationId,Long formId) {
UserEntity userEntity = validator.validateUser(request);
return applicationDao.getApplicationByFormId(applicationId,formId,userEntity);
return applicationDao.getApplicationByFormId(request, applicationId,formId);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteApplication(HttpServletRequest request, Long applicationId) {
applicationDao.deleteById(applicationId);
applicationDao.deleteById(request, applicationId);
}
@Override
@@ -74,14 +72,14 @@ public class ApplicationServiceImpl implements ApplicationService {
public NextOrPreviousFormResponse getNextOrPreviousForm(HttpServletRequest request, Long applicationId, Long formId,
FormActionEnum action) {
ApplicationEntity applicationEntity = validateApplication(applicationId);
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
return flowFormDao.getNextOrPreviousForm(applicationEntity, formId, action);
}
@Override
@Transactional(rollbackFor = Exception.class)
public ApplicationResponse updateApplicationStatus(HttpServletRequest request, Long applicationId, ApplicationStatusTypeEnum status) {
UserEntity userEntity = validator.validateUser(request);
return applicationDao.updateApplicationStatus(userEntity, applicationId, status);
return applicationDao.updateApplicationStatus(request, applicationId, status);
}

View File

@@ -70,17 +70,18 @@ public class AuthenticationService {
this.authenticationManager = authenticationManager;
}
public JWTToken login(LoginReq loginReq,HttpServletRequest request) {
public JWTToken login(LoginReq loginReq, HttpServletRequest request) {
UserEntity user=null;
LoginAttemptEntity loginAttemptEntity = prepareLoginAttemptEntity(loginReq, request);
log.info("Attempting login for email: {}", loginReq.getEmail());
String emailWithHubId = loginReq.getEmail()+":"+loginReq.getHubUuid();
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
loginReq.getEmail(), loginReq.getPassword());
emailWithHubId, loginReq.getPassword());
Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
log.info("Authentication successful for email: {}", loginReq.getEmail());
user = userRepository.findByEmailIgnoreCase(loginReq.getEmail())
user = userRepository.findByEmailIgnoreCaseAndHubUniqueUuid(loginReq.getEmail(), loginReq.getHubUuid())
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
loginAttemptEntity.setUserId(user.getId());

View File

@@ -1,7 +1,6 @@
package net.gepafin.tendermanagement.service.impl;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.config.jwt.TokenProvider;
import net.gepafin.tendermanagement.dao.CallDao;
import net.gepafin.tendermanagement.entities.CallEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
@@ -12,12 +11,13 @@ import net.gepafin.tendermanagement.model.request.UpdateCallRequestStep1;
import net.gepafin.tendermanagement.model.response.CallDetailsResponseBean;
import net.gepafin.tendermanagement.model.response.CallResponse;
import net.gepafin.tendermanagement.service.CallService;
import net.gepafin.tendermanagement.util.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
@Service
@@ -27,59 +27,61 @@ public class CallServiceImpl implements CallService {
private CallDao callDao;
@Autowired
private TokenProvider tokenProvider;
private Validator validator;
@Override
@Transactional(rollbackFor = Exception.class)
public CallResponse createCallStep1(HttpServletRequest request, CreateCallRequestStep1 createCallRequest) {
Map<String, Object> userInfo= tokenProvider.getUserInfoAndUserIdFromToken(request);
return callDao.createCallStep1(createCallRequest, Long.parseLong(userInfo.get("userId").toString()));
UserEntity user = validator.validateUser(request);
return callDao.createCallStep1(createCallRequest, user);
}
@Override
@Transactional(rollbackFor = Exception.class)
public CallResponse createCallStep2(HttpServletRequest request, Long callId, CreateCallRequestStep2 createCallRequest) {
Map<String, Object> userInfo= tokenProvider.getUserInfoAndUserIdFromToken(request);
return callDao.createCallStep2(callId, createCallRequest, Long.parseLong(userInfo.get("userId").toString()));
UserEntity user = validator.validateUser(request);
CallEntity call = validator.validateUserWithCall(user, callId);
return callDao.createCallStep2(call, createCallRequest, user);
}
@Override
@Transactional(rollbackFor = Exception.class)
public CallResponse updateCallStep1(HttpServletRequest request, Long callId,
UpdateCallRequestStep1 updateCallRequest) {
Map<String, Object> userInfo= tokenProvider.getUserInfoAndUserIdFromToken(request);
return callDao.updateCallStep1(callId, updateCallRequest, Long.parseLong(userInfo.get("userId").toString()));
UserEntity user = validator.validateUser(request);
CallEntity call = validator.validateUserWithCall(user, callId);
return callDao.updateCallStep1(call, updateCallRequest, user);
}
@Override
@Transactional(readOnly = true)
public CallResponse getCallById(Long callId) {
return callDao.getCallById(callId);
public CallResponse getCallById(HttpServletRequest request, Long callId) {
UserEntity user = validator.validateUser(request);
CallEntity call = validator.validateUserWithCall(user, callId);
return callDao.getCallById(call);
}
@Override
@Transactional(readOnly = true)
public List<CallDetailsResponseBean> getAllCalls(HttpServletRequest request) {
Map<String, Object> userInfo= tokenProvider.getUserInfoAndUserIdFromToken(request);
UserEntity user=tokenProvider.validateUser(userInfo);
UserEntity user = validator.validateUser(request);
return callDao.getAllCalls(user);
}
@Override
@Transactional(rollbackFor = Exception.class)
public CallResponse validateCallData(Long callId) {
return callDao.validateCallData(callDao.validateCall(callId));
}
@Override
public CallEntity getCallEntityById(Long id){
return callDao.getCallEntityById(id);
public CallResponse validateCallData(HttpServletRequest request, Long callId) {
UserEntity user = validator.validateUser(request);
CallEntity call = validator.validateUserWithCall(user, callId);
return callDao.validateCallData(call);
}
@Override
@Transactional(rollbackFor = Exception.class)
public CallResponse updateCallStatus(HttpServletRequest request, Long callId, CallStatusEnum statusReq) {
return callDao.updateCallStatus(callId, statusReq);
UserEntity user = validator.validateUser(request);
CallEntity call = validator.validateUserWithCall(user, callId);
return callDao.updateCallStatus(call, statusReq);
}
@@ -88,13 +90,15 @@ public class CallServiceImpl implements CallService {
return callDao.validateCall(callId);
}
@Override
public CallEntity validatePublishedCall(Long callId) {
return callDao.validatePublishedCall(callId);
}
@Override
@Transactional(readOnly = true)
public byte[] downloadCallDocumentsAsZip(Long callId) {
return callDao.downloadCallDocumentsAsZip(callId);
}
}
@Override
public CallEntity validatePublishedCall(Long callId) {
return callDao.validatePublishedCall(callId);
}
@Override
@Transactional(readOnly = true)
public byte[] downloadCallDocumentsAsZip(Long callId) {
return callDao.downloadCallDocumentsAsZip(callId);
}
}

View File

@@ -22,7 +22,8 @@ public class DashboardServiceImpl implements DashboardService {
@Override
public SuperAdminWidgetResponseBean getDashboardWidgetForSuperAdmin(HttpServletRequest request) {
return dashboardDao.getDashboardWidget();
UserEntity userEntity=validator.validateUser(request);
return dashboardDao.getDashboardWidget(userEntity);
}
@Override

View File

@@ -3,12 +3,15 @@ package net.gepafin.tendermanagement.service.impl;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.dao.FormDao;
import net.gepafin.tendermanagement.entities.ApplicationEntity;
import net.gepafin.tendermanagement.entities.CallEntity;
import net.gepafin.tendermanagement.entities.FormEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.model.request.ApplicationFormFieldRequestBean;
import net.gepafin.tendermanagement.model.request.FormRequest;
import net.gepafin.tendermanagement.model.response.FormResponseBean;
import net.gepafin.tendermanagement.service.FormService;
import net.gepafin.tendermanagement.util.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@@ -20,25 +23,32 @@ public class FormServiceImpl implements FormService {
@Autowired
private FormDao formDao;
@Autowired
private Validator validator;
@Override
public FormResponseBean createForm(HttpServletRequest request,Long callId, FormRequest formRequest) {
return formDao.createForm(callId,formRequest);
UserEntity user = validator.validateUser(request);
CallEntity call = validator.validateUserWithCall(user, callId);
return formDao.createForm(call,formRequest);
}
@Override
public FormResponseBean updateForm(HttpServletRequest request, Long formId, FormRequest formRequest,Boolean forceDeleteFlow) {
return formDao.updateForm(formId,formRequest,forceDeleteFlow);
UserEntity user = validator.validateUser(request);
return formDao.updateForm(user, formId,formRequest,forceDeleteFlow);
}
@Override
public FormResponseBean getFormById(HttpServletRequest request, Long formId) {
return formDao.getFormEntityById(formId);
UserEntity user = validator.validateUser(request);
return formDao.getFormEntityById(user, formId);
}
@Override
public void deleteForm(HttpServletRequest request, Long formId) {
formDao.deleteFormById(formId);
return;
UserEntity user = validator.validateUser(request);
formDao.deleteFormById(user, formId);
}
@Override
@@ -48,7 +58,9 @@ public class FormServiceImpl implements FormService {
@Override
public List<FormResponseBean> getFormsByCallId(HttpServletRequest request, Long callId) {
return formDao.getFormsByCallId(callId);
UserEntity user = validator.validateUser(request);
CallEntity call = validator.validateUserWithCall(user, callId);
return formDao.getFormsByCallId(call);
}
@Override

View File

@@ -0,0 +1,59 @@
package net.gepafin.tendermanagement.service.impl;
import net.gepafin.tendermanagement.dao.HubDao;
import net.gepafin.tendermanagement.entities.HubEntity;
import net.gepafin.tendermanagement.model.request.HubReq;
import net.gepafin.tendermanagement.model.response.HubResponseBean;
import net.gepafin.tendermanagement.service.HubService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class HubServiceImpl implements HubService {
@Autowired
private HubDao hubDao;
@Override
@Transactional(rollbackFor = Exception.class)
public HubResponseBean createHub(HubReq hubReq) {
return hubDao.createHub(hubReq);
}
@Override
@Transactional(rollbackFor = Exception.class)
public HubResponseBean updateHub(Long hubId, HubReq hubReq) {
return hubDao.updateHub(hubId, hubReq);
}
@Override
@Transactional(readOnly = true)
public HubResponseBean getHubById(Long hubId) {
return hubDao.getHubById(hubId);
}
@Override
@Transactional(readOnly = true)
public List<HubResponseBean> getAllHubs() {
return hubDao.getAllHubs();
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteHub(Long hubId) {
hubDao.deleteHub(hubId);
}
@Override
public HubEntity getHubByUuid(String hubUuid) {
return hubDao.getHubByUuid(hubUuid);
}
@Override
public HubResponseBean getHubByHubUuid(String uuid) {
return hubDao.getHubByHubUuid(uuid);
}
}

View File

@@ -2,13 +2,11 @@ package net.gepafin.tendermanagement.service.impl;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.config.SamlSuccessHandler;
import net.gepafin.tendermanagement.dao.UserDao;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.model.request.LoginReq;
import net.gepafin.tendermanagement.model.request.UpdateUserReq;
import net.gepafin.tendermanagement.model.request.UserReq;
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
import net.gepafin.tendermanagement.enums.UserStatusEnum;
import net.gepafin.tendermanagement.model.request.*;
import net.gepafin.tendermanagement.model.response.UserSamlResponse;
@@ -33,17 +31,9 @@ public class UserServiceImpl implements UserService {
@Autowired
private Validator validator;
@Autowired
private SamlSuccessHandler samlSuccessHandler;
@Override
@Transactional(rollbackFor = Exception.class)
public JWTToken createUser(HttpServletRequest request, String tempToken, UserReq userReq) {
if (tempToken == null) {
validator.validateRequest(request,RoleStatusEnum.ROLE_SUPER_ADMIN);
}else {
samlSuccessHandler.validateToken(tempToken, userReq.getCodiceFiscale());
}
return userDao.createUser(request, tempToken, userReq);
}
@@ -67,7 +57,7 @@ public class UserServiceImpl implements UserService {
}
@Override
public JWTToken login(LoginReq loginReq,HttpServletRequest request) {
public JWTToken login(LoginReq loginReq, HttpServletRequest request) {
return userDao.login(loginReq,request);
}
@@ -87,8 +77,8 @@ public class UserServiceImpl implements UserService {
return userDao.resetPassword(resetPasswordReq);
}
@Override
public Boolean changePassword(ChangePasswordRequest request){
return userDao.changePassword(request);
public Boolean changePassword(HttpServletRequest httpServletRequest, ChangePasswordRequest request){
return userDao.changePassword(validator.validateUser(httpServletRequest), request);
}
@Override
public void logoutUser(HttpServletRequest request, HttpServletResponse response) {
@@ -127,8 +117,8 @@ public class UserServiceImpl implements UserService {
}
@Override
@Transactional(readOnly = true)
public List<UserResponseBean> getAllUsers(Long roleId) {
// Calling DAO Function
return userDao.getAllUsers(roleId);
public List<UserResponseBean> getAllUsers(HttpServletRequest request, Long roleId) {
UserEntity user=validator.validateUser(request);
return userDao.getAllUsers(user, roleId);
}
}

View File

@@ -4,9 +4,12 @@ import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.config.jwt.TokenProvider;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.dao.CallDao;
import net.gepafin.tendermanagement.entities.CallEntity;
import net.gepafin.tendermanagement.entities.CompanyEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
import net.gepafin.tendermanagement.service.CallService;
import net.gepafin.tendermanagement.service.CompanyService;
import net.gepafin.tendermanagement.service.UserService;
import net.gepafin.tendermanagement.web.rest.api.errors.ForbiddenAccessException;
@@ -33,6 +36,9 @@ public class Validator {
@Autowired
private CompanyService companyService;
@Autowired
private CallService callService;
public Map<String, Object> getUserInfoFromToken(HttpServletRequest request) {
return tokenProvider.getUserInfoAndUserIdFromToken(request);
}
@@ -100,4 +106,14 @@ public class Validator {
return Long.parseLong(userInfo.get("userId").toString());
}
public CallEntity validateUserWithCall(UserEntity user, Long callId) {
CallEntity callEntity = callService.validateCall(callId);
if(user.getHub().getId().equals(callEntity.getHub().getId())) {
throw new ForbiddenAccessException(Status.FORBIDDEN, Translator.toLocale(GepafinConstant.PERMISSION_DENIED));
}
return callEntity;
}
}

View File

@@ -85,7 +85,7 @@ public interface CallApi {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
@GetMapping(value = "/{callId}",
produces = { "application/json" })
ResponseEntity<Response<CallResponse>> getCallById(
ResponseEntity<Response<CallResponse>> getCallById(HttpServletRequest request,
@Parameter(description = "The call ID", required = true) @PathVariable("callId") Long callId);

View File

@@ -0,0 +1,113 @@
package net.gepafin.tendermanagement.web.rest.api;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.model.request.HubReq;
import net.gepafin.tendermanagement.model.response.HubResponseBean;
import net.gepafin.tendermanagement.model.util.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.validation.Valid;
import net.gepafin.tendermanagement.web.rest.api.errors.ErrorConstants;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Validated
@RequestMapping("/hub")
public interface HubApi {
@Operation(summary = "API to create a hub", responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) }))
})
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
@PostMapping(value = "", produces = "application/json")
ResponseEntity<Response<HubResponseBean>> createHub(HttpServletRequest request,
@Parameter(description = "Hub request object", required = true)
@Valid @RequestBody HubReq hubReq);
@Operation(summary = "API to update a hub", responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) }))
})
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
@PutMapping(value = "/{hubId}", produces = "application/json")
ResponseEntity<Response<HubResponseBean>> updateHub(HttpServletRequest request,
@Parameter(description = "The hub id", required = true)
@PathVariable("hubId") Long hubId,
@Parameter(description = "Hub request object", required = true)
@Valid @RequestBody HubReq hubReq);
@Operation(summary = "API to get a hub by id", responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) }))
})
@GetMapping(value = "/{hubId}", produces = "application/json")
ResponseEntity<Response<HubResponseBean>> getHubById(HttpServletRequest request,
@Parameter(description = "The hub id", required = true)
@PathVariable("hubId") Long hubId);
@Operation(summary = "API to get all hubs", responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) }))
})
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
@GetMapping(value = "", produces = "application/json")
ResponseEntity<Response<List<HubResponseBean>>> getAllHubs(HttpServletRequest request);
@Operation(summary = "API to delete a hub", responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) }))
})
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
@DeleteMapping(value = "/{hubId}")
ResponseEntity<Response<Void>> deleteHub(HttpServletRequest request,
@Parameter(description = "The hub id", required = true)
@PathVariable("hubId") Long hubId);
@Operation(summary = "API to get a hub by id", responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) }))
})
@GetMapping(value = "/uuid/{uuid}", produces = "application/json")
ResponseEntity<Response<HubResponseBean>> getHubByUuid(HttpServletRequest request,
@Parameter(description = "The hub id", required = true)
@PathVariable("uuid") String uuid);
}

View File

@@ -144,8 +144,10 @@ public interface UserApi {
@RequestMapping(value = "/change-password",
produces = {"application/json"},
method = RequestMethod.POST)
ResponseEntity<Response<Boolean>> changePassword(
@Parameter(description = "Change password request object", required = true) @Valid @RequestBody ChangePasswordRequest changePasswordRequest); @Operation(summary = "Api to logout user",
ResponseEntity<Response<Boolean>> changePassword(HttpServletRequest request,
@Parameter(description = "Change password request object", required = true) @Valid @RequestBody ChangePasswordRequest changePasswordRequest);
@Operation(summary = "Api to logout user",
responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@@ -192,6 +194,7 @@ public interface UserApi {
produces = { "application/json" })
ResponseEntity<Response<UserResponseBean>> getValidUser(HttpServletRequest request);
@Operation(summary = "Api to validate existing user from saml token",
responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@@ -232,7 +235,7 @@ public interface UserApi {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE)}))})
@RequestMapping(value = "", produces = {"application/json"}, method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
ResponseEntity<Response<List<UserResponseBean>>> getAllUsers(
ResponseEntity<Response<List<UserResponseBean>>> getAllUsers(HttpServletRequest request,
@Parameter( required = false)@RequestParam(value ="roleId", required = false) Long roleId);

View File

@@ -59,8 +59,8 @@ public class CallApiController implements CallApi {
}
@Override
@Transactional(readOnly = true)
public ResponseEntity<Response<CallResponse>> getCallById(Long callId) {
CallResponse createCallResponseBean = callService.getCallById(callId);
public ResponseEntity<Response<CallResponse>> getCallById(HttpServletRequest request, Long callId) {
CallResponse createCallResponseBean = callService.getCallById(request, callId);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(createCallResponseBean, Status.SUCCESS, Translator.toLocale(GepafinConstant.CALL_FETCH_SUCCESS_MSG)));
}
@@ -76,7 +76,7 @@ public class CallApiController implements CallApi {
}
@Override
public ResponseEntity<Response<CallResponse>> validateCallData(HttpServletRequest request, Long callId) {
CallResponse call = callService.validateCallData(callId);
CallResponse call = callService.validateCallData(request, callId);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(call, Status.SUCCESS, Translator.toLocale(GepafinConstant.CALL_FETCH_SUCCESS_MSG)));

View File

@@ -29,10 +29,13 @@ public class CustomUserDetailsService implements UserDetailsService {
@Override
@Transactional
public UserDetails loadUserByUsername(final String email) throws UsernameNotFoundException {
log.debug("Authenticating {}", email);
public UserDetails loadUserByUsername(final String emailWithHudId) throws UsernameNotFoundException {
log.debug("Authenticating {}", emailWithHudId);
String[] loginParts = emailWithHudId.split(":");
String email = loginParts[0];
String hubId = loginParts[1];
UserEntity user = userRepository.findByEmailIgnoreCase(email)
UserEntity user = userRepository.findByEmailIgnoreCaseAndHubUniqueUuid(email, hubId)
.orElseThrow(
() -> new UsernameNotFoundException("User " + email + " was not found in the database"));
return createSpringSecurityUser(user);

View File

@@ -0,0 +1,73 @@
package net.gepafin.tendermanagement.web.rest.api.impl;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.model.request.HubReq;
import net.gepafin.tendermanagement.model.response.HubResponseBean;
import net.gepafin.tendermanagement.model.util.Response;
import net.gepafin.tendermanagement.service.HubService;
import net.gepafin.tendermanagement.web.rest.api.HubApi;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class HubApiController implements HubApi {
@Autowired
private HubService hubService;
@Override
public ResponseEntity<Response<HubResponseBean>> createHub(HttpServletRequest request, @Valid HubReq hubReq) {
HubResponseBean hubResponse = hubService.createHub(hubReq);
return ResponseEntity.status(HttpStatus.CREATED)
.body(new Response<>(hubResponse, Status.SUCCESS, Translator.toLocale(GepafinConstant.HUB_CREATE_SUCCESS)));
}
@Override
public ResponseEntity<Response<HubResponseBean>> updateHub(HttpServletRequest request, Long hubId, @Valid HubReq hubReq) {
HubResponseBean hubResponse = hubService.updateHub(hubId, hubReq);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(hubResponse, Status.SUCCESS, Translator.toLocale(GepafinConstant.HUB_UPDATE_SUCCESS)));
}
@Override
public ResponseEntity<Response<HubResponseBean>> getHubById(HttpServletRequest request, Long hubId) {
HubResponseBean hubResponse = hubService.getHubById(hubId);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(hubResponse, Status.SUCCESS, Translator.toLocale(GepafinConstant.HUB_GET_SUCCESS)));
}
@Override
public ResponseEntity<Response<List<HubResponseBean>>> getAllHubs(HttpServletRequest request) {
List<HubResponseBean> hubs = hubService.getAllHubs();
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(hubs, Status.SUCCESS, Translator.toLocale(GepafinConstant.HUB_GET_ALL_SUCCESS)));
}
@Override
public ResponseEntity<Response<Void>> deleteHub(HttpServletRequest request, Long hubId) {
hubService.deleteHub(hubId);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(null, Status.SUCCESS, Translator.toLocale(GepafinConstant.HUB_DELETE_SUCCESS)));
}
@Override
public ResponseEntity<Response<HubResponseBean>> getHubByUuid(HttpServletRequest request, String uuid) {
HubResponseBean hubResponse = hubService.getHubByHubUuid(uuid);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(hubResponse, Status.SUCCESS, Translator.toLocale(GepafinConstant.HUB_GET_SUCCESS)));
}
}

View File

@@ -79,9 +79,9 @@ public class UserApiController implements UserApi {
return ResponseEntity.ok(new Response<>(jwtToken, Status.SUCCESS, Translator.toLocale(GepafinConstant.LOGIN_SUCCESS_MSG)));
}
@Override
public ResponseEntity<Response<Boolean>> changePassword(@Valid @RequestBody ChangePasswordRequest request) {
public ResponseEntity<Response<Boolean>> changePassword(HttpServletRequest httpServletRequest, @Valid @RequestBody ChangePasswordRequest request) {
log.info("Change Password attempt for email: {}", request.getEmail());
userService.changePassword(request);
userService.changePassword(httpServletRequest, request);
return ResponseEntity.ok(new Response<>(null, Status.SUCCESS, Translator.toLocale(GepafinConstant.SUCCESS_PASSWORD_CHANGED)));
}
@Override
@@ -142,10 +142,10 @@ public class UserApiController implements UserApi {
return ResponseEntity.ok(new Response<>(data, Status.SUCCESS, Translator.toLocale(GepafinConstant.TOKEN_VALIDATE_SUCCESS_MSE)));
}
@Override
public ResponseEntity<Response<List<UserResponseBean>>> getAllUsers(
public ResponseEntity<Response<List<UserResponseBean>>> getAllUsers(HttpServletRequest request,
Long roleId) {
log.info("Get all Users by Role ID - Role ID: {}", roleId);
List<UserResponseBean> users = userService.getAllUsers(roleId);
List<UserResponseBean> users = userService.getAllUsers(request, roleId);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(users, Status.SUCCESS, Translator.toLocale(GepafinConstant.GET_USERS_SUCCESS_MSG)));
}

View File

@@ -64,4 +64,5 @@ default_System_Receiver_Email=antonio.manca@bflows.net
gepafin_email=bandi@pec.gepafin.it
rinaldo_email=rinaldo.bonazzo@bflows.net
carlo_email=carlo.mancosu@bflows.net
default.hub.uuid=p4lk3bcx1RStqTaIVVbXs

View File

@@ -749,6 +749,72 @@
<column name="updated_date" type="TIMESTAMP WITHOUT TIME ZONE"></column>
</createTable>
</changeSet>
<changeSet id="24-09-2024_1" author="Harish Bagora">
<createTable tableName="hub">
<column name="ID" type="BIGINT" autoIncrement="true">
<constraints primaryKey="true" nullable="false" unique="true" primaryKeyName="hub_pkey"/>
</column>
<column name="COMPANY_NAME" type="VARCHAR(255)">
<constraints nullable="false"/>
</column>
<column name="FIRST_NAME" type="VARCHAR(255)"/>
<column name="LAST_NAME" type="VARCHAR(255)"/>
<column name="EMAIL" type="VARCHAR(255)">
<constraints nullable="false"/>
</column>
<column name="CITY" type="VARCHAR(255)"/>
<column name="COUNTRY" type="VARCHAR(255)">
<constraints nullable="false"/>
</column>
<column name="VAT_NUMBER" type="VARCHAR(255)">
<constraints nullable="false" unique="true"/>
</column>
<column name="DOMAIN_NAME" type="VARCHAR(255)"/>
<column name="APP_CONFIG" type="TEXT"/>
<column name="UNIQUE_UUID" type="VARCHAR(255)">
<constraints nullable="false" unique="true"/>
</column>
<column name="CREATED_DATE" type="TIMESTAMP WITHOUT TIME ZONE">
<constraints nullable="true"/>
</column>
<column name="UPDATED_DATE" type="TIMESTAMP WITHOUT TIME ZONE">
<constraints nullable="true"/>
</column>
</createTable>
</changeSet>
<changeSet id="24-09-2024_2" author="Harish Bagora">
<insert tableName="hub">
<column name="COMPANY_NAME" value="bandi gepafin Company"/>
<column name="FIRST_NAME" value="John"/>
<column name="LAST_NAME" value="Doe"/>
<column name="EMAIL" value="john.doe@test.test"/>
<column name="CITY" value="rome"/>
<column name="COUNTRY" value="italy"/>
<column name="VAT_NUMBER" value="12345678974"/>
<column name="DOMAIN_NAME" value="https://bandi-staging.memento.credit"/>
<column name="APP_CONFIG" value="{}"/>
<column name="UNIQUE_UUID" value="p4lk3bcx1RStqTaIVVbXs"/>
<column name="created_date" value="2024-10-24 00:00:00"/>
<column name="updated_date" value="2024-10-24 00:00:00"/>
</insert>
<insert tableName="hub">
<column name="COMPANY_NAME" value="sviluppumbria"/>
<column name="FIRST_NAME" value="svilupp"/>
<column name="LAST_NAME" value="umbria"/>
<column name="EMAIL" value="sviluppumbria@test.test"/>
<column name="CITY" value="rome"/>
<column name="COUNTRY" value="italy"/>
<column name="VAT_NUMBER" value="98765432152"/>
<column name="DOMAIN_NAME" value="https://bandi-staging.sviluppumbria.it"/>
<column name="APP_CONFIG" value="{}"/>
<column name="UNIQUE_UUID" value="t7jh5wfg9QXylNaTZkPoE"/>
<column name="created_date" value="2024-10-24 00:00:00"/>
<column name="updated_date" value="2024-10-24 00:00:00"/>
</insert>
</changeSet>
<changeSet id="25-09-2024_2" author="Nisha kashyap">
<update tableName="form_field">
@@ -1146,4 +1212,78 @@
</column>
</addColumn>
</changeSet>
<changeSet id="17-10-2024_1" author="Rajesh Khore">
<!-- Step 1: Add the HUB_ID column as nullable initially -->
<addColumn tableName="GEPAFIN_USER">
<column name="HUB_ID" type="INTEGER"/>
</addColumn>
<addColumn tableName="CALL">
<column name="HUB_ID" type="INTEGER"/>
</addColumn>
<!-- Step 2: Update the HUB_ID column with a default value -->
<update tableName="GEPAFIN_USER">
<column name="HUB_ID" value="1"/> <!-- Set to the default hub id -->
</update>
<update tableName="CALL">
<column name="HUB_ID" value="1"/> <!-- Set to the default hub id -->
</update>
<!-- Step 3: Alter the columns to be NOT NULL and add foreign key constraints -->
<addNotNullConstraint tableName="GEPAFIN_USER" columnName="HUB_ID" columnDataType="INTEGER"/>
<addNotNullConstraint tableName="CALL" columnName="HUB_ID" columnDataType="INTEGER"/>
<addForeignKeyConstraint baseTableName="GEPAFIN_USER"
baseColumnNames="HUB_ID"
referencedTableName="HUB"
referencedColumnNames="ID"
constraintName="fk_hub_gepafin_user"/>
<addForeignKeyConstraint baseTableName="CALL"
baseColumnNames="HUB_ID"
referencedTableName="HUB"
referencedColumnNames="ID"
constraintName="fk_hub_gepafin_call"/>
</changeSet>
<changeSet id="19-10-2024_1" author="Harish Bagora">
<addColumn tableName="saml_response">
<column name="IN_RESPONSE_TO" type="TEXT"/>
<column name="ISSUE_INSTANT" type="TEXT"/>
<column name="SAML_ID" type="TEXT"/>
<column name="HUB_UUID" type="varchar(255)"/>
<column name="status" type="varchar(255)"/>
</addColumn>
<addColumn tableName="protocol">
<column name="HUB_ID" type="TEXT"/>
</addColumn>
<insert tableName="gepafin_user">
<column name="password" value="$2a$10$doUyOcEm8WPuFfpFT5y18.1DvZzF7exbqgy9X0P27cUBK7YWbfzzS"/>
<column name="email" value="sviluppumbriaUser@test.test"/>
<column name="first_name" value="Super"/>
<column name="last_name" value="User"/>
<column name="phone_number" value="1234567890"/>
<column name="role_id" valueComputed="2"/>
<column name="status" value="ACTIVE"/>
<column name="last_login" value="2024-08-14 00:00:00"/>
<column name="created_date" value="2024-08-14 00:00:00"/>
<column name="updated_date" value="2024-08-14 00:00:00"/>
<column name="organization" value="SuperOrg"/>
<column name="address" value="123 Main Street"/>
<column name="city" value="Rome"/>
<column name="country" value="Italy"/>
<column name="HUB_ID" value="2"/>
</insert>
</changeSet>
</databaseChangeLog>

View File

@@ -256,5 +256,13 @@ cannot.create.beneficiary.user = Creation of a Beneficiary user is not allowed.
evaluationCriteria.invalid=This evaluation criterion does not belong to the current call.
# Hub Messages
hub_create_success=Hub created successfully
hub_update_success=Hub updated successfully
hub_get_success=Hub retrieved successfully
hub_get_all_success=Hubs retrieved successfully
hub_delete_success=Hub deleted successfully
hub_not_found=Hub not found

View File

@@ -246,10 +246,17 @@ delete.signed.document.file.success=Documento firmato eliminato con successo.
dashboard.widget.fetched.successfully=Widget dashboard recuperato correttamente.
login_attempt_successfully_created= Tentativo di login creato con successo.
get_login_attempt_se_msg=Lista dei tentativi di accesso recuperata correttamente.
application.in.submit.status.cannot.delete.company=Non è possibile eliminare l'azienda perché ci sono domande attive con stato SUBMITTED.
application.in.submit.status.cannot.delete.company=Non <EFBFBD> possibile eliminare l'azienda perch<EFBFBD> ci sono domande attive con stato SUBMITTED.
get.users.success.msg = Utenti recuperati con successo
cannot.create.beneficiary.user = La creazione di un utente beneficiario non è consentita. Si prega di assegnare il ruolo appropriato.
cannot.create.beneficiary.user = La creazione di un utente beneficiario non <EFBFBD> consentita. Si prega di assegnare il ruolo appropriato.
evaluationCriteria.invalid=Questo criterio di valutazione non appartiene alla chiamata corrente.
# Hub Messages
hub_create_success=Hub creato con successo
hub_update_success=Hub aggiornato con successo
hub_get_success=Hub recuperato con successo
hub_get_all_success=Hub recuperati con successo
hub_delete_success=Hub eliminato con successo
hub_not_found=Hub non trovato