com.vcredit.lrh.microservice.gateway.api.redis.SecurityHandlerRedis.java Source code

Java tutorial

Introduction

Here is the source code for com.vcredit.lrh.microservice.gateway.api.redis.SecurityHandlerRedis.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vcredit.lrh.microservice.gateway.api.redis;

import com.alibaba.fastjson.JSONObject;
import com.vcredit.lrh.commons.constants.LrhConstants;
import com.vcredit.lrh.commons.constants.RedisCacheKeys;
import com.vcredit.lrh.commons.utils.Base64Utils;
import com.vcredit.lrh.db.redis.template.O2ORedisTemplate;
import com.vcredit.lrh.microservice.gateway.api.filter.O2OSecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * @author Liu Jianwei<liujianwei@vcredit.com>
 * @date 2016-5-14
 */
@Component("securityHandlerRedis")
@EnableConfigurationProperties({ O2OSecurityProperties.class })
public class SecurityHandlerRedis {

    Logger logger = LoggerFactory.getLogger(SecurityHandlerRedis.class);

    @Autowired
    //    @Qualifier("o2oRedisTemplate")
    O2ORedisTemplate redisTemplate;

    @Autowired
    O2OSecurityProperties securityProperties;

    private Map<String, List<String>> securityMap = null;

    @Value("${version.iosAppVertion}")
    private String iosAppVertion;

    @Value("${version.andriodAppVersion}")
    private String andriodAppVersion;

    //    @Autowired
    //    private O2OAccessTokenRepo repository;
    public void process(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        String token = "";
        String clientVersion = "";
        String deviceType = "";
        //header??
        String base64Str = servletRequest.getHeader("clientHeader");
        if (!StringUtils.isEmpty(base64Str)) {
            String headerJsonStr = Base64Utils.getFromBase64(base64Str);
            JSONObject headerJson = JSONObject.parseObject(headerJsonStr);
            token = headerJson.getString("accessToken");
            try {
                clientVersion = headerJson.getString("apiClientVersion");
                deviceType = headerJson.getString("deviceType");
                //add by xuhui 20170406
                if (!StringUtils.isEmpty(clientVersion)) {
                    if ("iOS".equals(deviceType) && iosAppVertion.compareTo(clientVersion) > 0) {
                        JSONObject jSONObject = new JSONObject();
                        PrintWriter pw = httpServletResponse.getWriter();
                        jSONObject.put("type", LrhConstants.ErrorCodeTypeEnum.FORCEUPDATE.getCode());
                        jSONObject.put("success", true);
                        jSONObject.put("code", 201);
                        Map<String, Object> map = new HashMap();
                        //?
                        map.put("updateUrl", "");
                        map.put("updateInfo", "");
                        map.put("updateTargetVersion", iosAppVertion);
                        map.put("forceUpdate", true);
                        map.put("appType", "iOS");
                        jSONObject.put("data", map);
                        pw.write(jSONObject.toJSONString());
                        pw.flush();
                    }
                    if ("android".equals(deviceType) && andriodAppVersion.compareTo(clientVersion) > 0) {
                        JSONObject jSONObject = new JSONObject();
                        PrintWriter pw = httpServletResponse.getWriter();
                        jSONObject.put("type", LrhConstants.ErrorCodeTypeEnum.FORCEUPDATE.getCode());
                        jSONObject.put("success", true);
                        jSONObject.put("code", 201);
                        Map<String, Object> map = new HashMap();
                        //?
                        map.put("updateUrl",
                                "http://10.154.40.42:7777/lrh_apk_android_20_v0.0.1/vcredit_lrh_debug_v0.0.2_2017_0421_1041_Vcredit_TecentQQ.apk");
                        map.put("updateInfo", "");
                        map.put("updateTargetVersion", andriodAppVersion);
                        map.put("forceUpdate", true);
                        map.put("appType", "android");
                        jSONObject.put("data", map);
                        pw.write(jSONObject.toJSONString());
                        pw.flush();
                    }
                }
            } catch (Exception e) {
            }
        }

        //        String token = request.getParameter("accessToken") == null ? accessTokenFromHeader : request.getParameter("accessToken");
        if (StringUtils.isEmpty(token)) {
            token = servletRequest.getSession().getId().toUpperCase();
        }
        String openId = request.getParameter("open_id");
        httpServletResponse.setHeader("Content-Type", "application/json");
        try {
            if (servletRequest.getServletPath().equals(securityProperties.getLoginSecurityUrl())) {
                chain.doFilter(request, response);
            } else if (servletRequest.getServletPath().equals("/favicon.ico")) {
                chain.doFilter(request, response);
                //                PrintWriter pw = httpServletResponse.getWriter();
                //                pw.write("favicon.ico");
                //                pw.flush();
            } else if (openId == null && null == token) {
                unauthorizedRequest(httpServletResponse);
            } else if (needAuthentication(servletRequest.getServletPath())) {
                //                JSONObject currentUser = securityService.getUserByAccessToken(token);
                JSONObject currentUser = redisTemplate.get(RedisCacheKeys.ACCOUNT_CACHE_TOKEN + token,
                        JSONObject.class);
                if (null == currentUser) {
                    unauthorizedRequest(httpServletResponse);
                } else {
                    chain.doFilter(request, response);
                }
            } else {
                chain.doFilter(request, response);
            }
        } catch (ServletException ex) {
            logger.error(ex.getMessage(), ex);
            serverErrorRequest(httpServletResponse);
        }
    }

    private void serverErrorRequest(HttpServletResponse httpServletResponse) throws IOException {
        JSONObject jSONObject = new JSONObject();
        PrintWriter pw = httpServletResponse.getWriter();
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        jSONObject.put("status", "error");
        jSONObject.put("code", HttpServletResponse.SC_NOT_ACCEPTABLE);
        jSONObject.put("message", "server error , please try again later...");
        pw.write(jSONObject.toJSONString());
        pw.flush();
    }

    private void unauthorizedRequest(HttpServletResponse httpServletResponse) throws IOException {
        JSONObject jSONObject = new JSONObject();
        PrintWriter pw = httpServletResponse.getWriter();
        //        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        jSONObject.put("type", LrhConstants.ErrorCodeTypeEnum.RELOGIN.getCode());
        jSONObject.put("success", false);
        jSONObject.put("code", HttpServletResponse.SC_UNAUTHORIZED);
        jSONObject.put("message", "???");
        pw.write(jSONObject.toJSONString());
        pw.flush();
    }

    private boolean needAuthentication(String requestPath) {
        boolean flag = false;

        if (null == securityMap) {
            securityMap = new HashMap<>();
            Map<String, String> filterUrls = securityProperties.getFilterChainDefinitions();
            List<String> anno = new ArrayList<>();
            List<String> auth = new ArrayList<>();
            Set<String> keys = filterUrls.keySet();
            for (String key : keys) {
                int keyIndex = key.indexOf("/**");
                String newkey = key;
                if (keyIndex > 0) {
                    newkey = key.substring(0, keyIndex).trim();
                }

                if (filterUrls.get(key).trim().equals("anno")) {
                    anno.add(newkey);
                } else {
                    auth.add(newkey);
                }
            }

            securityMap.put("anno", anno);
            securityMap.put("auth", auth);
        }
        List<String> auth = securityMap.get("auth");
        for (String string : auth) {
            if (requestPath.startsWith(string)) {
                flag = true;
                break;
            }
        }
        return flag;
    }
}