保誠-保戶業務員媒合平台
Jack
2022-01-14 98471b0ef1a5751c8acea4354c93c63a1e95d42c
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
package com.pollex.pam.service;
 
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import com.pollex.pam.domain.Customer;
import com.pollex.pam.enums.CustomerDetailEnum;
import com.pollex.pam.repository.CustomerRepository;
import com.pollex.pam.security.jwt.TokenProvider;
import com.pollex.pam.security.token.OtpAuthenticationToken;
import com.pollex.pam.web.rest.vm.OtpAccount;
 
@Service
@Transactional
public class CustomerAuthService {
 
    @Autowired
    AuthenticationManagerBuilder authenticationManagerBuilder;
 
    @Autowired
    CustomerRepository customerRepository;
 
    @Autowired
    TokenProvider tokenProvider;
 
    public String authorize(Customer account, String indexKey, String otpCode) {
        OtpAccount otpAccount = OtpAccount.createOtpAccount(account, indexKey);
        OtpAuthenticationToken authenticationToken = new OtpAuthenticationToken(
            otpAccount,
            otpCode
        );
 
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
 
        Authentication authentication = buildCustomerAuthToken(account, otpCode, indexKey);
        String jwt = tokenProvider.createToken(authentication, false);
        return jwt;
    }
 
    public UsernamePasswordAuthenticationToken buildCustomerAuthToken(Customer customer
            , String otpCode, String indexKey) {
 
        List<GrantedAuthority> grantedAuths = Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"));
 
        final String account = customer.toAccountString();
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(account, otpCode, grantedAuths);
 
        Map<String, String> details = new HashMap<>();
        details.put(CustomerDetailEnum.DB_ID.getValue(), customer.getId().toString());
        authenticationToken.setDetails(details);
 
        return authenticationToken;
    }
}