package com.lutao.cloud.common.security.aspect;

import com.lutao.cloud.common.core.util.MessageInfo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

/**
 * Create by guoyc on 2021/12/21
 */
@Component
@Aspect
public class AuthTokenAspect{
    /// @Around是可以改变controller返回值的
    @Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable{
        // 放行
        MessageInfo messageInfo = new MessageInfo();
        Object proceed = pjp.proceed();
        if (proceed != null){
            ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>) proceed;
            OAuth2AccessToken body = responseEntity.getBody();
            if (responseEntity.getStatusCode().is2xxSuccessful()){
                messageInfo = MessageInfo.ok(body);
            } else{
                messageInfo = MessageInfo.failed(body);
            }
        }
        return ResponseEntity.status(HttpStatus.OK).body(messageInfo);
    }
}
