From 5e8b57aacdbf94cd57c4d3533ded5ee73ff71340 Mon Sep 17 00:00:00 2001 From: jack <jack.su@pollex.com.tw> Date: 星期五, 27 十二月 2024 14:43:28 +0800 Subject: [PATCH] [UPDATE] 透過e service 登入時調整判斷錯誤的邏輯, 如果登入失敗的時候也需要從DB提取錯誤訊息顯示 --- pamapi/src/main/java/com/pollex/pam/security/provider/EServiceAuthenticationProvider.java | 142 ++++++++++++++++------------------------------ 1 files changed, 50 insertions(+), 92 deletions(-) diff --git a/pamapi/src/main/java/com/pollex/pam/security/provider/EServiceAuthenticationProvider.java b/pamapi/src/main/java/com/pollex/pam/security/provider/EServiceAuthenticationProvider.java index a5b9aaa..1860b1b 100644 --- a/pamapi/src/main/java/com/pollex/pam/security/provider/EServiceAuthenticationProvider.java +++ b/pamapi/src/main/java/com/pollex/pam/security/provider/EServiceAuthenticationProvider.java @@ -1,28 +1,20 @@ package com.pollex.pam.security.provider; -import com.fasterxml.jackson.core.JsonProcessingException; +import com.pollex.pam.business.domain.Consultant; +import com.pollex.pam.business.enums.ConsultantDetailEnum; +import com.pollex.pam.business.repository.ConsultantRepository; +import com.pollex.pam.business.repository.EServiceErrorCodeRepository; +import com.pollex.pam.business.service.EServiceConnectService; +import com.pollex.pam.business.service.dto.EServiceResponse; +import com.pollex.pam.business.web.errors.ConsultantDisableException; +import com.pollex.pam.business.config.AppProperties; +import com.pollex.pam.business.security.token.EServiceAuthenticationToken; +import com.pollex.pam.business.web.errors.EServiceErrorException; import com.pollex.pam.config.ApplicationProperties; -import com.pollex.pam.domain.Consultant; -import com.pollex.pam.enums.ConsultantDetailEnum; -import com.pollex.pam.enums.ConsultantStatusEnum; -import com.pollex.pam.repository.ConsultantRepository; -import com.pollex.pam.security.token.EServiceAuthenticationToken; -import com.pollex.pam.service.LoginRecordService; -import com.pollex.pam.service.dto.EServiceResponse; -import com.pollex.pam.web.rest.errors.ConsultantDisableException; -import com.pollex.pam.web.rest.errors.EServiceErrorException; -import org.apache.http.conn.ssl.NoopHostnameVerifier; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.ssl.SSLContexts; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.*; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; @@ -30,18 +22,11 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.util.UriComponentsBuilder; -import javax.net.ssl.SSLContext; import java.security.GeneralSecurityException; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.X509Certificate; import java.util.*; -import static com.pollex.pam.enums.ConsultantStatusEnum.DISABLE; +import static java.util.Arrays.asList; @Component public class EServiceAuthenticationProvider { @@ -50,55 +35,73 @@ private static final Logger log = LoggerFactory.getLogger(EServiceAuthenticationProvider.class); @Autowired - ApplicationProperties applicationProperty; + ApplicationProperties applicationProperties; @Autowired ConsultantRepository consultantRepository; @Autowired - LoginRecordService loginRecordService; + EServiceConnectService eServiceConnectService; + + @Autowired + EServiceErrorCodeRepository eServiceErrorCodeRepository; public Authentication authenticate(EServiceAuthenticationToken authenticationToken) throws AuthenticationException { String account = authenticationToken.getPrincipal(); String credentials = authenticationToken.getCredentials(); - if(applicationProperty.isMockLogin()){ - loginRecordService.saveEServiceLoginSuccessRecord(account); - return getConsultantToken(account, credentials); + + if(applicationProperties.isMockLogin()){ + return getConsultantTokenAndRecordLoginTime(account, credentials); } + + try { - ResponseEntity<EServiceResponse> responseEntity = loginByEService(account, credentials); + ResponseEntity<EServiceResponse> responseEntity = eServiceConnectService.loginByEService(account, credentials); if(HttpStatus.OK.equals(responseEntity.getStatusCode())) { EServiceResponse eServiceResponse = responseEntity.getBody(); log.debug("eService response = {}", eServiceResponse); - if(E_SERVICE_LOGIN_SUCCESS_CODE.equals(eServiceResponse.getIssuccess())){ - loginRecordService.saveEServiceLoginSuccessRecord(account); - return getConsultantToken(account, credentials); + if(eServiceResponse == null) { + throw new RuntimeException("eService error!, response body is null"); } - else { - loginRecordService.saveEServiceLoginFailRecord(account, eServiceResponse.getMsg()); - throw new EServiceErrorException(eServiceResponse.getMsg()); + + List<String> successCode = new ArrayList<>(asList("0","3","4","6")); + + if(successCode.contains(eServiceResponse.getCode())) { + return getConsultantTokenAndRecordLoginTime(account, credentials); + } else { + log.debug("account:{},error:{}",account,eServiceResponse.getMsg()); + eServiceErrorCodeRepository.findByErrorCode(eServiceResponse.getCode()). + ifPresent(eServiceErrorCode -> { + throw new EServiceErrorException(eServiceErrorCode.getErrorMessage()); + }); + + throw new EServiceErrorException("�頛詨�����炊嚗��頛詨"); } + +// if(E_SERVICE_LOGIN_SUCCESS_CODE.equals(eServiceResponse.getIssuccess())){ +// +// return getConsultantTokenAndRecordLoginTime(account, credentials); +// } +// else { +// log.debug("account:{},error:{}",account,eServiceResponse.getMsg()); +// throw new EServiceErrorException("�頛詨�����炊嚗��頛詨"); +// } } throw new RuntimeException("eService http error!, response http status code = " + responseEntity.getStatusCode()); - } catch (JsonProcessingException e) { - throw new RuntimeException("convert to json processing error!"); } catch (GeneralSecurityException e) { + log.error("General Security SSL error!",e); throw new RuntimeException("General Security SSL error!"); } } - private UsernamePasswordAuthenticationToken getConsultantToken(String account, String credential) throws ConsultantDisableException { - Consultant consultant = consultantRepository.findOneByAgentNo(account).orElseThrow(() -> new UsernameNotFoundException("閰脤“����蒂銝��慦�像�蝟餌絞銝�")); + private UsernamePasswordAuthenticationToken getConsultantTokenAndRecordLoginTime(String account, String credential) throws ConsultantDisableException { + Consultant consultant = consultantRepository.findOneByAgentNo(account).orElseThrow(() -> new UsernameNotFoundException("撣唾��Ⅳ�隤�")); - if(consultant.getStatus() == DISABLE) { - throw new ConsultantDisableException("憿批�董�����銝�"); - } - - List<GrantedAuthority> grantedAuths = Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")); + List<GrantedAuthority> grantedAuths = Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(account, credential, grantedAuths); Map<String, String> details = new HashMap<>(); @@ -108,50 +111,5 @@ authenticationToken.setDetails(details); return authenticationToken; - } - - private ResponseEntity<EServiceResponse> loginByEService(String account, String paxxword) throws JsonProcessingException, GeneralSecurityException { - RestTemplate restTemplate = getTrustAllRestTemplate(); - settingMessageConvertersToSpecifyType(restTemplate, MediaType.ALL); - - String urlTemplate = UriComponentsBuilder.fromHttpUrl(applicationProperty.geteServiceLoginUrl()) - .queryParam("func", applicationProperty.geteServiceLoginFunc()) - .queryParam("id", account) - .queryParam("pin", paxxword) - .queryParam("pwd", paxxword) - .queryParam("sys", applicationProperty.geteServiceLoginSys()) - .queryParam("transactionId", UUID.randomUUID().toString()) - .encode().toUriString(); - - log.debug("http get loginByEService, url = {}", urlTemplate); - - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON); - - HttpEntity<String> entity = new HttpEntity<>(headers); - return restTemplate.exchange(urlTemplate, HttpMethod.GET, entity, EServiceResponse.class); - } - - private RestTemplate getTrustAllRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { - SSLContext sslContext = SSLContexts.custom() - .loadTrustMaterial(null, (X509Certificate[] x509Certs, String s) -> true) - .build(); - SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); - CloseableHttpClient httpClient = HttpClients.custom() - .setSSLSocketFactory(csf) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); - requestFactory.setHttpClient(httpClient); - requestFactory.setConnectTimeout(300000); - requestFactory.setReadTimeout(300000); - return new RestTemplate(requestFactory); - } - - private void settingMessageConvertersToSpecifyType(RestTemplate restTemplate, MediaType mediaType) { - List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); - MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); - converter.setSupportedMediaTypes(Collections.singletonList(mediaType)); - messageConverters.add(converter); - restTemplate.setMessageConverters(messageConverters); } } -- Gitblit v1.8.0