package cn.datax.auth.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Slf4j
public class AuthTokenAspect {

    @Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    public Object handleControllerMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        DataOauthResponse dataOauthResponse = new DataOauthResponse();
        Object proceed = joinPoint.proceed();
        if (proceed != null) {
            ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>)proceed;
            OAuth2AccessToken body = responseEntity.getBody();
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                dataOauthResponse.setCode(200);
                dataOauthResponse.setSuccess(true);
                dataOauthResponse.setData(body);
            } else {
                log.error("error:{}", responseEntity.getStatusCode().toString());
                dataOauthResponse.setCode(500);
                dataOauthResponse.setMsg("客户端授权失败");
                dataOauthResponse.setSuccess(false);
            }
        }
        return ResponseEntity
                .status(200)
                .body(dataOauthResponse);
    }
}
