JAVA 自定义注解应用

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthRequired {
    String[] authMask() default {"empty"};

    MatchRule rule() default MatchRule.ANY;
}

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {
    boolean required() default true;
}
public enum MatchRule {
    ANY(0),
    BOTH(1);

    private int value;

    private MatchRule(int value) {
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }

    public static MatchRule fromValue(int value) {
        MatchRule[] var1 = values();
        int var2 = var1.length;

        for(int var3 = 0; var3 < var2; ++var3) {
            MatchRule rule = var1[var3];
            if(rule.getValue() == value) {
                return rule;
            }
        }

        return null;
    }
}


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 *
 */
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface RoleRequired {

    Role[] role() default Role.ADMIN;
}
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
public enum Role {
    SUPER_ADMIN(0, "超级管理员"),
    ADMIN(1, "普通管理员"),
    SUPPLIER(2, "供应商"),
    STATIONMASTER(3, "机构站长"),
    ;

    Role(int id, String title) {
        this.id = id;
        this.title = title;
    }

    int id;

    String title;

    public int getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public static final Map<Integer, Role> map = new HashMap<>();
    static {
        for (Role role : Role.values()) {
            map.put(role.getId(), role);
        }
    }

    public static Role getRole(int id) {
        return map.get(id);
    }
}



import org.apache.commons.collections.CollectionUtils;

import java.util.List;
import java.util.Set;

/**
 * 
 */
public final class AuthMatchUtils {

    private static Set<String> userMasks;

    private static List<String> requiredMasks;

    private AuthMatchUtils() {
    }

    public final static boolean any(Set<String> userMasks, Set<String> requiredMasks) {
        if (CollectionUtils.isEmpty(requiredMasks)) {
            return true;
        }
        if (CollectionUtils.isEmpty(userMasks)) {
            return false;
        }
        if (userMasks.contains(AuthMask.AUTH_MASK_ALL)) {
            return true;
        }
        for (String item : requiredMasks) {
            if (AuthMask.AUTH_MASK_ALL.equalsIgnoreCase(item) || userMasks.contains(item))
                return true;
        }
        return false;
    }

    public final static boolean any(Set<String> userMasks, List<String> requiredMasks) {
        if (requiredMasks == null || requiredMasks.size() <= 0) {
            return true;
        }
        if (CollectionUtils.isEmpty(userMasks)) {
            return false;
        }
        if (userMasks.contains(AuthMask.AUTH_MASK_ALL)) {
            return true;
        }
        for (String item : requiredMasks) {
            if (AuthMask.AUTH_MASK_ALL.equalsIgnoreCase(item) || userMasks.contains(item))
                return true;
        }
        return false;
    }

    public final static boolean both(Set<String> userMasks, Set<String> requiredMasks) {
        if (CollectionUtils.isEmpty(requiredMasks)) {
            return true;
        }
        if (CollectionUtils.isEmpty(userMasks)) {
            return false;
        }
        if (userMasks.contains(AuthMask.AUTH_MASK_ALL)) {
            return true;
        }
        for (String item : requiredMasks) {
            if (!AuthMask.AUTH_MASK_ALL.equalsIgnoreCase(item) && !userMasks.contains(item))
                return false;
        }
        return true;
    }

    public final static boolean both(Set<String> userMasks, List<String> requiredMasks) {
        if (requiredMasks == null || requiredMasks.size() <= 0) {
            return true;
        }
        if (CollectionUtils.isEmpty(userMasks)) {
            return false;
        }
        if (userMasks.contains(AuthMask.AUTH_MASK_ALL)) {
            return true;
        }
        for (String item : requiredMasks) {
            if (!AuthMask.AUTH_MASK_ALL.equalsIgnoreCase(item) && !userMasks.contains(item))
                return false;
        }
        return true;
    }

    public final static boolean match(Set<String> userMasks, Set<String> requiredMasks, MatchRule rule) {
        if (MatchRule.ANY == rule || null == rule) {
            return any(userMasks, requiredMasks);
        }
        return both(userMasks, requiredMasks);
    }

    public final static boolean match(Set<String> userMasks, List<String> requiredMasks, MatchRule rule) {
        if (MatchRule.ANY == rule || null == rule) {
            return any(userMasks, requiredMasks);
        }
        return both(userMasks, requiredMasks);
    }
}


import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class AuthMaskInterceptor extends HandlerInterceptorAdapter implements InitializingBean {

    private final static String DEFAULT_CALLBACK_PARAM = "callback";

    private IAuthService authService;

    private String authRequiredResponse;

    /* (non-Javadoc)
     * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        if (!(handler instanceof HandlerMethod)) {
            throw new IllegalArgumentException("LoginInterceptor only support HanlderMethod handler");
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;

        /**
         * 登陆账号验证
         */
        AuthRequired anno = null;
        if (handlerMethod.getMethod().isAnnotationPresent(AuthRequired.class)) {
            anno = handlerMethod.getMethod().getAnnotation(AuthRequired.class);
        } else if (handlerMethod.getBeanType().isAnnotationPresent(AuthRequired.class)) {
            anno = handlerMethod.getBeanType().getAnnotation(AuthRequired.class);
        }
        if (null == anno) {
            return true;
        }

        //验证权限
        String[] arr = anno.authMask();
        MatchRule rule = anno.rule();
        if (arr == null || arr.length <= 0) {
            return true;
        }
        Set<String> requiredMaskSet = new HashSet<>(Arrays.asList(arr));
        Set<String> userMaskSet = null;

        //登录用户
        User user = (User) request.getAttribute(FrontConstant.LOGIN_USER_PARAM);
        if (user != null) {
            userMaskSet = authService.getUserAuthSet(user.getUser_id());
            user.setAuthMaskSet(userMaskSet);
        } else {
            userMaskSet = Collections.emptySet();
        }

        //通过权限验证
        if (AuthMatchUtils.match(userMaskSet, requiredMaskSet, rule)) {
            return true;
        }

        //权限验证失败
        if ("GET".equals(request.getMethod().toUpperCase()) ) {
            String callback = request.getParameter(DEFAULT_CALLBACK_PARAM);
            if (StringUtils.isBlank(callback)) {
                response.getWriter().print(authRequiredResponse);
            } else {
                response.getWriter().print(callback + "(" + authRequiredResponse + ");");
            }
        } else if(isAsyncRequest(request)){
            String callback = request.getParameter(DEFAULT_CALLBACK_PARAM);
            if (StringUtils.isBlank(callback)) {
                response.getWriter().print(authRequiredResponse);
            } else {
                response.getWriter().print(callback + "(" + authRequiredResponse + ");");
            }
        }
        return false;
    }

    private boolean isAsyncRequest(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        return header != null && "XMLHttpRequest".equalsIgnoreCase(header);
    }

    /* (non-Javadoc)
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(authService, "authService must not be null!");
        authRequiredResponse = JsonUtils.objectToJsonString(new ApiResult(ErrorCode.EC_NO_PERMISSION, //NL
                "无操作权限,请联系管理员开通权限"));
    }

    public void setAuthService(IAuthService authService) {
        this.authService = authService;
    }
}
@AuthRequired(authMask = { "financial_member_realtime_settle_detail",
            "financial_member_realtime_settle_detail_search_btn" })
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值