package cn.qinys.platform.base.security.aspect;


import cn.qinys.platform.base.exceptions.BizException;
import cn.qinys.platform.base.security.annotation.HasPermission;
import cn.qinys.platform.base.security.utils.CurrentUtils;
import cn.qinys.platform.base.vo.LoginUserInfo;
import lombok.SneakyThrows;
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.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Description:
 *
 * @author tanlie
 * Date: 2024/1/9 11:01
 */
@Aspect
@Component
@Order(2)
@Slf4j
public class HasPermissionAspect {
    @SneakyThrows
    @Around("@annotation(hasPermission)")
    public Object around(ProceedingJoinPoint pjp, HasPermission hasPermission) {
        if (!hasPermission.open()) {
            return pjp.proceed();
        }
        // 超级管理员不校验权限
        LoginUserInfo userInfo = CurrentUtils.getCurrentUserInfo();
        if ("1".equalsIgnoreCase(userInfo.getSuperAdmin())) {
            return pjp.proceed();
        }
        List<String> codes = CurrentUtils.getPermissionCodes();
        String[] permissionCodes = hasPermission.value();
        boolean hasPerms = false;
        for (String code : permissionCodes) {
            if (codes.contains(code)) {
                hasPerms = true;
                break;
            }
        }
        if (hasPerms) {
            return pjp.proceed();
        }
        throw new BizException(403, "没有权限：" + String.join(",", permissionCodes));
    }

}
