Filter存使用者資訊

IT的魚發表於2020-12-21
  @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        //判斷如果是APP請求,則直接通過
        String requestURI = httpServletRequest.getRequestURI();
        if (requestURI.startsWith("/e/welink") ||
                requestURI.startsWith("/e/test/welink") ||
                requestURI.startsWith("/e/approve/waitApprove") ||
                requestURI.startsWith("/e/page/applicationPage") ||
                requestURI.startsWith("/e/ows/user/listRole") ||
                requestURI.endsWith(".ttf") ||
                requestURI.endsWith(".woff") ||
                requestURI.endsWith(".eot") ||
                requestURI.endsWith(".woff2") ||
                requestURI.endsWith(".css") ||
                requestURI.endsWith(".js") ||
                requestURI.endsWith(".png") ||
                requestURI.endsWith(".jpg") ||
                requestURI.endsWith(".wav") ||
                requestURI.endsWith(".xlsx") ||
                requestURI.endsWith(".svg") ||
                requestURI.startsWith("/e/api/csp/") ||
                requestURI.endsWith("/e/api/important_contact/all") ||
                requestURI.contains("getRepOffAndIndustry") ||
                requestURI.contains("getAllQcLine")
                // requestURI.endsWith("/e/promotion/test")
                ) {
            chain.doFilter(request, response);
            return;
        }
        if (requestURI.indexOf("/e/page") != -1) {
            if (isMSBrowser(httpServletRequest)) {
                response.setCharacterEncoding("gbk");
                PrintWriter out = response.getWriter();
                out.println("<div>本系統不支援 IE EDGE 等瀏覽器,推薦使用 Google Chrome瀏覽器,謝謝。</div>");
                return;
            }
        }
        HttpSession session = httpServletRequest.getSession();
        UserInfoBean uiBean = (UserInfoBean) session
                .getAttribute(SsoConstants.SESSION_USER_INFO_KEY);
        if (uiBean == null) {   //會話已經超時
            if (CommonUtil.isAjax(httpServletRequest)) {   //ajax請求會話超時,filter不會進入統一異常攔截
                Map<String, String> map = new HashMap<>();
                map.put("code", "401");
                response.setCharacterEncoding("utf-8");
                response.getWriter().print(JSONObject.toJSON(map));
                return;
            }
            try {
                // 從 sso 跳轉回來 回到當前訪問的 url
                SsoUtil.loginAndRedirect2AppCurrentURL((HttpServletRequest) request,
                        (HttpServletResponse) response);
                return;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                User token = null;
                try (Jedis jedis = jedisPool.getResource()) {
                    String redisKey = "userInfo_" + uiBean.getUid();
                    String tokenStr = jedis.get(redisKey);
                    if (StringUtils.isNotBlank(tokenStr)) {
                        token = JSON.parseObject(tokenStr, User.class);
                    }
                    if (token == null) {//|| token.getRootList().size() == 0
                        Result r = userService.login((HttpServletRequest) request,
                                (HttpServletResponse) response);
                        token = (User) r.getData();
                        if ("N".equals(token.getIsVaild())) {
                            if (CommonUtil.isAjax(httpServletRequest)) {   //ajax請求會話超時,filter不會進入統一異常攔截
                                throw new BadRequestException("此賬號已被禁用,如需開通,請聯絡系統管理員 王超偉 w00509928 !");
                            } else {
                                response.setCharacterEncoding("gbk");
                                response.getWriter().println("此賬號已被禁用,如需開通,請聯絡系統管理員 王超偉 w00509928 !");
                                return;
                            }
                        }

                        // "審批"跳轉流程
                        if (token.getIsExists()) {
                            // 使用者表"存在"使用者
                            Boolean redirect2ApplicationPage = approveLoginFilter.redirectWithUserExist(token);
                            if (redirect2ApplicationPage) {
                                ((HttpServletResponse) response).sendRedirect(((HttpServletRequest) request).getContextPath() + "/page/applicationPage?agentId=" + token.getUserAgentId());
                                return;
                            }
                        } else {
                            // 使用者表"不存在"使用者
                            Map<String, Object> newUserMap = approveLoginFilter.getNewUserByOldAgentId(token); // 檢視是否更換賬號
                            if (ObjectUtils.isEmpty(newUserMap)) {
                                // 沒有更換賬號,則表示完全為一個新的賬戶,按照正常的流程
                                approveLoginFilter.redirectWithUserNotExist(token);
                                ((HttpServletResponse) response).sendRedirect(((HttpServletRequest) request).getContextPath() + "/page/applicationPage?agentId=" + token.getUserAgentId());
                                return;
                            } else {
                                // 更換了賬號,則需要重新跳轉至 使用者表"存在"使用者流程
                                User newUser = new User();
                                newUser.setId((String) newUserMap.get("ID"));
                                newUser.setUserAgentId((String) newUserMap.get("USER_AGENTID"));
                                newUser.setUserEmail((String) newUserMap.get("USER_EMAIL"));
                                newUser.setUserPhono((String) newUserMap.get("USER_PHONE"));
                                newUser.setCreateTime((Long) newUserMap.get("CREATE_DATE"));
                                newUser.setRoleId((String) newUserMap.get("ROLE_ID"));
                                newUser.setQc_line((String) newUserMap.get("QC_LINE"));
                                newUser.setRep_off((String) newUserMap.get("REP_OFF"));
                                Boolean redirect2ApplicationPage = approveLoginFilter.redirectWithUserExist(newUser);
                                if (redirect2ApplicationPage) {
                                    ((HttpServletResponse) response).sendRedirect(((HttpServletRequest) request).getContextPath() + "/page/applicationPage?agentId=" + token.getUserAgentId());
                                    return;
                                } else {
                                    // 重新登入
                                    Result loginResult = userService.login((HttpServletRequest) request, (HttpServletResponse) response);
                                    token = (User) loginResult.getData();
                                }
                            }
                        }

                        // 載入整改配置角色
                        userService.setRectRole(token);
                        // 載入選單、許可權等
                        userService.loadUserResource(token);
//                        session.setAttribute("userInfo", token);
                        logUtils.log("登入", null, token.getUserAgentId(), token.getId());
                        dao.commit();
                        jedis.set(redisKey, JSON.toJSONString(token));
                        log.info("從資料庫中載入使用者資訊");
                    }
                    // 設定過期時間 單位(秒)
                    jedis.expire(redisKey, EXP_TIME);
                }
                Method m = AppContext.class.getDeclaredMethod("setCurrentUser", User.class);
                m.setAccessible(true);
                m.invoke(null, token);
                chain.doFilter(request, response);
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex);
            } finally {
                AppContext.clearAll();
                try {
                    dao.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

相關文章