package com.philisense.www.exception;

import com.philisense.www.constant.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * spring security异常处理
 *
 * @author
 */
@RestControllerAdvice
public class SecurityExceptionHandler extends GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 权限校验异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public Map<String, Object> handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
        result.put(DATASUCCESS, false);
        result.put(DATASTATUS, HttpStatus.FORBIDDEN);
        result.put(DATAMESSAGE, "您的权限不足，无法访问该资源，请联系管理员授权");
        return result;
    }
}
