ludc
2023-09-12 7f9d6840cc01c25ac9816df60dbac3d040594fa3
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
package com.vci.ubcs.code.service.impl;
 
import com.vci.ubcs.code.service.IPasswordFreeLoginService;
import com.vci.ubcs.code.util.HttpUtils;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestTemplate;
 
import javax.annotation.Resource;
import java.util.List;
 
/**
 * 免密登录服务
 * @author ludc
 * @date 2023/9/11 15:45
 */
@Service
public class PasswordFreeLoginServiceImpl implements IPasswordFreeLoginService {
 
    // 通过服务注册中心获取网关的端口号
    @Autowired
    private DiscoveryClient discoveryClient;
 
    /**
     * 获取网关端口
     * @return
     */
    public String getGatewayPort() {
        List<ServiceInstance> instances = discoveryClient.getInstances("ubcs-gateway");
        if (!instances.isEmpty()) {
            ServiceInstance gatewayInstance = instances.get(0);
            return String.valueOf(gatewayInstance.getPort());
        }
        return "80";
    }
 
    /**
     * 免密登录
     * @param account 账号
     * @return
     */
    @Override
    public boolean passwordFreeLogin(String account) {
        // 免密登录接口地址
        String loginUrl = "http://localhost:"+this.getGatewayPort()+"/ubcs-auth/oauth/passwordFreeLogin?username=admin&grant_type=captcha&scope=all&type=account";
 
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
 
        //设置请求体参数
        MultiValueMap<String,String> bodyParams = new LinkedMultiValueMap<String,String>();
        bodyParams.add("account",account);
 
        // 发送POST请求
        String responseBody = HttpUtils.post(loginUrl, bodyParams);
        System.out.println(responseBody);
        //拿到响应体将token存入到redis中,以account作为存储的key
 
        // 解析响应体获取令牌
        // 这里假设响应体是JSON格式,包含一个名为"token"的字段
        // 根据实际情况进行解析
        // JSONObject json = new JSONObject(responseBody);
        // String token = json.getString("token");
 
        return false;
    }
 
 
}