package cn.quantgroup.xyqb.security;

import cn.qg.ec.model.user.UserLoginRegEvent;
import cn.quantgroup.xyqb.service.event.KinesisService;
import cn.quantgroup.xyqb.urora.UroraAuthenticationManager;
import cn.quantgroup.xyqb.urora.UroraAuthenticationToken;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2021/6/25 0025.
 */
@Aspect
@Component
public class AuthorizationAspect extends HttpAspect {

    private static final Logger logger = LoggerFactory.getLogger(AuthorizationAspect.class);

    @Autowired
    private AuthenticationAdapter authenticationAdapter;

    @Pointcut("@annotation(cn.quantgroup.xyqb.security.AuthorizationPoint)")
    private void pointCut() {
    }

    @Around("pointCut()")
    private Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        AssentHeader header = getAssentHeader();
//        kinesisService.send(UserLoginRegEvent.SubEventType.user_attempt_login, header, null);
        Authentication authenticate = authenticationAdapter.authenticate(header.getAuthType(), header.getAuthMessage());
        if(!authenticate.isAuthenticated()){
            throw new BadCredentialsException("not authorized");
        }
        AuthorityManager.authentication(authenticate);
        try {
            Object object = joinPoint.proceed();
            return object;
        }finally {
            AuthorityManager.release();
        }
    }
}
