张晓波
2023-09-19 164694c47c35d6654df69b533e8dbf8b5423efc5
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
package com.thhy.gateway.config;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.StringUtil;
import com.thhy.general.common.BasicResult;
import com.thhy.general.common.BasicStatus;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
 
import java.nio.charset.StandardCharsets;
 
public class GlobalFilters implements GlobalFilter, Ordered {
 
    @Autowired
    private ExcludeRoute excludeRoute;
 
    @Autowired
    private RedissonClient redissonClient;
 
    @Value("${global.keyPrefix}")
    private String keyPrefix;
 
    private static final String ALL = "*";
    private static final String MAX_AGE = "18000L";
 
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        exchange.getLogPrefix();
        System.out.println("这是全局");
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        System.out.println("访问路径"+path);
        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders headers = response.getHeaders();
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*");
        headers.add("MultipleAllowOriginValues","*");
        headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, ALL);
        headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
        if (request.getMethod() == HttpMethod.OPTIONS) {
            response.setStatusCode(HttpStatus.OK);
            return Mono.empty();
        }
 
 
        String[] excludeurls = excludeRoute.getExcludeurls();
 
        for(String excludeurl : excludeurls){
            if(path.equals(excludeurl)||path.contains(excludeurl)){
                return chain.filter(exchange);
            }
        }
 
        if(!request.getHeaders().containsKey("usertoken")){
            BasicResult basicResult = new BasicResult(false, BasicStatus.TOKEN_IS_NULL);  //请登录
            return buildReturnMono(JSON.toJSONString(basicResult),exchange);
        }
 
        String userToken = request.getHeaders().get("usertoken").get(0);
 
        Object obj = getUserInfo(userToken,exchange);
        if(obj==null){
            BasicResult basicResult = new BasicResult(false, BasicStatus.LOGIN_INFO_IS_ERROR);  //登录信息异常
            return buildReturnMono(JSON.toJSONString(basicResult),exchange);
        }
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(obj));
        if(!jsonObject.containsKey("userId")||StringUtil.isNullOrEmpty(jsonObject.getString("userId"))){
            BasicResult basicResult = new BasicResult(false, BasicStatus.LOGIN_INFO_IS_ERROR);  //登录信息异常
            return buildReturnMono(JSON.toJSONString(basicResult),exchange);
            //throw new BasicException(BasicStatus.LOGIN_INFO_IS_ERROR);
        }
        //BodyHandlerServerHttpResponseDecorator responseDecorator = new BodyHandlerServerHttpResponseDecorator(bodyHandler, exchange.getResponse());
        return chain.filter(exchange);
 
    }
 
    public static Mono<Void> buildReturnMono(String jsonStr, ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        byte[] bits = jsonStr.getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.OK);
        HttpHeaders headers = response.getHeaders();
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*");
        headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, ALL);
        headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
        //指定编码,否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
 
    public Object getUserInfo(String token,ServerWebExchange exchange){
        RBucket<Object> rBucket = redissonClient.getBucket(keyPrefix+":usertoken:"+ token);
        Object obj = rBucket.get();
        return obj;
    }
 
    @Override
    public int getOrder() {
        return 0;
    }
}