package com.philisense.www.handler;

import com.alibaba.fastjson.JSON;
import com.philisense.www.constant.HttpStatus;
import com.philisense.www.utils.ServletUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

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

/**
 * 需要在 方法上 加入 @PreAuthorize("hasRole('ROLE_AAA')") 注解
 * 支持并不使用
 * 这里不会返回数据，被 SecurityExceptionHandler 权限校验异常处理了
 *
 * @Description:如果用户已经通过身份验证，试图访问受保护的(该用户没有权限的)资源
 * @author
 */
@Component("jwtAccessDeniedHandler")
public class JwtAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {    	
        Map<String,Object> responsemap = new HashMap<>();
        responsemap.put("success", false);
        responsemap.put("message", "您的权限不足，无法访问该资源，请联系管理员授权");
        responsemap.put("error", "Forbidden");
        responsemap.put("status", HttpStatus.FORBIDDEN);
        responsemap.put("timestamp", new Date());
        responsemap.put("path", httpServletRequest.getRequestURI());
        ServletUtils.renderString(httpServletResponse, JSON.toJSONString(responsemap));
    }
}

