liujie
2026-09-11 4f6f15b818704079ff2e4e4719b798f48d68a335
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.tourguide.modules.system.service;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tourguide.common.exception.BusinessException;
import com.tourguide.modules.system.entity.SystemMenu;
import com.tourguide.modules.system.entity.SystemRole;
import com.tourguide.modules.system.entity.SystemRoleMenu;
import com.tourguide.modules.system.mapper.SystemMenuMapper;
import com.tourguide.modules.system.mapper.SystemRoleMapper;
import com.tourguide.modules.system.mapper.SystemRoleMenuMapper;
import org.springframework.stereotype.Service;
 
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
 
/** 统一从角色菜单关系中加载后台权限,供登录响应和接口鉴权复用。 */
@Service
public class AdminPermissionService {
    private static final String SUPER_ADMIN_ROLE = "ADMIN";
 
    private final SystemRoleMapper roleMapper;
    private final SystemMenuMapper menuMapper;
    private final SystemRoleMenuMapper roleMenuMapper;
 
    public AdminPermissionService(SystemRoleMapper roleMapper, SystemMenuMapper menuMapper,
                                  SystemRoleMenuMapper roleMenuMapper) {
        this.roleMapper = roleMapper;
        this.menuMapper = menuMapper;
        this.roleMenuMapper = roleMenuMapper;
    }
 
    public List<String> getMenuCodes(String roleCode) {
        SystemRole role = roleMapper.selectOne(new LambdaQueryWrapper<SystemRole>()
                .eq(SystemRole::getRoleCode, roleCode)
                .eq(SystemRole::getStatus, 1)
                .last("LIMIT 1"));
        if (role == null) {
            throw new BusinessException(401, "后台角色不存在或已停用");
        }
 
        if (SUPER_ADMIN_ROLE.equals(roleCode)) {
            return toMenuCodes(menuMapper.selectList(new LambdaQueryWrapper<SystemMenu>()
                    .eq(SystemMenu::getStatus, 1)
                    .orderByAsc(SystemMenu::getSort, SystemMenu::getId)));
        }
 
        List<Long> menuIds = roleMenuMapper.selectList(new LambdaQueryWrapper<SystemRoleMenu>()
                        .eq(SystemRoleMenu::getRoleId, role.getId()))
                .stream()
                .map(SystemRoleMenu::getMenuId)
                .collect(Collectors.toList());
        if (menuIds.isEmpty()) {
            return Collections.emptyList();
        }
        return toMenuCodes(menuMapper.selectList(new LambdaQueryWrapper<SystemMenu>()
                .in(SystemMenu::getId, menuIds)
                .eq(SystemMenu::getStatus, 1)
                .orderByAsc(SystemMenu::getSort, SystemMenu::getId)));
    }
 
    private List<String> toMenuCodes(List<SystemMenu> menus) {
        return menus.stream().map(SystemMenu::getMenuCode).collect(Collectors.toList());
    }
}