package com.jiayue.center.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jiayue.center.backenum.AuditType;
import com.jiayue.center.backenum.BusinessStatus;
import com.jiayue.center.backenum.BusinessType;
import com.jiayue.center.entity.SysOperLog;
import com.jiayue.center.factory.OperateLogFactory;
import com.jiayue.center.service.SysPolicyService;
import com.jiayue.center.util.IPUtils;
import com.jiayue.center.util.JwtTokenUtil;
import com.jiayue.center.util.ServletUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 权限不足：认证过的用户访问无权限资源时的异常
 *
 * @author zzy
 * @version 1.0
 * @since 2018/8/23 14:45
 */
@Service
@Slf4j
public class RestAccessDeniedHandler implements AccessDeniedHandler {
    @Autowired
    SysPolicyService sysPolicyService;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException {
        String token = request.getHeader("Authorization");
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        Claims claims = jwtTokenUtil.getClaimsFromToken(token);
        String username="";
        if (claims==null){
            username = "未知用户";
        }
        else{
            username = claims.getSubject();
        }
        SysOperLog operLog = new SysOperLog();
        operLog.setStatus(BusinessStatus.FAIL.ordinal());
        // 请求的地址
        String ip = IPUtils.getIpAddr();
        operLog.setOperIp(ip);
        operLog.setOperUrl(org.apache.commons.lang3.StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255));
        operLog.setOperName(username);
        // 设置请求方式
        operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
        operLog.setCreateBy(username);
        // 设置action动作
        operLog.setBusinessType(BusinessType.BAC.ordinal());
        // 设置标题
        operLog.setTitle("越权访问");
        // 操作描述
        operLog.setOperdesc("越权访问");
        // 审计类型
        operLog.setAuditType(AuditType.SYS.ordinal());
        // 保存数据库
        OperateLogFactory.recordOper(operLog);

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setStatus(402);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("没有接口访问权限！");
    }
}
