文件夹目录权限实现方法总结(附代码)

       文件夹权限分为可读、可写、管理、没有权限四种。有管理权限则有可读、可写权限。设置了没有权限,则不能设置可读、可写、管理权限。如果不设置没有权限,默认文件夹有可读权限。

       权限设置,只能一级一级往下设置,不能从下往上设置。设置中,不允许出现冲突情况(上级目录没有权限,下级目录有权限)。

       权限是继承的,子目录自动拥有父级目录的权限。

       本目录设置权限前,查询所有下级目录是否设置过权限,如果设置过,则不允许设置权限。

情形一:目录B角色甲有权限,其他角色没设置过权限。那么下级目录就不允许再设置任何权限,即不允许再给甲设置下级目录没有权限。如果下级某个目录设置甲没有权限那么所有人都看不了该目录,没有意义。

情形二:目录B设置了甲乙丙三个角色有权限,子目录B1可以设置甲没有权限,可以设置目录B2乙没有权限,那么B2目录的下级目录就不能设置乙有权限。

情形三:目录B丙没有权限,甲乙有权限。下级目录B1可以设置甲乙没有权限,所有下级目录都不能设置丙有权限。

实现:

一、文件目录表结构设计: 

文件夹目录信息表: 

CREATE TABLE `disk_file` (
  `id` varchar(50) NOT NULL,
  `createtime` datetime DEFAULT NULL,
  `createuserid` varchar(50) DEFAULT NULL,
  `createusername` varchar(50) DEFAULT NULL,
  `filemd5` varchar(200) DEFAULT NULL,
  `filename` varchar(255) DEFAULT NULL,
  `filesize` bigint(20) NOT NULL,
  `filesuffix` varchar(20) DEFAULT NULL,
  `filetype` int(11) DEFAULT NULL,
  `imgsize` varchar(50) DEFAULT NULL,
  `pid` varchar(50) DEFAULT NULL,
  `thumbnailurl` varchar(200) DEFAULT NULL,
  `typecode` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `UKfjg8ov86e52cc1vw2g4cahpu7` (`createuserid`,`pid`,`filetype`,`filename`),
  KEY `IDX7h8ca5qp48qow851woryvg8q` (`pid`),
  KEY `IDX9j6hnchh4o79nofxhjgy0lc29` (`filename`),
  KEY `IDXlhtq88mi2kvwxihin21rvvm9b` (`typecode`),
  KEY `IDXb244b04v1wu3ftqfqjt7wodks` (`filesuffix`),
  KEY `IDXq0mhp53s6a40gh5w93bqmx5jp` (`filetype`),
  KEY `IDXc7snngp84h66d6f64u0l0hb56` (`createuserid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

文件夹权限数据表: 

CREATE TABLE `disk_file_folder_privilege` (
  `id` varchar(32) NOT NULL COMMENT '主键',
  `user_id` varchar(32) DEFAULT NULL COMMENT '用户id',
  `role_id` varchar(32) DEFAULT NULL,
  `present_catalog` varchar(32) DEFAULT NULL COMMENT '当前文件夹目录',
  `whole_catalog` varchar(512) DEFAULT NULL COMMENT '完整文件夹目录',
  `readable` char(1) DEFAULT NULL COMMENT '可读:1',
  `writable` char(1) DEFAULT NULL COMMENT '可写:1',
  `manage` char(1) DEFAULT NULL COMMENT '管理:1',
  `no_auth` char(1) DEFAULT NULL COMMENT '没有权限',
  `create_time` varchar(32) DEFAULT NULL,
  `update_time` varchar(32) DEFAULT NULL,
  `creater` varchar(32) DEFAULT NULL,
  `updater` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='文件夹权限';

二、保存文件夹目录权限

import cn.datainvest.common.page.Page;
import cn.datainvest.common.utils.lang.DateTimeUtil;
import cn.datainvest.core.constant.Constant;
import cn.datainvest.core.mapper.BaseGeneratedMapper;
import cn.datainvest.core.result.ServiceResult;
import cn.datainvest.core.result.ServiceResultHelper;
import cn.datainvest.core.service.AbstractBaseAOService;
import cn.datainvest.dms.system.auth.AuthUtil;
import cn.datainvest.dms.system.dao.customized.DiskFileFolderPrivilegeCustomizedMapper;
import cn.datainvest.dms.system.dao.gen.DiskFileFolderPrivilegeGeneratedMapper;
import cn.datainvest.dms.system.dto.request.DiskFileFolderPrivilegeForm;
import cn.datainvest.dms.system.dto.request.DiskFileFolderPrivilegeRequest;
import cn.datainvest.dms.system.entity.customized.DiskFileAO;
import cn.datainvest.dms.system.entity.customized.DiskFileFolderPrivilegeAO;
import cn.datainvest.dms.system.entity.customized.UserAO;
import cn.datainvest.dms.system.entity.gen.DiskFileFolderPrivilegeCriteria;
import cn.datainvest.dms.system.service.IDiskFileFolderPrivilegeService;
import cn.datainvest.dms.system.service.IDiskFileService;
import cn.datainvest.dms.system.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

@Service
public class DiskFileFolderPrivilegeService extends AbstractBaseAOService<DiskFileFolderPrivilegeAO, DiskFileFolderPrivilegeCriteria> implements IDiskFileFolderPrivilegeService {

    @Resource
    private IDiskFileService diskFileService;

    @Resource
    private IRoleService roleService;

    @Resource
    private DiskFileFolderPrivilegeGeneratedMapper diskFileFolderPrivilegeGeneratedMapper;

    @Resource
    private DiskFileFolderPrivilegeCustomizedMapper diskFileFolderPrivilegeCustomizedMapper;

    @Override
    protected BaseGeneratedMapper<DiskFileFolderPrivilegeAO, DiskFileFolderPrivilegeCriteria> getGeneratedMapper() {
        return diskFileFolderPrivilegeGeneratedMapper;
    }

    @Override
    public ServiceResult<List<DiskFileFolderPrivilegeAO>> list(DiskFileFolderPrivilegeRequest request) {
        ServiceResult<List<DiskFileFolderPrivilegeAO>> ret = new ServiceResult<>();
        PageHelper.startPage(request.getPageNo(), request.getPageSize());
        List<DiskFileFolderPrivilegeAO> privilegeAOList = diskFileFolderPrivilegeCustomizedMapper.listByCondition(request);
        ret.setData(privilegeAOList);
        ret.setSucceed(true);
        ret.setAdditionalProperties("page", Page.obtainPage(new PageInfo<>(privilegeAOList)));
        return ret;
    }


    /**
     * 保存文件夹目录权限
     *
     * @param form
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServiceResult<Boolean> save(DiskFileFolderPrivilegeForm form) {
        List<String> roleIds = Arrays.asList(form.getRoleIds());
        if (CollectionUtils.isEmpty(roleIds)) {
            return ServiceResultHelper.genResultWithFaild("角色不能为空", -1);
        }
        if (StringUtils.isEmpty(form.getFileId())) {
            return ServiceResultHelper.genResultWithFaild("请选择文件夹目录", -1);
        }
        DiskFileAO diskFile = diskFileService.selectByPrimaryKey(form.getFileId()).getData();
        if (diskFile == null) {
            return ServiceResultHelper.genResultWithFaild("文件夹目录不存在", -1);
        }
        if (!Constant.INVALID_FLG.equals(diskFile.getFiletype())) {
            return ServiceResultHelper.genResultWithFaild("请选择文件夹目录", -1);
        }
        if (StringUtils.isEmpty(form.getReadable())
                && StringUtils.isEmpty(form.getWritable())
                && StringUtils.isEmpty(form.getManage())
                && StringUtils.isEmpty(form.getNoAuth())) {
            return ServiceResultHelper.genResultWithFaild("请设置文件夹目录权限", -1);
        }
        UserAO user = AuthUtil.getCurrentUser();
        //1.判断是否是设置父级目录权限:子级文件夹目录已经设置过权限则不允许设置
        List<DiskFileAO> childList = diskFileService.listChildNodes(null, form.getFileId());
        if (!CollectionUtils.isEmpty(childList)) {
            for (DiskFileAO file : childList) {
                List<DiskFileFolderPrivilegeAO> privilegeList = listPrivilegeIn(file.getId(), roleIds).getData();
                if (!CollectionUtils.isEmpty(privilegeList)) {
                    return ServiceResultHelper.genResultWithFaild("子级文件夹目录已经设置过权限", -1);
                }
            }
        }
        //2.查询其他角色是否设置过父级权限
        //获取直接父级
        DiskFileAO parent = diskFileService.getParentByChildId(form.getFileId()).getData();
        if (parent != null) {
            boolean hasPrivilege = hasPrivilegeIn(parent.getId(), roleIds);
            // 查询其他角色是否设置过父级目录的权限
            boolean hasPrivilegeOtherRoles = hasPrivilegeOtherRoles(parent.getId(), roleIds);
            //查询所有父级
            List<String> allParent = diskFileService.getAllParent(parent.getId());
            boolean isExist = existParent(allParent, roleIds);
            //如果父级目录配置过权限
            if (isExist) {
                //并且被配为没有权限,那么子级目录不能配置为有读/写/管理权限
                if (!hasPrivilege && StringUtils.isEmpty(form.getNoAuth())) {
                    return ServiceResultHelper.genResultWithFaild("父级文件夹目录没有权限,该文件夹目录不能配置读/写/管理权限", -1);
                }
                //其他角色没有设置过父级目录权限,并且父级为有权限,下级目录不允许再设置任何权限
                if (hasPrivilege && !hasPrivilegeOtherRoles) {
                    return ServiceResultHelper.genResultWithFaild("不允许设置该文件夹目录权限", -1);
                }
            }
        }
        List<DiskFileFolderPrivilegeAO> result = new ArrayList<>();
        for (String roleId : roleIds) {
            DiskFileFolderPrivilegeAO tmp = new DiskFileFolderPrivilegeAO();
            tmp.setRoleId(roleId);
            tmp.setCreater(user.getUserName());
            tmp.setCreateTime(DateTimeUtil.formatDateTime(new Date()));
            tmp.setPresentCatalog(form.getFileId());//当前文件夹目录
            tmp.setNoAuth(form.getNoAuth());
            if (StringUtils.isEmpty(form.getNoAuth())) {
                tmp.setReadable(Constant.VALID_FLG.toString());
            }
            //设置所选文件夹的可写,管理权限
            if (Constant.VALID_FLG.toString().equals(form.getWritable())) {
                tmp.setWritable(form.getWritable());
            }
            if (Constant.VALID_FLG.toString().equals(form.getManage())) {
                tmp.setWritable(Constant.VALID_FLG.toString());
                tmp.setManage(form.getManage());
            }
            result.add(tmp);
        }
        //先删除之前设置的权限
        deleteByFolderCatalog(form.getFileId(), roleIds);
        //编辑时删除原始数据
        if (!StringUtils.isEmpty(form.getFolderPrivilegeId())) {
            deleteById(form.getFolderPrivilegeId());
        }
        if (!CollectionUtils.isEmpty(result)) {
            insertBatch(result);
        }
        return ServiceResultHelper.genResultWithSuccess();
    }


    /**
     * 删除已存在的权限,需要比较权限的大小
     * 子级目录不覆盖父级目录的权限
     *
     * @param fileId
     * @return
     */
    public ServiceResult deleteByFolderCatalog(String fileId, List<String> roleIds) {
        DiskFileFolderPrivilegeCriteria criteria = new DiskFileFolderPrivilegeCriteria();
        DiskFileFolderPrivilegeCriteria.Criteria c = criteria.createCriteria();
        if (StringUtils.isEmpty(fileId)) {
            return ServiceResultHelper.genResultWithFaild("文件夹目录不能为空", -1);
        }

        c.andRoleIdIn(roleIds);
        c.andPresentCatalogEqualTo(fileId);
        return deleteByCriteria(criteria);
    }


    /**
     * 查询其他角色是否设置过父级目录的权限
     *
     * @param fileId
     * @param roleIds
     * @return
     */
    public boolean hasPrivilegeOtherRoles(String fileId, List<String> roleIds) {
        DiskFileFolderPrivilegeCriteria criteria = new DiskFileFolderPrivilegeCriteria();
        criteria.createCriteria().andPresentCatalogEqualTo(fileId).andRoleIdNotIn(roleIds)
                .andNoAuthIsNull();
        List<DiskFileFolderPrivilegeAO> data = selectByCriteria(criteria).getData();
        if (!CollectionUtils.isEmpty(data)) {
            return true;
        }
        return false;
    }


    public ServiceResult<List<DiskFileFolderPrivilegeAO>> listPrivilegeIn(String fileId,
                                                                          List<String> roleIds) {
        DiskFileFolderPrivilegeCriteria criteria = new DiskFileFolderPrivilegeCriteria();
        criteria.createCriteria().andPresentCatalogEqualTo(fileId).andRoleIdIn(roleIds);
        return selectByCriteria(criteria);
    }


    /**
     * 查询没有权限的数据
     *
     * @param roleIds
     * @return
     */
    @Override
    public ServiceResult<List<DiskFileFolderPrivilegeAO>> listNoPrivileges(List<String> roleIds) {
        return ServiceResultHelper.genResultWithSuccess(diskFileFolderPrivilegeCustomizedMapper.listNoPrivileges(roleIds));
    }


    /**
     * 目录是否有权限
     *
     * @param fileId
     * @param roleIds
     * @return
     */
    public boolean hasPrivilegeIn(String fileId, List<String> roleIds) {
        DiskFileFolderPrivilegeCriteria criteria = new DiskFileFolderPrivilegeCriteria();
        criteria.createCriteria().andPresentCatalogEqualTo(fileId).andRoleIdIn(roleIds)
                .andNoAuthIsNull();
        List<DiskFileFolderPrivilegeAO> list = selectByCriteria(criteria).getData();
        if (!CollectionUtils.isEmpty(list)) {
            return true;
        }
        return false;
    }


    /**
     * 获取目录权限列表
     *
     * @param fileId
     * @param roleIds
     * @return
     */
    @Override
    public ServiceResult<List<DiskFileFolderPrivilegeAO>> listPrivileges(String fileId, List<String> roleIds) {
        DiskFileFolderPrivilegeCriteria criteria = new DiskFileFolderPrivilegeCriteria();
        criteria.createCriteria().andPresentCatalogEqualTo(fileId).andRoleIdIn(roleIds);
        return selectByCriteria(criteria);
    }


    /***
     * 是否存在父级目录
     *
     * @param fileIds
     * @param roleIds
     * @return
     */
    public boolean existParent(List<String> fileIds, List<String> roleIds) {
        if (CollectionUtils.isEmpty(fileIds)) {
            return false;
        }
        DiskFileFolderPrivilegeCriteria criteria = new DiskFileFolderPrivilegeCriteria();
        criteria.createCriteria().andPresentCatalogIn(fileIds).andRoleIdIn(roleIds);
        List<DiskFileFolderPrivilegeAO> list = selectByCriteria(criteria).getData();
        if (!CollectionUtils.isEmpty(list)) {
            return true;
        }
        return false;
    }


    /**
     * 根据角色集合查询文件夹目录权限
     */
    @Override
    public ServiceResult<List<DiskFileFolderPrivilegeAO>> listByRoleId(List<String> roleIds) {
        return ServiceResultHelper.genResultWithSuccess(diskFileFolderPrivilegeCustomizedMapper.listByRoleId(roleIds));
    }


    /**
     * 查询文件夹目录权限
     */
    @Override
    public ServiceResult<List<DiskFileFolderPrivilegeAO>> listByUserId(String userId) {
        DiskFileFolderPrivilegeCriteria criteria = new DiskFileFolderPrivilegeCriteria();
        criteria.createCriteria().andUserIdEqualTo(userId);
        return selectByCriteria(criteria);
    }

    @Override
    public int insertBatch(List<DiskFileFolderPrivilegeAO> privilegeAOList) {
        return diskFileFolderPrivilegeCustomizedMapper.insertBatch(privilegeAOList);
    }


    /**
     * 查询目录
     *
     * @param fileId
     * @return
     */
    @Override
    public ServiceResult<List<DiskFileFolderPrivilegeAO>> listRoleFilePrivileges(String fileId,
                                                                                 List<String> roleIds) {
        DiskFileFolderPrivilegeCriteria criteria = new DiskFileFolderPrivilegeCriteria();
        criteria.createCriteria().andPresentCatalogEqualTo(fileId).andRoleIdIn(roleIds);
        return selectByCriteria(criteria);
    }


    /**
     * 获取文件夹的权限数据
     *
     * @param pid
     * @param roleIds
     * @return
     */
    @Override
    public ServiceResult<List<DiskFileFolderPrivilegeAO>> listFolderPrivileges(String pid, List<String> roleIds) {
        List<DiskFileFolderPrivilegeAO> privilegeList = null;
        List<DiskFileFolderPrivilegeAO> data = listPrivileges(pid, roleIds).getData();
        if (!CollectionUtils.isEmpty(data)) {
            privilegeList = data;
        } else {
            //查询所有父级
            List<String> allParentFileIds = diskFileService.getAllParent(pid);
            Collections.reverse(allParentFileIds);
            if (!CollectionUtils.isEmpty(allParentFileIds)) {
                for (String parentId : allParentFileIds) {
                    privilegeList = listRoleFilePrivileges(parentId, roleIds).getData();
                    if (!CollectionUtils.isEmpty(privilegeList)) {
                        break;
                    }
                }
            }
        }
        return ServiceResultHelper.genResultWithSuccess(privilegeList);
    }


    /**
     * 根据文件夹id获取权限
     *
     * @param fileId
     * @return
     */
    @Override
    public ServiceResult<DiskFileFolderPrivilegeAO> getFolderPrivilegeByFileId(String fileId) {
        UserAO user = AuthUtil.getCurrentUser();
        DiskFileFolderPrivilegeAO result = new DiskFileFolderPrivilegeAO();
        if (user.isSuperAdmin()) {
            result.setPresentCatalog(fileId);
            result.setReadable("1");
            result.setWritable("1");
            result.setManage("1");
        } else {
            List<String> roleIds = roleService.getRoleIdsByUserId(user.getId()).getData();
            boolean readable = false;
            boolean writeable = false;
            boolean manage = false;
            boolean noAuth = false;
            if (CollectionUtils.isEmpty(roleIds)) {
                return ServiceResultHelper.genResultWithFaild("没有查询到用户的角色信息", -1);
            }
            List<DiskFileFolderPrivilegeAO> privilegeList = listFolderPrivileges(fileId, roleIds).getData();
            if (!CollectionUtils.isEmpty(privilegeList)) {
                for (DiskFileFolderPrivilegeAO privilege : privilegeList) {
                    if (!readable) {
                        if (!StringUtils.isEmpty(privilege.getReadable())) {
                            readable = true;
                        }
                    }
                    if (!writeable) {
                        if (!StringUtils.isEmpty(privilege.getWritable())) {
                            writeable = true;
                        }
                    }
                    if (!manage) {
                        if (!StringUtils.isEmpty(privilege.getManage())) {
                            manage = true;
                        }
                    }
                    if (!noAuth) {
                        if (!StringUtils.isEmpty(privilege.getNoAuth())) {
                            noAuth = true;
                        }
                    }
                }
                result.setPresentCatalog(fileId);
                result.setReadable(readable ? "1" : null);
                result.setWritable(writeable ? "1" : null);
                result.setManage(manage ? "1" : null);
                result.setNoAuth(noAuth ? "1" : null);
            } else {
                return ServiceResultHelper.genResultWithSuccess();
            }
        }
        return ServiceResultHelper.genResultWithSuccess(result);
    }
}

DiskFileService:


    /**
     * 根据子级查询父级
     *
     * @param childId 子id
     * @return
     */
    @Override
    public ServiceResult<DiskFileAO> getParentByChildId(String childId) {
        DiskFileAO file = selectByPrimaryKey(childId).getData();
        if (file != null) {
            return selectByPrimaryKey(file.getPid());
        }
        return ServiceResultHelper.genResultWithFaild();
    }



   /**
     * 获取所有父级
     *
     * @param fileId
     * @return
     */
    @Override
    public List<String> getAllParent(String fileId) {
        List<DiskFileAO> fileList = selectByCriteria(null).getData();
        List<DiskFileAO> parentList = new ArrayList<>();

        if (!CollectionUtils.isEmpty(fileList)) {
            //查询所有父级
            getAllParentListWithChild(fileList, fileId, fileId, parentList);
        }

        List<String> parentFileIds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(parentList)) {
            parentList.stream().forEach(o -> parentFileIds.add(o.getId()));
        }
        return parentFileIds;
    }

    /**
     * 根据子级查询所有父级
     *
     * @param allList    所有文件
     * @param childId    子级id
     * @param parentList 最终返回的子级+所有父级的集合
     * @return
     */
    @Override
    public List<DiskFileAO> getAllParentListWithChild(List<DiskFileAO> allList, String childId,
                                                      String notContain, List<DiskFileAO> parentList) {
        if (!CollectionUtils.isEmpty(allList)) {
            for (DiskFileAO resource : allList) {
                // 判断是否存在父节点
                if (resource.getId().equals(childId)) {
                    // 递归遍历上一级
                    getAllParentListWithChild(allList, resource.getPid(), notContain, parentList);
                    if (!parentList.contains(resource) && !resource.getId().equals(notContain)) {
                        parentList.add(resource);
                    }
                }
            }
            return parentList;
        }
        return null;
    }


    @Override
    public List<DiskFileAO> listChildNodes(DiskFileRequest request, String pid) {
        List<DiskFileAO> fileList = listByCondition(request);
        List<DiskFileAO> childNodes = new ArrayList<>();
        if (!CollectionUtils.isEmpty(fileList)) {
            DiskFileAO parent = null;
            for (DiskFileAO file : fileList) {
                if (file.getId().equals(pid)) {
                    parent = file;
                    break;
                }
            }
            //递归获取所有子节点
            if (parent != null) {
                getAllChildNodes(parent, fileList, childNodes);
            }
        }
        return childNodes;
    }


    /**
     * 获取某个父节点下面的所有子节点
     *
     * @return
     */
    public static <T extends BaseTreeAO> List<T> getAllChildNodes(T parentNode, List<T> list, List<T> childNodes) {
        for (T node : list) {
            //遍历出父id等于参数的id,add进子节点集合
            if (StringUtils.isNotEmpty(node.getPid()) && node.getPid().equals(parentNode.getId())) {
                //递归遍历下一级
                getAllChildNodes(node, list, childNodes);
                childNodes.add(node);
            }
        }
        return childNodes;
    }

三、根据权限取出文件夹目录

 @Override
    public ServiceResult<List<DiskFileAO>> findPageList(DiskFileRequest request) {
        List<DiskFileAO> fileList = listByParentId(request.getPid(), request.isContainFolder()).getData();
        List<RoleAO> roles = roleService.getRolesByUserName(AuthUtil.getCurrentUser().getUserName()).getData();
        List<String> roleIds = new ArrayList<>();
        List<String> fileIds = new ArrayList<>();
        roles.stream().forEach(o -> roleIds.add(o.getId()));
        fileList.stream().forEach(o -> fileIds.add(o.getId()));
        request.setRoleIds(roleIds);
        request.setFileIds(fileIds);
        ServiceResult<List<DiskFileAO>> ret = new ServiceResult<>();
        PageHelper.startPage(request.getPageNo(), request.getPageSize());
        StringBuilder orderBy=new StringBuilder();
        //order by 排序处理,防止sql注入
        if(!StringUtils.isEmpty(request.getOrderfield())){
            orderBy.append(request.getOrderfield()).append(" ").append(request.getOrdertype());
        }else{
            orderBy.append("createtime").append(" ").append("desc");
        }
        PageHelper.orderBy(orderBy.toString());
        List<DiskFileAO> fileListBeanList = diskFileCustomizedMapper.findAllList(request);
        ret.setData(fileListBeanList);
        ret.setSucceed(true);
        ret.setAdditionalProperties("page", Page.obtainPage(new PageInfo<>(fileListBeanList)));
        return ret;
    }

mybatis sql配置:

 <select id="findAllList"  resultMap="CustomResultMap"
          parameterType="cn.datainvest.dms.system.dto.request.DiskFileRequest">
      SELECT
              t2.id,
              t2.filename,
              t2.filesize,
              t2.filetype,
              t2.filemd5,
              t2.filesuffix,
              t2.createtime,
              t2.pid,
              t2.typecode,
              t2.regulation_title,
              t2.regulation_publish_time,
              t2.regulation_impl_time, t2.regulation_issue_1, t2.regulation_issue_2, t2.regulation_issue_3,
              t2.regulation_classify, t2.regulation_file_type, t2.regulation_type, t2.regulation_number, t2.regulation_input_time,
              t2.regulation_status, t2.regulation_remark,
              dts.icon AS fileicon
      FROM
      (
        <choose>
              <when test="isSuperAdmin != null and isSuperAdmin != '' and isSuperAdmin == 'false'">
                  SELECT
                        *
                  FROM
                        disk_file
                  <where>
                      <include refid="fileScopeWhere" />
                      AND id NOT IN
                        (
                          SELECT
                                present_catalog
                          FROM
                                `disk_file_folder_privilege`
                          <where>
                              <if test="roleIds != null and roleIds.size()>0 ">
                                  AND role_id in
                                  <foreach collection="roleIds" item="item" index="index" open="(" separator="," close=")" >
                                      #{item,jdbcType=VARCHAR}
                                  </foreach>
                              </if>
                              AND no_auth is not null AND no_auth &lt;&gt; ''
                          </where>
                        )
                  </where>
              </when>
          <otherwise> <!--超级管理员查看所有-->
              SELECT
                     *
              FROM
                    disk_file
              <where>
                  <if test="isContainFolder == false">
                      AND filetype &lt;&gt; 0
                  </if>
                  <if test="pid != null and pid != '' ">
                      AND pid = #{pid, jdbcType=VARCHAR}
                  </if>
              </where>
          </otherwise>
        </choose>
      ) t2
      LEFT JOIN
              disk_type_suffix dts
              ON dts.suffix = t2.filesuffix
              AND dts.typecode = t2.typecode
    <where>
        <if test="typecode != null and typecode != '' and typecode != 'all' and typecode != 'ALL' ">
            AND t2.typecode = #{typecode, jdbcType=VARCHAR}
        </if>
        <if test="filesuffix != null and filesuffix != '' ">
            AND t2.filesuffix = #{filesuffix, jdbcType=VARCHAR}
        </if>
        <if test="filename != null and filename != ''">
            AND t2.filename LIKE CONCAT('%', #{filename, jdbcType=VARCHAR},'%')
        </if>
    </where>
  </select>

四、判断文件夹是否有可写、管理权限

1.上传文件到文件夹时判断有没有可写、管理权限

@ApiOperation(value = "切块上传", notes = "切块上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "切块", dataType = "file", paramType = "form", required = true),
    })
    @PostMapping("/uploadChunk")
    @FolderPrivilege(value = {"writable", "manage"}, logical = Logical.OR)
    public Object uploadChunk(@RequestParam("file")MultipartFile file, ChunkPojo chunkPojo) throws Exception {
        UserAO user = AuthUtil.getCurrentUser();
        //判断切块是否为空
        if (file == null) {
            return ServiceResultHelper.genResultWithFaild("切块不能为空", -1);
        }
        //参数设置
        Chunk chunk = new Chunk();
        BeanUtils.copyProperties(chunkPojo, chunk);
        chunk.setUserid(user.getId());
        chunk.setUsername(user.getUserName());
        chunk.setBytes(file.getBytes());
        //4.调用切块上传接口
        return diskFileService.uploadChunk(chunk);
    }

使用注解方式: 

package cn.datainvest.dms.system.folderPrivilege;

import org.apache.shiro.authz.annotation.Logical;

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


@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface FolderPrivilege {
    String[] value();

    Logical logical() default Logical.AND;
}

 aop获取文件夹权限并从注解中获取权限验证:

package cn.datainvest.dms.system.folderPrivilege;

import cn.datainvest.common.exception.BaseException;
import cn.datainvest.dms.system.auth.AuthUtil;
import cn.datainvest.dms.system.entity.customized.DiskFileFolderPrivilegeAO;
import cn.datainvest.dms.system.entity.customized.UserAO;
import cn.datainvest.dms.system.service.IDiskFileFolderPrivilegeService;
import cn.datainvest.dms.system.service.IDiskFileService;
import cn.datainvest.dms.system.service.IRoleService;
import org.apache.shiro.authz.annotation.Logical;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author yangfeng
 * @date 2019年9月10日
 */
@Aspect
@Component
public class FolderPrivilegeAspect {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private IDiskFileService diskFileService;

    @Resource
    private IRoleService roleService;

    @Resource
    private IDiskFileFolderPrivilegeService diskFileFolderPrivilegeService;

    public FolderPrivilegeAspect() {
    }

    /**
     * 定义切入点对象表达式 execution
     * 注解参数 logOperation
     */
    private static final String pointCutExpression = "execution(@FolderPrivilege * *(..)) && @annotation(folderPrivilege)";

    /**
     * 切入点声明
     *
     * @param folderPrivilege
     */
    @Pointcut(pointCutExpression)
    public void handlePointCut(FolderPrivilege folderPrivilege) {
    }

    /**
     * Before 增强。对handlePointCut进行before增强
     *
     * @param joinPoint       被通知的对象的对象、参数。。。
     * @param folderPrivilege 注解参数提取action Name
     */
    @Before(value = "handlePointCut(folderPrivilege)")
    public void handleBefore(JoinPoint joinPoint, FolderPrivilege folderPrivilege) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request != null) {
            String[] privileges = folderPrivilege.value();
            Logical logical = folderPrivilege.logical();
            String pid = request.getParameter("pid");
            UserAO user = AuthUtil.getCurrentUser();
            if (!user.isSuperAdmin()) {
                boolean privileged = false;
                if (!StringUtils.isEmpty(pid)) {
                    List<String> roleIds = roleService.getRoleIdsByUserId(user.getId()).getData();

                    //获取文件夹的权限数据
                    List<DiskFileFolderPrivilegeAO> privilegeList = diskFileFolderPrivilegeService.listFolderPrivileges(pid, roleIds).getData();

                    if (!CollectionUtils.isEmpty(privilegeList)) {
                        for (DiskFileFolderPrivilegeAO privilege : privilegeList) {
                            if (privileges != null && privileges.length > 0) {
                                if (logical == null) {
                                    if (FolderPrivilegeType.WRITABLE.getCode().equals(privileges[0])
                                            && !StringUtils.isEmpty(privilege.getWritable())) {
                                        privileged = true;
                                        break;
                                    } else if (FolderPrivilegeType.MANAGE.getCode().equals(privileges[0])
                                            && !StringUtils.isEmpty(privilege.getManage())) {
                                        privileged = true;
                                        break;
                                    }
                                } else if (Logical.OR.equals(logical)) {
                                    for (String p : privileges) {
                                        if (FolderPrivilegeType.WRITABLE.getCode().equals(p)
                                                && !StringUtils.isEmpty(privilege.getWritable())) {
                                            privileged = true;
                                            break;
                                        }
                                        if (FolderPrivilegeType.MANAGE.getCode().equals(p)
                                                && !StringUtils.isEmpty(privilege.getManage())) {
                                            privileged = true;
                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
                if (!privileged) {
                    throw new BaseException(-1, "没有操作权限");
                }
            }
        }
    }


}

2.删除文件或文件夹时判断有没有管理权限


    /**
     * 检查文件是否有管理权限
     *
     * @param ids 文件id
     */
    public void checkManagePrivilege(List<String> ids) {
        UserAO user = AuthUtil.getCurrentUser();
        List<String> roleIds = roleService.getRoleIdsByUserId(user.getId()).getData();
        if (CollectionUtils.isEmpty(roleIds)) {
            throw new BaseException(-1, "没有查询到用户的角色信息");
        }
        if (!CollectionUtils.isEmpty(ids)) {
            for (String id : ids) {
                List<DiskFileFolderPrivilegeAO> privilegeList = diskFileFolderPrivilegeService
                        .listFolderPrivileges(id, roleIds).getData();
                DiskFileAO file = selectByPrimaryKey(id).getData();
                if (file != null) {
                    if (!hasManagePrivilege(privilegeList)) {
                        throw new BaseException(-1, file.getFilename() + ":没有删除权限");
                    }
                }
            }
        }
    }


    /**
     * 是否有管理权限
     *
     * @param privilegeList
     * @return
     */
    public boolean hasManagePrivilege(List<DiskFileFolderPrivilegeAO> privilegeList) {
        boolean result = false;
        if (!CollectionUtils.isEmpty(privilegeList)) {
            for (DiskFileFolderPrivilegeAO privilege : privilegeList) {
                if (!StringUtils.isEmpty(privilege.getManage())) {
                    result = true;
                    break;
                }
            }
        }
        return result;
    }

   至此,文件夹权限保存,根据权限获取文件夹,判断文件夹可写、管理权限完成。

©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页