UserAuthLocal.java 7.79 KB
package com.ui.User;

import com.ui.contants.HttpUriContants;
import com.ui.http.HttpRestClient;
import com.ui.model.BaseResponse;
import com.ui.model.req.AuthModule;
import com.ui.model.req.User;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by zhengyouwei on 2016/7/13.
 * 鉴权
 */
@Component
@EnableAsync
public class UserAuthLocal {
    Logger log = LoggerFactory.getLogger(UserAuthLocal.class);

    private static ConcurrentHashMap<String, User> usermap = new ConcurrentHashMap<>();

    private static ConcurrentHashMap<String, AuthModule> modulemap = new ConcurrentHashMap<>();

    private static ConcurrentHashMap<String, Set<String>> moduleGroupmap = new ConcurrentHashMap<>();


    @Autowired
    HttpRestClient httpRestClient;

    //@PostConstruct
    public synchronized void init() {
        try{
            //加载用户信息
            BaseResponse<List<User>> response = httpRestClient.exchangeForget(HttpUriContants.GET_All_USER, new ParameterizedTypeReference<BaseResponse<List<User>>>() {
            }, null);
            List<User> userlist = response.getData();
            for (User user : userlist) {
                usermap.put(user.getName(), user);
            }

            //加载mudule信息
            BaseResponse<List<AuthModule>> moduleResponse = httpRestClient.exchangeForget(HttpUriContants.GET_All_MODULE, new ParameterizedTypeReference<BaseResponse<List<AuthModule>>>() {
            }, null);
            List<AuthModule> modulelist = moduleResponse.getData();
            for (AuthModule module : modulelist) {
                modulemap.put(module.getModuleName(), module);
            }

            //加载module组信息
            for (Map.Entry<String,AuthModule> entry : modulemap.entrySet()){
                AuthModule authModule = entry.getValue();
                String group = authModule.getModuleGroup();
                if (StringUtils.isNotBlank(group)){
                    if (moduleGroupmap.containsKey(group)){
                        moduleGroupmap.get(group).add(entry.getKey());
                    }else {
                        Set<String> groupSet = new HashSet<>();
                        groupSet.add(entry.getKey());
                        moduleGroupmap.put(group,groupSet);
                    }
                }
            }
        }catch (Exception e){
            log.error(" - UserAuthLocal - init - error", e);
        }
    }

    /**
     * jian quan
     *
     * @param user
     * @param module
     * @return
     */
    public boolean auth(String user, String module) {
        if (usermap.isEmpty()) {//改用延时加载
            init();
        }
        User u = usermap.get(user);
        if (u == null) {
            return false;
        }
        AuthModule authModule = modulemap.get(module);
        if (authModule == null) {
            return false;
        }
        //最高权限
        if (StringUtils.isNotBlank(u.getModuleGroups())) {
            String[] moduleGroupArray = u.getModuleGroups().split(",");
            for (String groupName : moduleGroupArray) {
                if ("all".equals(groupName)) {
                    return true;
                }
            }
        }
        //先查找group
        String moduleGroup = authModule.getModuleGroup();
        if (moduleGroup != null && StringUtils.isNotBlank(u.getModuleGroups())) {
            String[] moduleGroupArray = u.getModuleGroups().split(",");
            for (String groupName : moduleGroupArray) {
                if (moduleGroup.equals(groupName)) {
                    return true;
                }
            }
        }

        //在查找单一类
        if (StringUtils.isNotBlank(u.getModules())) {
            String[] modulesArray = u.getModules().split(",");
            for (String moduleName : modulesArray) {
                if (module.equals(moduleName)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 获取用户
     *
     * @param name
     * @return
     */
    public User getUserByname(String name) {
        if (usermap.isEmpty()) {//改用延时加载
            init();
        }
        return usermap.get(name);
    }

    /**
     * 获取用户
     *
     * @param name
     * @return
     */
    public User getUserByLdapName(String name) {
        if (usermap.isEmpty()) {//改用延时加载
            init();
        }
        for(String key:usermap.keySet()){
            User u=usermap.get(key);
            if(name.equals(u.getLadpName())){
                return  u;
            }
        }
        return null;
    }

    public AuthModule getAuthModuleByname(String name) {
        if (modulemap.isEmpty()) {//改用延时加载
            init();
        }
        return modulemap.get(name);
    }

    /**
     * 获取用户所有的权限
     *
     * @param name
     * @return
     */
    public Set<String> getAllModuleByname(String name) {

        Set<String> set = new HashSet<>();
        if (usermap.isEmpty()) {//改用延时加载
            init();
        }
        User u = usermap.get(name);
        String groups = u.getModuleGroups();
        if (StringUtils.isNotBlank(groups)){//添加组
            for (String group : groups.split(",")) {
                if ("all".equals(group)){
                    set.addAll(modulemap.keySet());
                    return set;
                }
                set.addAll(moduleGroupmap.get(group));
            }
        }
        //添加但模块
        String modules = u.getModules();
        if (StringUtils.isNotBlank(modules)){//添加组
            for (String module : modules.split(",")) {
                set.add(module);
            }
        }
        return set;
    }

    /**
     * 更新用户信息
     *
     * @param name
     */
    @Async
    public void flushUser(String name) {
        Map<String, String> map = new HashMap<>();
        map.put("name", name);
        BaseResponse<User> response = httpRestClient.exchangeForget(HttpUriContants.GET_USER_BY_NAME, new ParameterizedTypeReference<BaseResponse<User>>() {
        }, map);
        User user = response.getData();
        if (user == null) {
            usermap.remove(name);
        } else {
            usermap.put(name, user);
        }
    }

    /**
     * 更新用户信息
     *
     * @param name
     */
    @Async
    public void flushModule(String name) {
        Map<String, String> map = new HashMap<>();
        map.put("name", name);
        AuthModule oldAuthModule = modulemap.get(name);
        BaseResponse<AuthModule> response = httpRestClient.exchangeForget(HttpUriContants.MODULE_GET_BYNAME, new ParameterizedTypeReference<BaseResponse<AuthModule>>() {
        }, map);
        AuthModule authModule = response.getData();
        if (authModule == null) {
            modulemap.remove(name);
            //删除组里的模块
            String group = oldAuthModule.getModuleGroup();
            if (moduleGroupmap.containsKey(group)) {
                moduleGroupmap.get(group).remove(name);
            }
        } else {
            modulemap.put(name, authModule);
            if (moduleGroupmap.containsKey(authModule.getModuleGroup())){
                moduleGroupmap.get(authModule.getModuleGroup()).add(name);
            }else {
                Set<String> groupSet = new HashSet<>();
                groupSet.add(name);
                moduleGroupmap.put(authModule.getModuleGroup(),groupSet);
            }
        }
    }

}