package com.user.service.core;

import com.alibaba.fastjson.JSON;
import com.base.orbit.constant.HttpStatus;
import com.base.orbit.domain.AjaxResult;
import com.base.orbit.utils.ServletUtils;
import com.base.orbit.utils.StringUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

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

/**
 * 用于解决认证过的用户访问无权限资源时的异常
 */
@Component
public class JsonAccessDenieHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        int code = HttpStatus.UNAUTHORIZED;
        String msg = StringUtils.format("请求访问：{}，没有访问权限!", httpServletRequest.getRequestURI());
        ServletUtils.renderString(httpServletResponse, JSON.toJSONString(AjaxResult.error(code, msg)));
    }
}
