package com.cpop.core.service.impl;

import com.cpop.common.constant.Constants;
import com.cpop.common.utils.StringUtils;
import com.cpop.core.base.entity.LoginUser;
import com.cpop.core.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Set;

/**
 * @author: DB
 * @date: 2022-10-20 15:15
 * @Description:
 * AuthorityPermissionService：自定义access表达式，鉴权验证。
 * 可以将自定义的access添加到配置类中：http.anyRequest.access(aps.hasPermission(xxx,xxx));
 * 也可以直接使用注解@PreAuthorize：@PreAuthorize(aps.hasPermission(xxx));
 */
@Service("aps")
public class AuthorityPermissionService {

    public boolean hasPermission(String permissions) {
        if (StringUtils.isEmpty(permissions)) {
            return false;
        }
        // 用户信息对象
        LoginUser loginUser = SecurityUtils.getInstance().getLoginUser();
        if (loginUser == null || CollectionUtils.isEmpty(loginUser.getPermissions())) {
            return false;
        }
        Set<String> authorities = loginUser.getPermissions();
        return StringUtils.isNotEmpty(permissions) && hasPermissions(authorities, permissions);
    }

    private boolean hasPermissions(Set<String> authorities, String permission) {
        return authorities.contains(Constants.ALL_PERMISSION) || authorities.contains(permission.trim());
    }
}
