教育训练处考试制证系统后端
zhangf
2024-09-11 1a316551c8e46b793904090cfa84781bf77fef2a
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
package com.ruoyi.framework.interceptor;
 
 
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.ResultConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.InstitutionUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.security.context.ThreeInContextHolder;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
 
/**
 * 自定义三方对接数据校验
 */
@Component
public class ThreeInstitutionInterceptor implements HandlerInterceptor {
 
    @Autowired
    private TokenService tokenService;
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        InstitutionUser institutionUser = tokenService.getThreeInUser(request);
        if (StringUtils.isNotNull(institutionUser))
        {
            tokenService.verifyThreeInToken(institutionUser);
            ThreeInContextHolder.setContext(institutionUser);
        }else {
            toJson(response,ResultConstants.ACCESS_TOKEN_OVERDUE.getCode(),ResultConstants.ACCESS_TOKEN_OVERDUE.getDesc());
            return false;
        }
        return true;
    }
 
    private void toJson(HttpServletResponse response,int code, String msg) throws IOException {
 
        AjaxResult result = AjaxResult.error(code, msg);
        // 设置编码格式
        response.setContentType("text/json;charset=utf-8");
        // 处理跨域问题
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS");
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(result));
        out.flush();
        out.close();
    }
 
 
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
 
        // 清除threadLocal
        ThreeInContextHolder.clearContext();
    }
}