updated code

This commit is contained in:
harish
2024-10-20 02:37:53 +05:30
parent 1073c705f0
commit 998c2ba01f
17 changed files with 187 additions and 54 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);

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

View File

@@ -120,6 +120,9 @@ 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) {
FormEntity formEntity = formService.validateForm(formId);
@@ -602,8 +605,7 @@ public class ApplicationDao {
if (totalSteps.intValue() != completedSteps) {
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_IS_INCOMPLETE_MSG));
}
Long maxProtocolNumber=protocolRepository.findMaxProtocolNumber();
Long 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 +620,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));

View File

@@ -14,7 +14,6 @@ import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
@Component
@@ -89,4 +88,9 @@ public class HubDao {
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)));
}
}

View File

@@ -114,7 +114,7 @@ public class UserDao {
Translator.toLocale(GepafinConstant.VALIDATE_EMAIL));
}
log.info("Creating user with email: {}", userReq.getEmail());
if (userRepository.existsByEmailIgnoreCaseAndhubUniqueUuid(userReq.getEmail(), userReq.getHubUuid())) {
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));
@@ -301,7 +301,7 @@ public class UserDao {
public String initiatePasswordReset(InitiatePasswordResetReq resetReq) {
UserEntity user = userRepository
.findByEmailIgnoreCaseAndhubUniqueUuid(resetReq.getEmail(), resetReq.getHubUuid())
.findByEmailIgnoreCaseAndHubUniqueUuid(resetReq.getEmail(), resetReq.getHubUuid())
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
@@ -314,7 +314,7 @@ public class UserDao {
public Boolean resetPassword(ResetPasswordReq resetPasswordReq) {
UserEntity user = userRepository
.findByEmailIgnoreCaseAndhubUniqueUuid(resetPasswordReq.getEmail(), resetPasswordReq.getHubUuid())
.findByEmailIgnoreCaseAndHubUniqueUuid(resetPasswordReq.getEmail(), resetPasswordReq.getHubUuid())
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
@@ -338,7 +338,7 @@ public class UserDao {
public Boolean changePassword(UserEntity userEntity, ChangePasswordRequest request) {
UserEntity user = userRepository
.findByEmailIgnoreCaseAndhubUniqueUuid(request.getEmail(), userEntity.getHub().getUniqueUuid())
.findByEmailIgnoreCaseAndHubUniqueUuid(request.getEmail(), userEntity.getHub().getUniqueUuid())
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));

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

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

@@ -1,10 +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")
Long 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;
@@ -20,12 +19,13 @@ public interface UserRepository extends JpaRepository<UserEntity, Long> {
Optional<UserEntity> findByBeneficiaryCodiceFiscale(String codiceFiscale);
boolean existsByBeneficiaryCodiceFiscale(String codiceFiscale);
UserEntity findByBeneficiaryId(Long beneficiaryId);
Long countByStatusAndRoleEntityRoleType(String status, String roleName);
List<UserEntity> findByRoleEntityId(Long roleId);
Optional<UserEntity> findByEmailIgnoreCaseAndhubUniqueUuid(String email, String hubId);
Optional<UserEntity> findByEmailIgnoreCaseAndHubUniqueUuid(String email, String hubId);
boolean existsByEmailIgnoreCaseAndhubUniqueUuid(String email, String hubUuid);
boolean existsByEmailIgnoreCaseAndHubUniqueUuid(String email, String hubUuid);
}

View File

@@ -1,9 +1,9 @@
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 net.gepafin.tendermanagement.model.util.Response;
import java.util.List;
@@ -13,4 +13,5 @@ public interface HubService {
HubResponseBean getHubById(Long hubId);
List<HubResponseBean> getAllHubs();
void deleteHub(Long hubId);
HubEntity getHubByUuid(String hubUuid);
}

View File

@@ -81,7 +81,7 @@ public class AuthenticationService {
Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
log.info("Authentication successful for email: {}", loginReq.getEmail());
user = userRepository.findByEmailIgnoreCaseAndhubUniqueUuid(loginReq.getEmail(), loginReq.getHubUuid())
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,6 +1,7 @@
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;
@@ -45,4 +46,9 @@ public class HubServiceImpl implements HubService {
public void deleteHub(Long hubId) {
hubDao.deleteHub(hubId);
}
@Override
public HubEntity getHubByUuid(String hubUuid) {
return hubDao.getHubByUuid(hubUuid);
}
}

View File

@@ -35,7 +35,7 @@ public class CustomUserDetailsService implements UserDetailsService {
String email = loginParts[0];
String hubId = loginParts[1];
UserEntity user = userRepository.findByEmailIgnoreCaseAndhubUniqueUuid(email, hubId)
UserEntity user = userRepository.findByEmailIgnoreCaseAndHubUniqueUuid(email, hubId)
.orElseThrow(
() -> new UsernameNotFoundException("User " + email + " was not found in the database"));
return createSpringSecurityUser(user);