All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.zhxu.bp.auth.AuthRule Maven / Gradle / Ivy

The newest version!
package cn.zhxu.bp.auth;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author Troy.Zhou @ 2022/8/2 17:22
 */
public class AuthRule {

    static final int TYPE_AUTHORITY = 1;
    static final int TYPE_OR_GROUP = 3;

    private final int type;

    /**
     * 关系为:且
     */
    private List auths;

    /**
     * 关系为:或
     */
    private List orRules;


    AuthRule(int type) {
        this.type = type;
    }

    public static AuthRule from(String authAttr) {
        if (authAttr.contains("|")) {
            AuthRule authRule = new AuthRule(AuthRule.TYPE_OR_GROUP);
            for (String authAttr0 : authAttr.split("\\|")) {
                AuthRule rule = new AuthRule(AuthRule.TYPE_AUTHORITY);
                rule.auths = Arrays.asList(authAttr0.split("&"));
                authRule.addOrRule(rule);
            }
            return authRule;
        }
        AuthRule rule = new AuthRule(AuthRule.TYPE_AUTHORITY);
        rule.auths = Arrays.asList(authAttr.split("&"));
        return rule;
    }

    private void addOrRule(AuthRule rule) {
        if (orRules == null) {
            orRules = new ArrayList<>(1);
        }
        orRules.add(rule);
    }

    public boolean isPermitAll() {
        return isPermit(Collections.emptyList());
    }

    public boolean isPermit(List authorities) {
        if (type == TYPE_AUTHORITY) {
            for (String auth: auths) {
                if (AuthConst.PERMIT_ALL.equals(auth)) {
                    continue;
                }
                if (!authorities.contains(auth)) {
                    return false;
                }
            }
            return true;
        }
        if (type == TYPE_OR_GROUP) {
            for (AuthRule rule: orRules) {
                if (rule.isPermit(authorities)) {
                    return true;
                }
            }
            return false;
        }
        return false;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy