package com.skr.mdm.filter;

import com.skr.mdm.authentication.TokenExpireException;
import com.skr.mdm.authentication.admin.AdminAuthenticationEntryPoint;
import com.skr.mdm.constant.RequestHeaderConstants;
import com.skr.mdm.dto.LoginAdminDTO;
import com.skr.mdm.service.AdminTokenService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token过滤器
 * @author nfq
 */
@Component
@Slf4j
public class AdminTokenFilter extends OncePerRequestFilter {

    @Autowired
    private AdminTokenService tokenService;
    @Autowired
    private AdminAuthenticationEntryPoint authenticationEntryPoint;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        request = new XssHttpRequestWrapper(request);
        String token = getToken(request);
        if (StringUtils.isNotBlank(token)) {
            LoginAdminDTO loginAdminDTO = null;
            try {
                loginAdminDTO = tokenService.getLoginAdmin(token);
                if (loginAdminDTO == null) {
                    filterChain.doFilter(request, response);
                    return;
                }
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(loginAdminDTO, null, loginAdminDTO.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authentication);
            } catch (TokenExpireException e) {
                authenticationEntryPoint.commence(request, response, e);
                return;
            }
        }
        //响应头处理
//        xssProtect(response);
        filterChain.doFilter(request, response);
    }

    /**
     * 根据参数或者header获取JWTtoken
     *
     * @param request
     * @return
     */
    public static String getToken(HttpServletRequest request) {
        String token = request.getParameter(RequestHeaderConstants.REQUEST_HEADER_TOKEN);
        if (StringUtils.isBlank(token)) {
            token = request.getHeader(RequestHeaderConstants.REQUEST_HEADER_TOKEN);
        }
        return token;
    }

    /**
     * 响应头处理
     *
     * @param response
     */
    private void xssProtect(HttpServletResponse response) {
        // 开启浏览器XSS过滤器
        response.setHeader("X-XSS-Protection", "1; mode=block");
        // 禁止页面加载到frame框架中
        response.setHeader("X-Frame-Options", "deny");
        // 阻止浏览器做MIMEtype嗅探
        response.setHeader("X-Content-Type-Options", "nosniff");
        // 定义了URL或页面内容中加载对象的策略（防止xss最有效的解决方案之一）
        response.setHeader("Content-Security-Policy", "default-src 'self'");
        // 限制JavaScript访问cookie
        response.setHeader("Set-Cookie", "HttpOnly");
    }

}
