保誠-保戶業務員媒合平台
wayne
2022-02-17 a3716f72066d25d745f4d5103ff23a553c3e102b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package com.pollex.pam.security.provider;
 
import com.fasterxml.jackson.core.JsonProcessingException;
import com.pollex.pam.config.ApplicationProperties;
import com.pollex.pam.domain.Consultant;
import com.pollex.pam.enums.ConsultantDetailEnum;
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.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;
import org.springframework.security.core.GrantedAuthority;
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.*;
 
@Component
public class EServiceAuthenticationProvider {
 
    private static final String E_SERVICE_LOGIN_SUCCESS_CODE = "true";
    private static final Logger log = LoggerFactory.getLogger(EServiceAuthenticationProvider.class);
 
    @Autowired
    ApplicationProperties applicationProperty;
 
    @Autowired
    ConsultantRepository consultantRepository;
 
    @Autowired
    LoginRecordService loginRecordService;
 
    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);
        }
 
        try {
            ResponseEntity<EServiceResponse> responseEntity = 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);
                }
                else {
                    loginRecordService.saveEServiceLoginFailRecord(account, eServiceResponse.getMsg());
                    throw new EServiceErrorException(eServiceResponse.getMsg());
                }
            }
 
            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) {
            throw new RuntimeException("General Security SSL error!");
        }
    }
 
    private UsernamePasswordAuthenticationToken getConsultantToken(String account, String credential) {
        Consultant consultant = consultantRepository.findOneByAgentNo(account).orElseThrow(() -> new UsernameNotFoundException("該顧問資料並不存在於媒合平台系統中"));
 
        List<GrantedAuthority> grantedAuths = Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"));
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(account, credential, grantedAuths);
 
        Map<String, String> details = new HashMap<>();
        details.put(ConsultantDetailEnum.ID.getValue(), consultant.getId().toString());
        details.put(ConsultantDetailEnum.NAME.getValue(), consultant.getName());
        details.put(ConsultantDetailEnum.AGENT_NO.getValue(), account);
        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);
    }
}