FastBee Security Advisories and Fixes
The maintained codebase includes the corresponding fixes; the first official release containing each fix still requires item-by-item verification. The table below distinguishes maintained code, fix commits, and official releases; updating to an arbitrary latest package is not a substitute for checking the deployed instance.
Remediation Status at a Glance
| Item | Affected scope or nature | Official remediation status | Upgrade and verification |
|---|---|---|---|
| Default-credential deployment risk | Initial deployment credentials exposed to untrusted networks | Deployment flow unchanged; users rotate credentials after deployment | Rotate default passwords before exposing a production instance and verify password strength |
| Demo-account logic flaw | Demo-role cache permissions and data scope | Fixed in maintained code; first official release pending verification | Check monitor:cache:list and guest-role data scope |
| go-view arbitrary SQL execution | Unauthenticated direct SQL endpoint | Fixed in maintained code; first official release pending verification | Disable when unused or require authorization; verify anonymous requests are rejected |
| Stored XSS | News, notices, and device-log rendering and persistence | Fixed in maintained code; first official release pending verification | Verify unsafe markup is sanitized and normal rich text still works |
| CVE-2025-15251 (XXE) | FastBee 2.1 and earlier (NVD) | Fixed in maintained code; first official release pending verification | Disable DTD/external entities and restrict SIP exposure |
| CVE-2026-7676 (arbitrary file read) | FastBee 1.2.1 and earlier (NVD) | Fixed in maintained code; first official release pending verification | Verify files outside the allowed directory are unreadable and normal downloads still work |
| CVE-2026-111654 (device-group IDOR) | FastBee 2.1.0 and earlier (CVE) | Fixed in maintained code; first official release pending verification | Use accounts with different owners to test all five device-group operation types |
| CVE-2026-120274 (Groovy RCE) | FastBee 2.1.0 and earlier (NVD/AVD) | Fixed in maintained code; fix commit; first official release pending verification | Verify compile-time and runtime protections and validation before persistence/hot-loading |
| Vertical privilege escalation | Low-privilege accounts accessing administrator APIs | Fixed in maintained code; first official release pending verification | Verify 403 responses and data scope by permission matrix, not only hidden menus |
Default credentials are intended for initial deployment, and users can change them after deployment; providing initial credentials does not change the existing deployment flow. Before exposing a production instance, rotate default passwords and restrict demo-account permissions to reduce unsolicited login attempts.
See the Pre-deployment Security Checklist for launch verification and the Security FAQ for fixed releases, custom-code upgrades, and instance validation.
Security Advisories
- This page collects publicly documented FastBee security issues, maintained-code remediation status, and instance verification guidance. Upgrade and validate your actual deployment promptly.
- When the first official release is still pending verification, do not infer that an instance is safe from its version label alone. Check deployed code, configuration, permissions, and regression results together.
- Back up programs, configuration, and data before remediation, and validate business compatibility in a test environment first.
Report a Security Issue
Email 164770707@qq.com with the subject "FastBee Security Issue". Include the installed version, affected product, reproduction steps, impact, and relevant logs. For undisclosed issues, do not publish vulnerability details or exploitable PoCs in public Issues first.
1. Weak Credential Vulnerability Fix
Vulnerability description: The platform admin password, database password, Redis password, EMQ console password, and similar credentials are too simple, which may allow attackers to access the system without authorization, leading to data leakage, tampering, or other malicious activities with serious impact on users and enterprises.
Fix recommendation: Change the above passwords, set complex, high-strength passwords, rotate passwords regularly, and harden server protection.
2. Logic Flaw Vulnerability Fix
Vulnerability description: The platform ships with a demo account, and the account credentials fastbee / 123456 are documented in plain text. If the role assigned to this account is granted the cache monitor or cache list permission monitor:cache:list, an attacker can obtain other users' login information from the cache and use it to log in to the platform, posing a major security risk.
Fix recommendation: Do not grant this permission to the demo account's role.
3. SQL Injection Vulnerability Fix
Vulnerability description: The go-view data visualization big-screen feature integrates a direct SQL execution capability, allowing arbitrary query SQL to be entered and executed without login or any credentials. Code location: com.fastbee.controller.goview.GoviewProjectDataController
Fix recommendation:
If you do not need this feature, comment out or delete the file directly;
If you need this feature, add login permission verification to the endpoint com.fastbee.controller.goview.GoviewProjectDataController#executeSql;
4. XSS Vulnerability Fix
Vulnerability description:
News and notice content is rendered directly into the DOM using Vue's v-html directive without any HTML escaping or sanitization. Fix recommendation: Add XSS filtering on both the frontend and backend;
Log data reported by devices (logValue) is stored directly in the database without any HTML filtering or escaping, and the frontend renders logValue directly with the v-html directive, allowing malicious scripts to execute in the administrator's browser. Fix recommendation: Add XSS filtering during frontend rendering;
4.1. Open Source Version Fix
The open source version can be fixed by updating to the latest code directly.
4.2. Commercial Version Fix
4.2.1. Frontend Fix
The following fix targets the latest version. Users whose code update entitlement has not expired can update the code directly. If the entitlement has expired, use the steps below. Users on the Vue 2 version can refer to the following content and fix it themselves.
- In the vue3/package.json file, add the following to "dependencies"
"dompurify": "^3.4.13",New file: Create a safeHtml.ts file under vue3/src/directive/module/
New file: Create a file named "security.ts" under vue3/src/utils
Replace the vue3/src/utils/index.js file
Replace the vue3/src/components/Editor/index.vue file
Replace the vue3/src/utils/map.js file
In the following files, replace "v-html" with "v-safe-html.presentation"
- src/views/iot/device/device-log.vue,
- src/views/iot/alert/log.vue,
- src/views/iot/clientDetails/index.vue,
- src/views/iot/device/device-alert.vue,
- src/views/iot/device/device-timer.vue,
- src/views/iot/product/product-things-model.vue,
- src/views/iot/scene/log.vue,
- src/views/iot/simulate/index.vue,
- src/views/visualBigScreen/management/packages/components/Tables/Tables/TableList/index.vue,
- src/views/visualBigScreen/management/packages/components/Tables/Tables/TableScrollBoard/index.vue,Replace src/views/system/notice/index.vue
Replace src/views/ruleegine/editor/js/jsplumb.js
Replace the src/views/iot/news/index.vue file
4.2.2. Backend Fix
- In the springboot/fastbee-common-extend/pom.xml file, add the dependency
<!-- 富文本白名单净化 -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.18.3</version>
</dependency>- In the springboot/fastbee-service/fastbee-system-service/pom.xml file, add the dependency
<!-- 单元测试组件 -->
<dependency>
<groupId>com.fastbee</groupId>
<artifactId>fastbee-test</artifactId>
<scope>test</scope>
</dependency>- springboot\fastbee-service\fastbee-iot-service\src...\iot\service\impl\NewsServiceImpl#insertNews method
/**
* 新增新闻资讯
*
* @param news 新闻资讯
* @return 结果
*/
@Override
public int insertNews(News news)
{
sanitizeNews(news);
news.setCreateTime(DateUtils.getNowDate());
news.setCreateBy(getUserName());
return newsMapper.insert(news);
}- springboot\fastbee-service\fastbee-iot-service\src...\iot\service\impl\NewsServiceImpl#updateNews method
/**
* 修改新闻资讯
*
* @param news 新闻资讯
* @return 结果
*/
@Override
public int updateNews(News news)
{
sanitizeNews(news);
news.setUpdateTime(DateUtils.getNowDate());
news.setUpdateBy(getUserName());
return newsMapper.updateById(news);
}- springboot\fastbee-service\fastbee-iot-service\src...\iot\service\impl\NewsServiceImpl#add the sanitizeNews method
private void sanitizeNews(News news)
{
news.setTitle(RichTextSanitizer.sanitizePlainText(news.getTitle()));
news.setContent(RichTextSanitizer.sanitizeRichText(news.getContent()));
news.setImgUrl(RichTextSanitizer.sanitizePlainText(news.getImgUrl()));
news.setCategoryName(RichTextSanitizer.sanitizePlainText(news.getCategoryName()));
news.setAuthor(RichTextSanitizer.sanitizePlainText(news.getAuthor()));
news.setRemark(RichTextSanitizer.sanitizePlainText(news.getRemark()));
}- In the springboot\fastbee-service\fastbee-iot-service...\iot\service\NewsServiceImplTest.java class, add the following two methods
@Test
@DisplayName("insertNews - 应净化新闻纯文本和富文本中的 XSS")
void testInsertNews_ShouldSanitizeXss() {
News news = new News();
news.setTitle("<b>新闻标题</b><script>alert(1)</script>");
news.setContent("<p class=\"ql-align-center\">正文</p><img src=\"/test.jpg\" onerror=\"alert('XSS')\"><script>alert(2)</script>");
news.setAuthor("<img src=x onerror=alert(3)>管理员");
when(newsMapper.insert(any(News.class))).thenReturn(1);
assertEquals(1, newsService.insertNews(news));
assertEquals("新闻标题", news.getTitle());
assertEquals("管理员", news.getAuthor());
assertTrue(news.getContent().contains("<p class=\"ql-align-center\">正文</p>"));
assertTrue(news.getContent().contains("<img src=\"/test.jpg\">"));
assertFalse(news.getContent().contains("onerror"));
assertFalse(news.getContent().contains("<script"));
}
@Test
@DisplayName("updateNews - 应移除危险链接协议并保留安全链接")
void testUpdateNews_ShouldSanitizeDangerousProtocol() {
News news = new News();
news.setNewsId(randomLongId());
news.setContent("<a href=\"javascript:alert(1)\">危险链接</a><a href=\"https://fastbee.cn\" target=\"\_blank\">安全链接</a>");
when(newsMapper.updateById(any(News.class))).thenReturn(1);
assertEquals(1, newsService.updateNews(news));
assertFalse(news.getContent().contains("javascript:"));
assertTrue(news.getContent().contains("href=\"https://fastbee.cn\""));
assertTrue(news.getContent().contains("rel=\"nofollow noopener noreferrer\""));
}- In the springboot\fastbee-service\fastbee-system-service...\service\impl\SysNoticeServiceImpl.java class, modify the insertNotice and updateNotice methods and add the sanitizeNotice method
/\*\*
_ 新增公告
_
_ @param notice 公告信息
_ @return 结果
\*/
@Override
public int insertNotice(SysNotice notice)
{
sanitizeNotice(notice);
return noticeMapper.insert(notice);
}
/**
* 修改公告
*
* @param notice 公告信息
* @return 结果
*/
@Override
public int updateNotice(SysNotice notice)
{
sanitizeNotice(notice);
notice.setUpdateTime(DateUtils.getNowDate());
return noticeMapper.updateById(notice);
}
private void sanitizeNotice(SysNotice notice)
{
notice.setNoticeTitle(RichTextSanitizer.sanitizePlainText(notice.getNoticeTitle()));
notice.setNoticeContent(RichTextSanitizer.sanitizeRichText(notice.getNoticeContent()));
notice.setRemark(RichTextSanitizer.sanitizePlainText(notice.getRemark()));
}- springboot\fastbee-common-extend\src\main\java\com\fastbee\common\extend\utils\html\add the RichTextSanitizer.java class
package com.fastbee.common.extend.utils.html;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.safety.Cleaner;
import org.jsoup.safety.Safelist;
/\*\*
- 用户可编辑富文本的 XSS 白名单净化工具。
\*/
public final class RichTextSanitizer {
private static final Safelist RICH_TEXT_SAFELIST = Safelist.relaxed()
.addTags("figure", "figcaption", "hr")
.addAttributes(":all", "class", "title")
.addAttributes("a", "target", "rel")
.addAttributes("img", "loading")
.addAttributes("table", "border", "cellpadding", "cellspacing")
.addAttributes("td", "colspan", "rowspan")
.addAttributes("th", "colspan", "rowspan", "scope")
.addProtocols("a", "href", "http", "https", "mailto")
.addProtocols("img", "src", "http", "https")
.addEnforcedAttribute("a", "rel", "nofollow noopener noreferrer")
.preserveRelativeLinks(true);
private RichTextSanitizer() {
}
/**
* 保留安全的排版标签,移除脚本、事件属性和危险协议。
*
* @param html 待净化的富文本
* @return 可安全交给前端 HTML 渲染的内容
*/
public static String sanitizeRichText(String html) {
if (html == null) {
return null;
}
Document.OutputSettings outputSettings = new Document.OutputSettings().prettyPrint(false);
Document document = Jsoup.parseBodyFragment(html, "https://fastbee.invalid");
Document cleanDocument = new Cleaner(RICH_TEXT_SAFELIST).clean(document);
cleanDocument.outputSettings(outputSettings);
// 协议相对地址会随页面协议指向任意外部站点,富文本中不允许使用。
for (Element element : cleanDocument.select("[href], [src]")) {
for (String attribute : new String[]{"href", "src"}) {
if (element.hasAttr(attribute) && element.attr(attribute).trim().startsWith("//")) {
element.removeAttr(attribute);
}
}
}
return cleanDocument.body().html();
}
/**
* 移除纯文本字段中的全部 HTML 标签及可执行内容。
*
* @param text 待净化的文本
* @return 不包含 HTML 标签的文本
*/
public static String sanitizePlainText(String text) {
if (text == null) {
return null;
}
Document.OutputSettings outputSettings = new Document.OutputSettings().prettyPrint(false);
return Jsoup.clean(text, "", Safelist.none(), outputSettings);
}
}- springboot\fastbee-service\fastbee-system-service\src\test\java\com\fastbee\system\service\add the SysNoticeServiceImplTest.java class
package com.fastbee.system.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import com.fastbee.framework.core.ut.BaseMockitoUnitTest;
import com.fastbee.system.domain.SysNotice;
import com.fastbee.system.mapper.SysNoticeMapper;
import com.fastbee.system.service.impl.SysNoticeServiceImpl;
/\*\*
- {@link SysNoticeServiceImpl} 单元测试。
\*/
@DisplayName("通知公告 Service 单元测试")
@Tag("dev")
class SysNoticeServiceImplTest extends BaseMockitoUnitTest {
@InjectMocks
private SysNoticeServiceImpl noticeService;
@Mock
private SysNoticeMapper noticeMapper;
@Test
@DisplayName("insertNotice - 应净化标题和公告富文本中的 XSS")
void insertNoticeShouldSanitizeXss() {
SysNotice notice = new SysNotice();
notice.setNoticeTitle("<b>安全公告</b><script>alert(1)</script>");
notice.setNoticeContent("<p>公告正文</p><img src=\"/test.jpg\" onerror=alert('XSS')><iframe src=\"https://example.com\"></iframe>");
when(noticeMapper.insert(any(SysNotice.class))).thenReturn(1);
assertEquals(1, noticeService.insertNotice(notice));
assertEquals("安全公告", notice.getNoticeTitle());
assertTrue(notice.getNoticeContent().contains("<p>公告正文</p>"));
assertTrue(notice.getNoticeContent().contains("<img src=\"/test.jpg\">"));
assertFalse(notice.getNoticeContent().contains("onerror"));
assertFalse(notice.getNoticeContent().contains("iframe"));
verify(noticeMapper).insert(notice);
}
@Test
@DisplayName("updateNotice - 应在修改前净化 XSS 并设置更新时间")
void updateNoticeShouldSanitizeXssAndSetUpdateTime() {
SysNotice notice = new SysNotice();
notice.setNoticeId(1L);
notice.setNoticeContent("<a href=\"javascript:alert(1)\">链接</a><strong>正常内容</strong>");
when(noticeMapper.updateById(any(SysNotice.class))).thenReturn(1);
assertEquals(1, noticeService.updateNotice(notice));
assertFalse(notice.getNoticeContent().contains("javascript:"));
assertTrue(notice.getNoticeContent().contains("<strong>正常内容</strong>"));
assertNotNull(notice.getUpdateTime());
verify(noticeMapper).updateById(notice);
}
}5. SIP XML External Entity (XXE): CVE-2025-15251
Affected versions: the NVD record covers FastBee 2.1 and earlier. The issue is located in ReqAbstractHandler.getRootElement in the SIP Message Handler. A malicious XML external entity reference may expose sensitive server files. Exploitation requires network access to the SIP service and conditions such as a valid deviceSipId; it is not an unconditional remote exploit against every deployment.
Remediation and verification:
- If SIP video access is not required, disable and restrict the SIP service ports. Do not expose 5060/5061 to untrusted networks, and remove demo devices and default credentials.
- Verify that the XML parser in the deployed code disallows DTDs, external general entities, and external parameter entities. A JDK upgrade alone is not a substitute for secure parser configuration.
- If the affected code is present, upgrade to a maintained release after testing and inspect the actual
ReqAbstractHandlerchanges. This page does not infer an unverified fixed release from the CVE's affected range. - After remediation, use non-sensitive test data to confirm that external DTDs and entity requests are rejected, and review SIP logs and outbound connections.
reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);References: NVD CVE-2025-15251, FastBee repository Issue ID7HNZ.
6. Arbitrary File Read in the Download Endpoint: CVE-2026-7676
Affected versions: the NVD record covers FastBee 1.2.1 and earlier. The issue is located in ToolController.download in springboot/fastbee-open-api/src/main/java/com/fastbee/data/controller/ToolController.java. Path traversal through the fileName argument may expose files outside the intended download directory, resulting in an arbitrary file read risk.
Remediation and verification:
- If an affected version is deployed, inspect the endpoint and argument-handling code and upgrade to a maintained release after testing. Do not determine the state of an instance from its version label or a third-party reproduction article alone.
- Canonicalize the target path and verify that it remains inside the allowed download directory. Reject absolute paths, directory traversal, and symlink escapes; string replacement alone is insufficient.
- Require authentication and authorization for the endpoint and retain access logs. If the endpoint is unnecessary, disable it at both the gateway and application layers.
- After remediation, use an isolated test directory to confirm that files outside that directory cannot be read and normal downloads still work.
Reference: NVD CVE-2026-7676.
7. Device-Group IDOR: CVE-2026-111654
Affected versions: the CVE record covers FastBee 2.1.0 and earlier. When GroupController queries lack device-group ownership checks, an authenticated low-privilege user may use group IDs to read, overwrite, reassign, change device-association data for, or delete another user's device groups.
Remediation and verification:
- Enforce device-group ownership or tenant boundaries throughout the controller, service, and Mapper query chain. Hiding frontend buttons or checking only that a group ID exists is insufficient.
- Apply consistent device-group ownership checks to reads, updates, reassignment, device-association changes, and deletion, and log denied cross-owner requests and abnormal changes.
- Disable self-registration when it is not required. Review existing low-privilege and demo accounts, and inspect device-group data for cross-user anomalies.
- Use two test accounts with different owners to verify that every device-group read and write path returns the correct authorization result, then review actual code changes and regression tests.
Reference: NVD CVE-2026-111654.
Version Verification Boundary
The affected versions above come from public CVE records and define the investigation scope. They do not mean that this page has confirmed a complete fix in any later release. Verify the deployed version, relevant source code, fix commits, and regression tests together; unverified fixed versions or commits are not claimed here.
8. Groovy Rule-Script Injection Leading to RCE: CVE-2026-120274
Affected versions: NVD and Alibaba Cloud AVD record FastBee 2.1.0 and earlier. If the /iot/script create/edit path merely removes import statements before hot-loading code into the default Groovy executor, the absence of a sandbox and dangerous-class isolation can let a remote attacker with script-editing permission execute arbitrary code on the server. Device uplinks and platform downlinks can execute the loaded script.
The attacker must already have script-editing permission; this is not an anonymous, unauthenticated exploit. Vertical-privilege remediation, script-editor permission restrictions, and Groovy executor protections must therefore be verified together.
Official remediation: the maintained codebase contains the fix. The public fix commit is 890a33846005a937a58cccd738b7fb9821b82ea9; the first official release containing it remains pending verification.
The fix uses SecureGroovyScriptExecutor.compileSource and BusinessScriptInterceptor to break the dangerous chain:
- Compile time: class declarations, package declarations, annotations, and custom constructors are rejected so scripts cannot define new executable structures.
- Runtime: process, file, and reflection calls are denied by default. Removing
importstatements or hiding the script editor is not a substitute for these controls. - Before persistence and hot-loading: new and edited scripts must pass the same compiler validation. Validation must not occur only at save time while hot-loading bypasses compiler restrictions.
- Permissions and auditing: grant script-editing permission only to roles that require it, and log script changes and abnormal execution.
Regression verification:
- In an isolated test environment, verify that classes, packages, annotations, and custom constructors are rejected, and that process, file, and reflection calls are denied.
- Verify that create/edit paths apply the same validation before persistence and hot-loading, while legitimate business scripts still run as expected.
- Use a standard-privilege account to confirm that script editing is unavailable, and inspect historical scripts and runtime logs for unexpected changes.
References: NVD CVE-2026-120274 and Alibaba Cloud AVD-2026-120274.
9. Vertical Privilege Escalation Vulnerability Fix
An attacker can exploit this vulnerability with a low-privilege account to access system endpoints that should only be available to administrators. Permission verification needs to be added to the corresponding endpoints, listed below:
- /system/user/2
- /system/user/authRole/1
- /system/config/list?pageNum=1&pageSize=10
- /system/role/list?pageNum=1&pageSize=10
- /system/post/list?pageNum=1&pageSize=10
- /system/dept/100
- /system/user/list?pageNum=1&pageSize=10
9.1. Open Source Version Fix
- springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysDeptController.java file
/**
* 根据部门编号获取详细信息
*/
@ApiOperation("根据部门编号获取详细信息")
@PreAuthorize("@ss.hasPermi('system:dept:query')")
@GetMapping(value = "/{deptId}")
public AjaxResult getInfo(@PathVariable Long deptId)
{
LoginUser loginUser = SecurityUtils.getLoginUser();
List<String> currentRoleKeys = loginUser.getUser().getRoles().stream()
.map(role -> role.getRoleKey())
.collect(Collectors.toList());
if (currentRoleKeys.contains("visitor")) {
return AjaxResult.error(403, "游客无权限访问部门信息!");
}
try {
deptService.checkDeptDataScope(deptId);
} catch (ServiceException e) {
return AjaxResult.error(403, e.getMessage());
}
SysDept dept = deptService.selectDeptById(deptId);
return AjaxResult.success(dept);
}9.1.1. Backend Fix
- springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysUserController.java file
/\*\*
_ 根据用户编号获取详细信息
_/
@PreAuthorize("@ss.hasPermi('system:user:query')")
@GetMapping(value = { "/", "/{userId}" })
public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
{
AjaxResult ajax = AjaxResult.success();
LoginUser loginUser = SecurityUtils.getLoginUser();
SysUser currentUser = loginUser.getUser();
Long currentUserId = currentUser.getUserId();
List<String> currentRoleKeys = currentUser.getRoles().stream()
.map(SysRole::getRoleKey)
.collect(Collectors.toList());
if (currentRoleKeys.contains("visitor")) {
return AjaxResult.error(403, "游客无权限访问用户信息!");
}
if (StringUtils.isNotNull(userId))
{
try {
userService.checkUserDataScope(userId);
} catch (ServiceException e) {
return AjaxResult.error(403, e.getMessage());
}
SysUser sysUser = userService.selectUserById(userId);
// 非超管过滤超管角色信息
if (!SysUser.isAdmin(currentUserId)) {
List<SysRole> filterRoles = sysUser.getRoles().stream()
.filter(r -> !r.isAdmin())
.collect(Collectors.toList());
sysUser.setRoles(filterRoles);
}
// 封装数据
ajax.put(AjaxResult.DATA_TAG, sysUser);
ajax.put("postIds", postService.selectPostListByUserId(userId));
List<Long> roleIds = sysUser.getRoles().stream()
.map(SysRole::getRoleId)
.collect(Collectors.toList());
ajax.put("roleIds", roleIds);
}
// 角色/岗位列表过滤
List<SysRole> roles = roleService.selectRoleAll();
ajax.put("roles", SysUser.isAdmin(currentUserId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
// ========== 8. 岗位列表:仅用selectPostListByUserId(适配现有方法) ==========
if (SysUser.isAdmin(currentUserId)) {
// 超管:返回所有岗位
ajax.put("posts", postService.selectPostAll());
} else {
// 非超管:仅返回当前登录用户自己的岗位
ajax.put("posts", postService.selectPostListByUserId(currentUserId));
}
return ajax;
}
/**
* 根据用户编号获取授权角色
*/
@PreAuthorize("@ss.hasPermi('system:user:query')")
@GetMapping("/authRole/{userId}")
public AjaxResult authRole(@PathVariable("userId") Long userId)
{
AjaxResult ajax = AjaxResult.success();
LoginUser loginUser = SecurityUtils.getLoginUser();
SysUser currentUser = loginUser.getUser();
Long currentUserId = currentUser.getUserId();
List<String> currentRoleKeys = currentUser.getRoles().stream()
.map(SysRole::getRoleKey)
.collect(Collectors.toList());
if (currentRoleKeys.contains("visitor")) {
return AjaxResult.error(403, "游客无权限访问用户授权角色信息!");
}
try {
userService.checkUserDataScope(userId);
} catch (ServiceException e) {
return AjaxResult.error(403, e.getMessage());
}
SysUser user = userService.selectUserById(userId);
List<SysRole> roles = roleService.selectRolesByUserId(userId);
List<SysRole> filterRoles = SysUser.isAdmin(currentUserId)
? roles // 超管返回所有授权角色
: roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()); // 非超管过滤超管角色
ajax.put("user", user);
ajax.put("roles", filterRoles);
return ajax;
}- springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysDeptServiceImpl.java file
/**
* 校验部门是否有数据权限
*
* @param deptId 部门id
*/
@Override
public void checkDeptDataScope(Long deptId)
{
if (SysUser.isAdmin(SecurityUtils.getUserId())) {
return;
}
SysDept queryDept = new SysDept();
List<SysDept> accessibleDepts = SpringUtils.getAopProxy(this).selectDeptList(queryDept);
if (CollectionUtils.isEmpty(accessibleDepts)) {
throw new ServiceException("没有权限访问部门数据!");
}
boolean hasPermission = accessibleDepts.stream()
.anyMatch(dept -> dept.getDeptId().equals(deptId));
if (!hasPermission) {
throw new ServiceException("没有权限访问该部门数据!");
}
SysDept targetDept = this.selectDeptById(deptId);
if (targetDept == null) {
throw new ServiceException("部门不存在!");
}
}- springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysPostServiceImpl.java file
/**
* 查询岗位信息集合
*
* @param post 岗位信息
* @return 岗位信息集合
*/
@Override
public List<SysPost> selectPostList(SysPost post)
{
LoginUser loginUser = SecurityUtils.getLoginUser();
if (loginUser.getUser().getRoles().stream()
.map(role -> role.getRoleKey())
.collect(Collectors.toList()).contains("visitor")) {
return Collections.emptyList();
}
List<SysPost> postList = postMapper.selectPostList(post);
return CollectionUtils.isEmpty(postList) ? Collections.emptyList() : postList;
}- springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysRoleServiceImpl.java file
/\*\*
_ 根据条件分页查询角色数据
_
_ @param role 角色信息
_ @return 角色数据集合信息
\*/
@Override
@DataScope(deptAlias = "d")
public List<SysRole> selectRoleList(SysRole role)
{
LoginUser loginUser = SecurityUtils.getLoginUser();
List<String> currentRoleKeys = loginUser.getUser().getRoles().stream()
.map(SysRole::getRoleKey)
.collect(Collectors.toList());
if (currentRoleKeys.contains("visitor")) {
return Collections.emptyList();
}
List<SysRole> roleList = roleMapper.selectRoleList(role);
if (CollectionUtils.isEmpty(roleList)) {
return Collections.emptyList();
}
Long currentUserId = loginUser.getUser().getUserId();
if (SysUser.isAdmin(currentUserId)) {
return roleList;
} else {
return roleList.stream()
.filter(r -> !r.isAdmin())
.collect(Collectors.toList());
}
}- In the src/views/index.vue file, replace "v-html" with "v-safe-html", then import
import { escapeHtml } from '@/utils/security';- Add the following methods to the script
function appendInfoLine(container: HTMLElement, label: string, value: unknown, highlight = false) {
container.append(document.createTextNode(`${label}:`));
const text = String(value ?? '');
if (highlight) {
const span = document.createElement('span');
span.style.color = '#486FF2';
span.textContent = text;
container.appendChild(span);
} else {
container.append(document.createTextNode(text));
}
container.appendChild(document.createElement('br'));
}
function appendColoredInfoLine(container: HTMLElement, label: string, value: unknown, color: string) {
container.append(document.createTextNode(`${label}:`));
const span = document.createElement('span');
span.style.color = color;
span.textContent = String(value ?? '');
container.appendChild(span);
container.appendChild(document.createElement('br'));
}In the src/views/ai/chat/index.vue file, replace "v-html" with "v-safe-html.markdown"
springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysUserServiceImpl.java file
/**
* 根据条件分页查询用户列表
*
* @param user 用户信息
* @return 用户信息集合信息
*/
@Override
@DataScope(deptAlias = "d", userAlias = "u")
public List<SysUser> selectUserList(SysUser user)
{
LoginUser loginUser = SecurityUtils.getLoginUser();
SysUser currentUser = loginUser.getUser();
Long currentUserId = currentUser.getUserId();
Long currentDeptId = currentUser.getDeptId();
if (!SecurityUtils.isAdmin(currentUserId)) {
user.setDeptId(currentDeptId);
user.setUserId(currentUserId);
return userMapper.selectUserList(user);
}
return userMapper.selectUserList(user);
}
/**
* 校验用户是否有数据权限
*
* @param userId 用户id
*/
@Override
public void checkUserDataScope(Long userId)
{
Long currentUserId = SecurityUtils.getUserId();
// 超管直接放行
if (SysUser.isAdmin(currentUserId)) {
return;
}
SysUser queryCondition = new SysUser();
List<SysUser> accessibleUsers = SpringUtils.getAopProxy(this).selectUserList(queryCondition);
boolean hasPermission = accessibleUsers.stream()
.anyMatch(u -> u.getUserId().equals(userId));
SysUser targetUser = this.selectUserById(userId);
if (targetUser != null && SysUser.isAdmin(targetUser.getUserId())) {
throw new ServiceException("禁止访问超级管理员信息!");
}
if (!hasPermission) {
throw new ServiceException("没有权限访问用户数据!");
}
}9.2. Commercial Version Fix
提示
For v2.7.0 and later versions, if the demo account fastbee exists, change the data scope of the visitor role assigned to the fastbee account to "own data only".
9.2.1. Case 1: If the code repository license has not expired, simply update the main branch code
9.2.2. Case 2: The code repository license has expired; for v2.7.0 and later versions, modify the code as follows
- com.fastbee.common.extend.utils.SecurityUtils#getDataScope method
public static String getDataScope() {
SysUser user = SecurityUtils.getLoginUser().getUser();
String dataScope;
if (user.isAdmin()) {
dataScope = DataScopeAspect.DATA_SCOPE_DEPT_AND_CHILD;
} else {
List<SysRole> roles = user.getRoles();
List<String> list = roles.stream().map(SysRole::getDataScope).distinct().collect(Collectors.toList());
if (list.contains(DataScopeAspect.DATA_SCOPE_DEPT_AND_CHILD)) {
dataScope = DataScopeAspect.DATA_SCOPE_DEPT_AND_CHILD;
} else if (list.contains(DataScopeAspect.DATA_SCOPE_DEPT)) {
dataScope = DataScopeAspect.DATA_SCOPE_DEPT;
} else {
dataScope = DataScopeAspect.DATA_SCOPE_SELF;
}
}
return dataScope;
}- com.fastbee.system.service.impl.SysDeptServiceImpl#checkDeptDataScope method
/**
* 校验部门是否有数据权限
*
* @param deptId 部门id
*/
@Override
public void checkDeptDataScope(Long deptId)
{
LoginUser loginUser = getLoginUser();
SysUser curUser = loginUser.getUser();
if (SysUser.isAdmin(curUser.getUserId())) {
return;
}
SysDept dept = new SysDept();
dept.setDeptId(deptId);
List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
if (StringUtils.isEmpty(depts))
{
throw new ServiceException("没有权限访问部门数据!");
}
if (null == curUser.getDeptId()) {
throw new ServiceException("没有权限访问部门数据!");
} else {
String dataScope = getDataScope();
if (DataScopeAspect.DATA_SCOPE_SELF.equals(dataScope) || DataScopeAspect.DATA_SCOPE_DEPT.equals(dataScope)) {
if (!curUser.getDeptId().equals(deptId)) {
throw new ServiceException("没有权限访问部门数据!");
}
} else if (DataScopeAspect.DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) {
if (!curUser.getDeptId().equals(deptId)) {
String ancestors = depts.get(0).getAncestors();
if (!ancestors.contains(curUser.getDeptId().toString())) {
throw new ServiceException("没有权限访问部门数据!");
}
}
}
}
}- com.fastbee.controller.system.SysDeptController#list method
/**
* 获取机构列表
*/
@ApiOperation("获取机构列表")
@PreAuthorize("@ss.hasPermi('system:dept:list')")
@GetMapping("/list")
public AjaxResult list(SysDept dept)
{
if (Objects.nonNull(dept) && null != dept.getDeptId()) {
deptService.checkDeptDataScope(dept.getDeptId());
}
List<SysDept> depts = deptService.selectDeptList(dept);
return success(depts);
}- com.fastbee.controller.system.SysDeptController#getInfo method
/**
* 根据机构编号获取详细信息
*/
@ApiOperation("根据机构编号获取详细信息")
@PreAuthorize("@ss.hasPermi('system:dept:query')")
@GetMapping(value = "/{deptId}")
public AjaxResult getInfo(@PathVariable Long deptId)
{
deptService.checkDeptDataScope(deptId);
SysDept sysDept = deptService.selectDeptById(deptId);
if (null != sysDept && null != sysDept.getDeptUserId()) {
SysUser sysUser = sysUserService.selectUserById(sysDept.getDeptUserId());
sysDept.setUserName(sysUser.getUserName());
sysDept.setPhone(sysUser.getPhonenumber());
}
return success(sysDept);
}- com.fastbee.controller.system.SysDeptController#getRole method
/**
* 获取机构角色
* @param deptId 机构id
* @return com.fastbee.common.core.domain.AjaxResult
*/
@GetMapping("/getRole")
public AjaxResult getRole(Long deptId) {
deptService.checkDeptDataScope(deptId);
String dataScope = getDataScope();
AjaxResult success = AjaxResult.success();
List<SysRole> sysRoleList = deptService.getRole(deptId);
if (DataScopeAspect.DATA_SCOPE_SELF.equals(dataScope)) {
List<Long> roleIdList = getLoginUser().getUser().getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList());
sysRoleList = sysRoleList.stream().filter(sysRole -> roleIdList.contains(sysRole.getRoleId())).collect(Collectors.toList());
} else {
if (!isAdmin(getUserId()) && CollectionUtils.isNotEmpty(sysRoleList)) {
sysRoleList = sysRoleList.stream().filter(sysRole -> !"admin".equals(sysRole.getRoleKey())).collect(Collectors.toList());
}
}
success.put("roles", sysRoleList);
success.put("roleIds", sysRoleList.stream().map(SysRole::getRoleId).collect(Collectors.toList()));
return success;
}- com.fastbee.system.service.impl.SysUserServiceImpl#checkUserDataScope method
/**
* 校验用户是否有数据权限
*
* @param userId 用户id
*/
@Override
public void checkUserDataScope(Long userId) {
LoginUser loginUser = getLoginUser();
SysUser curUser = loginUser.getUser();
if (SysUser.isAdmin(curUser.getUserId())) {
return;
}
if (curUser.getUserId().equals(userId)) {
return;
}
if (SysUser.isAdmin(userId)) {
throw new ServiceException("没有权限访问用户数据!");
}
SysUser user = SpringUtils.getAopProxy(this).selectUserById(userId);
if (ObjectUtil.isNull(user)) {
throw new ServiceException("没有权限访问用户数据!");
}
if (null == curUser.getDeptId() || null == user.getDeptId()) {
throw new ServiceException("没有权限访问用户数据!");
}
String dataScope = getDataScope();
if (DataScopeAspect.DATA_SCOPE_SELF.equals(dataScope)) {
throw new ServiceException("没有权限访问用户数据!");
} else if (DataScopeAspect.DATA_SCOPE_DEPT.equals(dataScope)) {
if (!curUser.getDeptId().equals(user.getDeptId())) {
throw new ServiceException("没有权限访问用户数据!");
}
} else if (DataScopeAspect.DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) {
if (!curUser.getDeptId().equals(user.getDeptId())) {
String ancestors = user.getDept().getAncestors();
if (!ancestors.contains(curUser.getDeptId().toString())) {
throw new ServiceException("没有权限访问用户数据!");
}
}
}
List<SysRole> roles = curUser.getRoles();
List<String> roleKeyList = roles.stream().map(SysRole::getRoleKey).collect(Collectors.toList());
if (!roleKeyList.contains("manager") && user.getDept().getDeptUserId().equals(userId)) {
throw new ServiceException("没有权限访问用户数据!");
}
}- com.fastbee.controller.system.SysUserController#list method
/**
* 获取用户列表
*/
@ApiOperation("获取用户分页列表")
@PreAuthorize("@ss.hasPermi('system:user:list')")
@GetMapping("/list")
public TableDataInfo list(SysUser user)
{
if (null != user.getDeptId()) {
deptService.checkDeptDataScope(user.getDeptId());
String dataScope = getDataScope();
if (DataScopeAspect.DATA_SCOPE_SELF.equals(dataScope)) {
user.setUserId(getUserId());
}
}
Page<SysUser> list = sysUserService.selectUserList(user);
return getDataTable(list.getRecords(), list.getTotal());
}- com.fastbee.controller.system.SysUserController#export method
@ApiOperation("导出用户列表")
@Log(title = "用户管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:user:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysUser user)
{
if (null != user.getDeptId()) {
deptService.checkDeptDataScope(user.getDeptId());
String dataScope = getDataScope();
if (DataScopeAspect.DATA_SCOPE_SELF.equals(dataScope)) {
user.setUserId(getUserId());
}
}
Page<SysUser> list = sysUserService.selectUserList(user);
ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
util.exportExcel(response, list.getRecords(), "用户数据");
}- com.fastbee.controller.system.SysUserController#authRole method
/**
* 根据用户编号获取授权角色
*/
@ApiOperation("根据用户编号获取授权角色")
@PreAuthorize("@ss.hasPermi('system:user:query')")
@GetMapping("/authRole/{userId}")
public AjaxResult authRole(@PathVariable("userId") Long userId)
{
sysUserService.checkUserDataScope(userId);
AjaxResult ajax = AjaxResult.success();
SysUser user = sysUserService.selectUserById(userId);
List<SysRole> roles = roleService.selectRolesByUserId(userId);
ajax.put("user", user);
ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
return ajax;
}- com.fastbee.controller.system.SysUserController#insertAuthRole method
/**
* 用户授权角色
*/
@ApiOperation("为用户授权角色")
@PreAuthorize("@ss.hasPermi('system:user:edit')")
@Log(title = "用户管理", businessType = BusinessType.GRANT)
@PutMapping("/authRole")
public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
{
sysUserService.checkUserDataScope(userId);
SysUser sysUser = sysUserService.selectSysUserById(userId);
List<Long> deptRoleIds = sysRoleDeptMapper.selectByDeptId(sysUser.getDeptId());
boolean b = deptRoleIds.removeAll(Arrays.asList(roleIds));
if (!b) {
return error("请检查角色id");
}
sysUserService.insertUserAuth(userId, roleIds);
return success();
}- com.fastbee.controller.system.SysUserController#deptTree method
/**
* 获取部门树列表
*/
@ApiOperation("获取部门树列表")
@PreAuthorize("@ss.hasPermi('system:dept:list')")
@GetMapping("/deptTree")
public AjaxResult deptTree(SysDept dept)
{
if (Objects.nonNull(dept) && null != dept.getDeptId()) {
deptService.checkDeptDataScope(dept.getDeptId());
}
return success(deptService.selectDeptTreeList(dept));
}- com.fastbee.controller.system.SysUserController#listTerminal method
/**
* 获取终端用户列表
* @param user 用户信息
* @return com.fastbee.common.core.page.TableDataInfo
*/
@ApiOperation("获取用户分页列表")
@PreAuthorize("@ss.hasPermi('system:user:list')")
@GetMapping("/listTerminal")
public TableDataInfo listTerminal(SysUser user)
{
if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
return new TableDataInfo();
}
Page<SysUser> page = sysUserService.listTerminal(user);
return getDataTable(page.getRecords(), page.getTotal());
}- com.fastbee.system.service.impl.SysUserServiceImpl#selectByDeptId method
/**
* 根据机构id获取当前机构所有非管理用户
*/
@Override
public Page<SysUser> selectByDeptId(SysUser user) {
Long deptId = SecurityUtils.getDeptId();
MPJLambdaWrapper<SysUser> wrapper = JoinWrappers.lambda(SysUser.class);
// select
wrapper.select(SysUser::getUserId, SysUser::getDeptId, SysUser::getUserName,
SysUser::getNickName);
// join
wrapper.innerJoin(SysDept.class, SysDept::getDeptId, SysUser::getDeptId);
// where
String dataScope = getDataScope();
if (DataScopeAspect.DATA_SCOPE_SELF.equals(dataScope)) {
wrapper.eq(SysUser::getUserId, user.getUserId());
} else {
wrapper.eq(SysUser::getDeptId, deptId);
wrapper.ne(SysUser::getDeptId, SysDept::getDeptUserId);
}
return baseMapper.selectPage(new Page<>(1, Integer.MAX_VALUE), wrapper);
}- com.fastbee.system.service.impl.SysRoleServiceImpl#checkRoleDataScope method
/**
* 校验角色是否有数据权限
*
* @param roleId 角色id
*/
@Override
public void checkRoleDataScope(Long roleId) {
LoginUser loginUser = getLoginUser();
SysUser curUser = loginUser.getUser();
if (SysUser.isAdmin(curUser.getUserId())) {
return;
}
List<SysRole> roles = curUser.getRoles();
List<Long> roleIdList = roles.stream().map(SysRole::getRoleId).collect(Collectors.toList());
if (roleIdList.contains(roleId)) {
return;
}
if (null == curUser.getDeptId()) {
throw new ServiceException("没有权限访问角色数据!");
} else {
String dataScope = getDataScope();
LambdaQueryWrapper<SysRoleDept> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(SysRoleDept::getRoleId, roleId);
List<SysRoleDept> sysRoleDepts = roleDeptMapper.selectList(queryWrapper);
SysRoleDept sysRoleDept = sysRoleDepts.get(0);
if (Objects.isNull(sysRoleDept)) {
throw new ServiceException("没有权限访问角色数据!");
}
Long bindDeptId = sysRoleDept.getDeptId();
if (DataScopeAspect.DATA_SCOPE_SELF.equals(dataScope)) {
throw new ServiceException("没有权限访问角色数据!");
} else if (DataScopeAspect.DATA_SCOPE_DEPT.equals(dataScope)) {
if (!curUser.getDeptId().equals(bindDeptId)) {
throw new ServiceException("没有权限访问角色数据!");
}
} else if (DataScopeAspect.DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) {
if (!curUser.getDeptId().equals(bindDeptId)) {
SysDept sysDept = sysDeptMapper.selectDeptById(bindDeptId);
String ancestors = sysDept.getAncestors();
if (!ancestors.contains(curUser.getDeptId().toString())) {
throw new ServiceException("没有权限访问角色数据!");
}
}
}
}
}- com.fastbee.system.service.impl.SysRoleServiceImpl#selectRoleList method
/**
* 根据条件分页查询角色数据
*
* @param role 角色信息
* @return 角色数据集合信息
*/
@Override
// @DataScope(deptAlias = "d")
public Page<SysRole> selectRoleList(SysRole role) {
LoginUser loginUser = getLoginUser();
Long userId = loginUser.getUserId();
Long userDeptId = loginUser.getDeptId();
String dataScope = getDataScope();
Page<SysRole> rolePage;
if (DataScopeAspect.DATA_SCOPE_SELF.equals(dataScope)) {
List<Long> roleIdList = loginUser.getUser().getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList());
rolePage = roleMapper.selectRoleByIds(new Page<>(role.getPageNum(), role.getPageSize()), roleIdList, role.getRoleName(), role.getStatus());
if (0 == rolePage.getTotal()) {
return rolePage;
}
List<SysRole> sysRoleList = rolePage.getRecords();
SysDept dept = loginUser.getUser().getDept();
for (SysRole sysRole : sysRoleList) {
if (Objects.nonNull(dept)) {
sysRole.setDeptId(dept.getDeptId());
sysRole.setDeptName(dept.getDeptName());
}
sysRole.setManager("manager".equals(sysRole.getRoleKey()));
}
return rolePage;
} else {
SysDept sysDept = new SysDept();
sysDept.setDeptId(role.getDeptId());
List<SysDept> sysDeptList = deptService.selectDeptList(sysDept);
if (CollectionUtils.isNotEmpty(sysDeptList)) {
Map<Long, String> deptMap = sysDeptList.stream().collect(Collectors.toMap(SysDept::getDeptId, SysDept::getDeptName));
List<Long> deptIdList = sysDeptList.stream().map(SysDept::getDeptId).collect(Collectors.toList());
List<SysRoleDeptVO> sysRoleDeptVOList = roleDeptMapper.selectRoleDeptByDeptIds(deptIdList);
Map<Long, SysRoleDeptVO> roleDeptMap = sysRoleDeptVOList.stream().collect(Collectors.toMap(SysRoleDeptVO::getRoleId, Function.identity()));
if (CollectionUtils.isEmpty(sysRoleDeptVOList)) {
return new Page<>();
}
List<Long> roleIdList = sysRoleDeptVOList.stream().map(SysRoleDeptVO::getRoleId).collect(Collectors.toList());
if (CollectionUtils.isEmpty(roleIdList)) {
return new Page<>();
}
rolePage = roleMapper.selectRoleByIds(new Page<>(role.getPageNum(), role.getPageSize()), roleIdList, role.getRoleName(), role.getStatus());
List<SysRole> sysRoleList = rolePage.getRecords();
for (SysRole sysRole : sysRoleList) {
SysRoleDeptVO sysRoleDeptVO = roleDeptMap.get(sysRole.getRoleId());
Long deptId1 = sysRoleDeptVO.getDeptId();
String deptName = deptMap.get(deptId1);
sysRole.setDeptId(deptId1);
sysRole.setDeptName(deptName);
sysRole.setCanEditRole(!(userDeptId.equals(deptId1) && "manager".equals(sysRole.getRoleKey()) && !isAdmin(userId)));
if (isAdmin(sysRoleDeptVO.getDeptUserId())) {
sysRole.setManager("terminalRegister".equals(sysRole.getRoleKey()) || "scadaShare".equals(sysRole.getRoleKey())
|| "manager".equals(sysRole.getRoleKey()) || "webRegister".equals(sysRole.getRoleKey()));
} else {
sysRole.setManager("manager".equals(sysRole.getRoleKey()));
}
}
return rolePage;
} else {
return new Page<>();
}
}
}- com.fastbee.controller.system.SysRoleController#list method
@ApiOperation("获取角色分页列表")
@PreAuthorize("@ss.hasPermi('system:role:list')")
@GetMapping("/list")
public TableDataInfo list(SysRole role, Integer pageNum, Integer pageSize)
{
if (null != role.getDeptId()) {
deptService.checkDeptDataScope(role.getDeptId());
}
role.setPageNum(pageNum);
role.setPageSize(pageSize);
Page<SysRole> rolePage = sysRoleService.selectRoleList(role);
// 按照 roleSort 字段排序
rolePage.getRecords().sort(Comparator.comparingInt(SysRole::getRoleSort));
TableDataInfo tableDataInfo = new TableDataInfo();
tableDataInfo.setCode(HttpStatus.SUCCESS);
tableDataInfo.setMsg(MessageUtils.message("query.success"));
tableDataInfo.setRows(rolePage.getRecords());
tableDataInfo.setTotal(rolePage.getTotal());
return tableDataInfo;
}- com.fastbee.controller.system.SysRoleController#export method
@ApiOperation("导出角色列表")
@Log(title = "角色管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:role:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysRole role)
{
if (null != role.getDeptId()) {
deptService.checkDeptDataScope(role.getDeptId());
}
List<SysRole> list = sysRoleService.selectRoleList(role).getRecords();
ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
util.exportExcel(response, list, "角色数据");
}- com.fastbee.controller.system.SysRoleController#optionselect method
/**
* 获取角色选择框列表
*/
@ApiOperation("获取角色选择框列表")
@PreAuthorize("@ss.hasPermi('system:role:query')")
@GetMapping("/optionselect")
public AjaxResult optionselect()
{
SysRole sysRole = new SysRole();
sysRole.setPageNum(1);
sysRole.setPageSize(99);
Page<SysRole> rolePage = sysRoleService.selectRoleList(sysRole);
return success(rolePage.getRecords());
}- com.fastbee.controller.system.SysRoleController#allocatedList method
/**
* 查询已分配用户角色列表
*/
@ApiOperation("查询已分配用户角色列表")
@PreAuthorize("@ss.hasPermi('system:role:list')")
@GetMapping("/authUser/allocatedList")
public TableDataInfo allocatedList(SysUser user)
{
if (null != user.getRoleId()) {
sysRoleService.checkRoleDataScope(user.getRoleId());
}
Page<SysUser> list = userService.selectAllocatedList(user);
return getDataTable(list.getRecords(), list.getTotal());
}- com.fastbee.controller.system.SysRoleController#unallocatedList method
/**
* 查询未分配用户角色列表
*/
@ApiOperation("查询未分配用户角色列表")
@PreAuthorize("@ss.hasPermi('system:role:list')")
@GetMapping("/authUser/unallocatedList")
public TableDataInfo unallocatedList(SysUser user)
{
if (null != user.getRoleId()) {
sysRoleService.checkRoleDataScope(user.getRoleId());
}
Page<SysUser> list = userService.selectUnallocatedList(user);
return getDataTable(list.getRecords(), list.getTotal());
}- com.fastbee.controller.system.SysRoleController#cancelAuthUser method
/**
* 取消授权用户
*/
@ApiOperation("取消授权用户")
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.GRANT)
@PutMapping("/authUser/cancel")
public AjaxResult cancelAuthUser(@RequestBody SysUserRole userRole)
{
if (null != userRole.getRoleId()) {
sysRoleService.checkRoleDataScope(userRole.getRoleId());
}
return toAjax(sysRoleService.deleteAuthUser(userRole));
}- com.fastbee.controller.system.SysRoleController#cancelAuthUserAll method
/**
* 批量取消授权用户
*/
@ApiOperation("批量取消授权用户")
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.GRANT)
@PutMapping("/authUser/cancelAll")
public AjaxResult cancelAuthUserAll(Long roleId, Long[] userIds)
{
if (null != roleId) {
sysRoleService.checkRoleDataScope(roleId);
}
return toAjax(sysRoleService.deleteAuthUsers(roleId, userIds));
}- com.fastbee.controller.system.SysRoleController#deptTree method
/**
* 获取对应角色部门树列表
*/
@ApiOperation("获取对应角色部门树列表")
@PreAuthorize("@ss.hasPermi('system:role:query')")
@GetMapping(value = "/deptTree/{roleId}")
public AjaxResult deptTree(@PathVariable("roleId") Long roleId)
{
sysRoleService.checkRoleDataScope(roleId);
AjaxResult ajax = AjaxResult.success();
ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
ajax.put("depts", deptService.selectDeptTreeList(new SysDept()));
return ajax;
}9.2.3. Case 3: The code repository license has expired; for versions v2.3 to v2.6.0, modify the code as follows
- com.fastbee.system.service.impl.SysDeptServiceImpl#checkDeptDataScope method
/**
* 校验部门是否有数据权限
*
* @param deptId 部门id
*/
@Override
public void checkDeptDataScope(Long deptId)
{
LoginUser loginUser = getLoginUser();
SysUser curUser = loginUser.getUser();
if (SysUser.isAdmin(curUser.getUserId())) {
return;
}
SysDept dept = new SysDept();
dept.setDeptId(deptId);
List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
if (StringUtils.isEmpty(depts))
{
throw new ServiceException("没有权限访问部门数据!");
}
if (null == curUser.getDeptId()) {
throw new ServiceException("没有权限访问部门数据!");
} else {
if (!curUser.getDeptId().equals(deptId)) {
throw new ServiceException("没有权限访问部门数据!");
}
}
}- com.fastbee.controller.system.SysDeptController#list method
/**
* 获取机构列表
*/
@ApiOperation("获取机构列表")
@PreAuthorize("@ss.hasPermi('system:dept:list')")
@GetMapping("/list")
public AjaxResult list(SysDept dept)
{
if (Objects.nonNull(dept) && null != dept.getDeptId()) {
deptService.checkDeptDataScope(dept.getDeptId());
}
List<SysDept> depts = deptService.selectDeptList(dept);
return success(depts);
}- com.fastbee.controller.system.SysDeptController#getRole method
/**
* 获取机构角色
* @param deptId 机构id
* @return com.fastbee.common.core.domain.AjaxResult
*/
@GetMapping("/getRole")
public AjaxResult getRole(Long deptId) {
deptService.checkDeptDataScope(deptId);
AjaxResult success = AjaxResult.success();
List<SysRole> sysRoleList = deptService.getRole(deptId);
if (!isAdmin(getUserId()) && CollectionUtils.isNotEmpty(sysRoleList)) {
sysRoleList = sysRoleList.stream().filter(sysRole -> !"admin".equals(sysRole.getRoleKey())).collect(Collectors.toList());
}
success.put("roles", sysRoleList);
success.put("roleIds", sysRoleList.stream().map(SysRole::getRoleId).collect(Collectors.toList()));
return success;
}- com.fastbee.system.service.impl.SysUserServiceImpl#checkUserDataScope method
/**
* 校验用户是否有数据权限
*
* @param userId 用户id
*/
@Override
public void checkUserDataScope(Long userId) {
LoginUser loginUser = getLoginUser();
SysUser curUser = loginUser.getUser();
if (SysUser.isAdmin(curUser.getUserId())) {
return;
}
if (curUser.getUserId().equals(userId)) {
return;
}
if (SysUser.isAdmin(userId)) {
throw new ServiceException("没有权限访问用户数据!");
}
SysUser user = SpringUtils.getAopProxy(this).selectUserById(userId);
if (ObjectUtil.isNull(user)) {
throw new ServiceException("没有权限访问用户数据!");
}
if (null == curUser.getDeptId() || null == user.getDeptId()) {
throw new ServiceException("没有权限访问用户数据!");
}
if (!curUser.getDeptId().equals(user.getDeptId())) {
throw new ServiceException("没有权限访问用户数据!");
}
List<SysRole> roles = curUser.getRoles();
List<String> roleKeyList = roles.stream().map(SysRole::getRoleKey).collect(Collectors.toList());
if (!roleKeyList.contains("manager") && user.getDept().getDeptUserId().equals(userId)) {
throw new ServiceException("没有权限访问用户数据!");
}
}- com.fastbee.controller.system.SysUserController#list method
/**
* 获取用户列表
*/
@ApiOperation("获取用户分页列表")
@PreAuthorize("@ss.hasPermi('system:user:list')")
@GetMapping("/list")
public TableDataInfo list(SysUser user)
{
if (null == user.getDeptId()) {
user.setDeptId(getLoginUser().getDeptId());
} else {
deptService.checkDeptDataScope(user.getDeptId());
}
if (null != user.getUserId()) {
sysUserService.checkUserDataScope(user.getUserId());
}
if (null == user.getShowChild()) {
user.setShowChild(true);
}
Page<SysUser> list = sysUserService.selectUserList(user);
return getDataTable(list.getRecords(), list.getTotal());
}- com.fastbee.controller.system.SysUserController#export method
@ApiOperation("导出用户列表")
@Log(title = "用户管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:user:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysUser user)
{
if (null == user.getDeptId()) {
user.setDeptId(getLoginUser().getDeptId());
} else {
deptService.checkDeptDataScope(user.getDeptId());
}
if (null != user.getUserId()) {
sysUserService.checkUserDataScope(user.getUserId());
}
if (null == user.getShowChild()) {
user.setShowChild(true);
}
Page<SysUser> list = sysUserService.selectUserList(user);
ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
util.exportExcel(response, list.getRecords(), "用户数据");
}- com.fastbee.controller.system.SysUserController#authRole method
/**
* 根据用户编号获取授权角色
*/
@ApiOperation("根据用户编号获取授权角色")
@PreAuthorize("@ss.hasPermi('system:user:query')")
@GetMapping("/authRole/{userId}")
public AjaxResult authRole(@PathVariable("userId") Long userId)
{
sysUserService.checkUserDataScope(userId);
AjaxResult ajax = AjaxResult.success();
SysUser user = sysUserService.selectUserById(userId);
List<SysRole> roles = roleService.selectRolesByUserId(userId);
ajax.put("user", user);
ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
return ajax;
}- com.fastbee.controller.system.SysUserController#insertAuthRole method
/**
* 用户授权角色
*/
@ApiOperation("为用户授权角色")
@PreAuthorize("@ss.hasPermi('system:user:edit')")
@Log(title = "用户管理", businessType = BusinessType.GRANT)
@PutMapping("/authRole")
public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
{
sysUserService.checkUserDataScope(userId);
SysUser sysUser = sysUserService.selectSysUserById(userId);
List<Long> deptRoleIds = sysRoleDeptMapper.selectByDeptId(sysUser.getDeptId());
boolean b = deptRoleIds.removeAll(Arrays.asList(roleIds));
if (!b) {
return error("请检查角色id");
}
sysUserService.insertUserAuth(userId, roleIds);
return success();
}- com.fastbee.controller.system.SysUserController#deptTree method
/**
* 获取部门树列表
*/
@ApiOperation("获取部门树列表")
@PreAuthorize("@ss.hasPermi('system:user:list')")
@GetMapping("/deptTree")
public AjaxResult deptTree(SysDept dept)
{
if (Objects.nonNull(dept) && null != dept.getDeptId()) {
deptService.checkDeptDataScope(dept.getDeptId());
}
return success(deptService.selectDeptTreeList(dept));
}- com.fastbee.controller.system.SysUserController#listTerminal method
/**
* 获取终端用户列表
* @param user 用户信息
* @return com.fastbee.common.core.page.TableDataInfo
*/
@ApiOperation("获取用户分页列表")
@PreAuthorize("@ss.hasPermi('system:user:list')")
@GetMapping("/listTerminal")
public TableDataInfo listTerminal(SysUser user)
{
if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
return new TableDataInfo();
}
Page<SysUser> page = sysUserService.listTerminal(user);
return getDataTable(page.getRecords(), page.getTotal());
}- com.fastbee.system.service.impl.SysRoleServiceImpl#checkRoleDataScope method
/**
* 校验角色是否有数据权限
*
* @param roleId 角色id
*/
@Override
public void checkRoleDataScope(Long roleId) {
LoginUser loginUser = getLoginUser();
SysUser curUser = loginUser.getUser();
if (SysUser.isAdmin(curUser.getUserId())) {
return;
}
List<SysRole> roles = curUser.getRoles();
List<Long> roleIdList = roles.stream().map(SysRole::getRoleId).collect(Collectors.toList());
if (roleIdList.contains(roleId)) {
return;
}
if (null == curUser.getDeptId()) {
throw new ServiceException("没有权限访问角色数据!");
} else {
LambdaQueryWrapper<SysRoleDept> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(SysRoleDept::getRoleId, roleId);
List<SysRoleDept> sysRoleDeptList = roleDeptMapper.selectList(queryWrapper);
SysRoleDept sysRoleDept = sysRoleDeptList.get(0);
if (Objects.isNull(sysRoleDept)) {
throw new ServiceException("没有权限访问角色数据!");
}
if (!curUser.getDeptId().equals(sysRoleDept.getDeptId())) {
throw new ServiceException("没有权限访问角色数据!");
}
}
}- com.fastbee.controller.system.SysRoleController#list method
@ApiOperation("获取角色分页列表")
@PreAuthorize("@ss.hasPermi('system:role:list')")
@GetMapping("/list")
public TableDataInfo list(SysRole role, Integer pageNum, Integer pageSize)
{
if (null != role.getDeptId()) {
deptService.checkDeptDataScope(role.getDeptId());
}
role.setPageNum(pageNum);
role.setPageSize(pageSize);
Page<SysRole> rolePage = sysRoleService.selectRoleList(role);
// 按照 roleSort 字段排序
rolePage.getRecords().sort(Comparator.comparingInt(SysRole::getRoleSort));
TableDataInfo tableDataInfo = new TableDataInfo();
tableDataInfo.setCode(HttpStatus.SUCCESS);
tableDataInfo.setMsg(MessageUtils.message("query.success"));
tableDataInfo.setRows(rolePage.getRecords());
tableDataInfo.setTotal(rolePage.getTotal());
return tableDataInfo;
}- com.fastbee.controller.system.SysRoleController#export method
@ApiOperation("导出角色列表")
@Log(title = "角色管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:role:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysRole role)
{
if (null != role.getDeptId()) {
deptService.checkDeptDataScope(role.getDeptId());
}
List<SysRole> list = sysRoleService.selectRoleList(role).getRecords();
ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
util.exportExcel(response, list, "角色数据");
}- com.fastbee.controller.system.SysRoleController#optionselect method
/**
* 获取角色选择框列表
*/
@ApiOperation("获取角色选择框列表")
@PreAuthorize("@ss.hasPermi('system:role:query')")
@GetMapping("/optionselect")
public AjaxResult optionselect()
{
Long deptId = getDeptId();
if (null == deptId) {
return success();
}
return success(sysRoleService.selectRoleAll());
}- com.fastbee.controller.system.SysRoleController#allocatedList method
/**
* 查询已分配用户角色列表
*/
@ApiOperation("查询已分配用户角色列表")
@PreAuthorize("@ss.hasPermi('system:role:list')")
@GetMapping("/authUser/allocatedList")
public TableDataInfo allocatedList(SysUser user)
{
if (null != user.getRoleId()) {
sysRoleService.checkRoleDataScope(user.getRoleId());
}
Page<SysUser> list = userService.selectAllocatedList(user);
return getDataTable(list.getRecords(), list.getTotal());
}- com.fastbee.controller.system.SysRoleController#unallocatedList method
/**
* 查询未分配用户角色列表
*/
@ApiOperation("查询未分配用户角色列表")
@PreAuthorize("@ss.hasPermi('system:role:list')")
@GetMapping("/authUser/unallocatedList")
public TableDataInfo unallocatedList(SysUser user)
{
if (null != user.getRoleId()) {
sysRoleService.checkRoleDataScope(user.getRoleId());
}
Long deptId = getDeptId();
if (null == deptId) {
return new TableDataInfo();
}
if (null != user.getDeptId()) {
deptService.checkDeptDataScope(deptId);
}
Page<SysUser> list = userService.selectUnallocatedList(user);
return getDataTable(list.getRecords(), list.getTotal());
}- com.fastbee.controller.system.SysRoleController#cancelAuthUser method
/**
* 取消授权用户
*/
@ApiOperation("取消授权用户")
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.GRANT)
@PutMapping("/authUser/cancel")
public AjaxResult cancelAuthUser(@RequestBody SysUserRole userRole)
{
if (null != userRole.getRoleId()) {
sysRoleService.checkRoleDataScope(userRole.getRoleId());
}
return toAjax(sysRoleService.deleteAuthUser(userRole));
}- com.fastbee.controller.system.SysRoleController#cancelAuthUserAll method
/**
* 批量取消授权用户
*/
@ApiOperation("批量取消授权用户")
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.GRANT)
@PutMapping("/authUser/cancelAll")
public AjaxResult cancelAuthUserAll(Long roleId, Long[] userIds)
{
if (null != roleId) {
sysRoleService.checkRoleDataScope(roleId);
}
return toAjax(sysRoleService.deleteAuthUsers(roleId, userIds));
}- com.fastbee.controller.system.SysRoleController#deptTree method
/**
* 获取对应角色部门树列表
*/
@ApiOperation("获取对应角色部门树列表")
@PreAuthorize("@ss.hasPermi('system:role:query')")
@GetMapping(value = "/deptTree/{roleId}")
public AjaxResult deptTree(@PathVariable("roleId") Long roleId)
{
sysRoleService.checkRoleDataScope(roleId);
AjaxResult ajax = AjaxResult.success();
ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
ajax.put("depts", deptService.selectDeptTreeList(new SysDept()));
return ajax;
}

