Fixes for Common System Vulnerabilities and Bugs
Notice
- Please fix the following vulnerabilities as soon as possible to keep the system more secure and reliable.
- Please fix the vertical privilege escalation vulnerability as soon as possible to keep the system more secure and reliable.
- You can fix these vulnerabilities directly by updating the source code. If you do not update the source code, you can modify the files by referring to the changes below.
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
<!-- Rich text safelist sanitization -->
<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
<!-- Unit test component -->
<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
/**
* Add news
*
* @param news the news
* @return result
*/
@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
/**
* Update news
*
* @param news the news
* @return result
*/
@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 - should sanitize XSS in news plain text and rich text")
void testInsertNews_ShouldSanitizeXss() {
News news = new News();
news.setTitle("<b>News Title</b><script>alert(1)</script>");
news.setContent("<p class=\"ql-align-center\">Body</p><img src=\"/test.jpg\" onerror=\"alert('XSS')\"><script>alert(2)</script>");
news.setAuthor("<img src=x onerror=alert(3)>Admin");
when(newsMapper.insert(any(News.class))).thenReturn(1);
assertEquals(1, newsService.insertNews(news));
assertEquals("News Title", news.getTitle());
assertEquals("Admin", news.getAuthor());
assertTrue(news.getContent().contains("<p class=\"ql-align-center\">Body</p>"));
assertTrue(news.getContent().contains("<img src=\"/test.jpg\">"));
assertFalse(news.getContent().contains("onerror"));
assertFalse(news.getContent().contains("<script"));
}
@Test
@DisplayName("updateNews - should remove dangerous link protocols and keep safe links")
void testUpdateNews_ShouldSanitizeDangerousProtocol() {
News news = new News();
news.setNewsId(randomLongId());
news.setContent("<a href=\"javascript:alert(1)\">Dangerous Link</a><a href=\"https://fastbee.cn\" target=\"\_blank\">Safe Link</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
/\*\*
_ Add notice
_
_ @param notice the notice information
_ @return result
\*/
@Override
public int insertNotice(SysNotice notice)
{
sanitizeNotice(notice);
return noticeMapper.insert(notice);
}
/**
* Update notice
*
* @param notice the notice information
* @return result
*/
@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 safelist sanitizer for user-editable rich text.
\*/
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() {
}
/**
* Keeps safe formatting tags and removes scripts, event attributes, and dangerous protocols.
*
* @param html the rich text to sanitize
* @return content that can be safely rendered as HTML on the frontend
*/
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);
// Protocol-relative URLs can point to any external site depending on the page protocol and are not allowed in rich text.
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();
}
/**
* Removes all HTML tags and executable content from plain text fields.
*
* @param text the text to sanitize
* @return text without any HTML tags
*/
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} unit tests.
\*/
@DisplayName("Notice Service Unit Tests")
@Tag("dev")
class SysNoticeServiceImplTest extends BaseMockitoUnitTest {
@InjectMocks
private SysNoticeServiceImpl noticeService;
@Mock
private SysNoticeMapper noticeMapper;
@Test
@DisplayName("insertNotice - should sanitize XSS in title and notice rich text")
void insertNoticeShouldSanitizeXss() {
SysNotice notice = new SysNotice();
notice.setNoticeTitle("<b>Security Notice</b><script>alert(1)</script>");
notice.setNoticeContent("<p>Notice body</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("Security Notice", notice.getNoticeTitle());
assertTrue(notice.getNoticeContent().contains("<p>Notice body</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 - should sanitize XSS and set update time before updating")
void updateNoticeShouldSanitizeXssAndSetUpdateTime() {
SysNotice notice = new SysNotice();
notice.setNoticeId(1L);
notice.setNoticeContent("<a href=\"javascript:alert(1)\">Link</a><strong>Normal content</strong>");
when(noticeMapper.updateById(any(SysNotice.class))).thenReturn(1);
assertEquals(1, noticeService.updateNotice(notice));
assertFalse(notice.getNoticeContent().contains("javascript:"));
assertTrue(notice.getNoticeContent().contains("<strong>Normal content</strong>"));
assertNotNull(notice.getUpdateTime());
verify(noticeMapper).updateById(notice);
}
}5. 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
5.1. Open Source Version Fix
- springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysDeptController.java file
/**
* Get details by department ID
*/
@ApiOperation("Get details by department ID")
@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, "Visitors are not allowed to access department information!");
}
try {
deptService.checkDeptDataScope(deptId);
} catch (ServiceException e) {
return AjaxResult.error(403, e.getMessage());
}
SysDept dept = deptService.selectDeptById(deptId);
return AjaxResult.success(dept);
}5.1.1. Backend Fix
- springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysUserController.java file
/\*\*
_ Get details by user ID
_/
@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, "Visitors are not allowed to access user information!");
}
if (StringUtils.isNotNull(userId))
{
try {
userService.checkUserDataScope(userId);
} catch (ServiceException e) {
return AjaxResult.error(403, e.getMessage());
}
SysUser sysUser = userService.selectUserById(userId);
// Non-admin: filter out admin role information
if (!SysUser.isAdmin(currentUserId)) {
List<SysRole> filterRoles = sysUser.getRoles().stream()
.filter(r -> !r.isAdmin())
.collect(Collectors.toList());
sysUser.setRoles(filterRoles);
}
// Wrap data
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);
}
// Filter role/post lists
List<SysRole> roles = roleService.selectRoleAll();
ajax.put("roles", SysUser.isAdmin(currentUserId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
// ========== 8. Post list: only use selectPostListByUserId (adapts to existing methods) ==========
if (SysUser.isAdmin(currentUserId)) {
// Admin: return all posts
ajax.put("posts", postService.selectPostAll());
} else {
// Non-admin: return only the current login user's own posts
ajax.put("posts", postService.selectPostListByUserId(currentUserId));
}
return ajax;
}
/**
* Get authorized roles by user ID
*/
@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, "Visitors are not allowed to access user authorized role information!");
}
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 // Admin: return all authorized roles
: roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()); // Non-admin: filter out admin roles
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
/**
* Check whether there is data permission for the department
*
* @param deptId department 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("You do not have permission to access department data!");
}
boolean hasPermission = accessibleDepts.stream()
.anyMatch(dept -> dept.getDeptId().equals(deptId));
if (!hasPermission) {
throw new ServiceException("You do not have permission to access this department's data!");
}
SysDept targetDept = this.selectDeptById(deptId);
if (targetDept == null) {
throw new ServiceException("Department does not exist!");
}
}- springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysPostServiceImpl.java file
/**
* Query the post information list
*
* @param post post information
* @return post information list
*/
@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
/\*\*
_ Query role data by condition with pagination
_
_ @param role role information
_ @return role data list
\*/
@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
/**
* Query the user list by condition with pagination
*
* @param user user information
* @return user information list
*/
@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);
}
/**
* Check whether there is data permission for the user
*
* @param userId user id
*/
@Override
public void checkUserDataScope(Long userId)
{
Long currentUserId = SecurityUtils.getUserId();
// Admin: allow directly
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("Access to super administrator information is forbidden!");
}
if (!hasPermission) {
throw new ServiceException("You do not have permission to access user data!");
}
}5.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".
5.2.1. Case 1: If the code repository license has not expired, simply update the main branch code
5.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
/**
* Check whether there is data permission for the department
*
* @param deptId department 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("You do not have permission to access department data!");
}
if (null == curUser.getDeptId()) {
throw new ServiceException("You do not have permission to access department data!");
} 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("You do not have permission to access department data!");
}
} 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("You do not have permission to access department data!");
}
}
}
}
}- com.fastbee.controller.system.SysDeptController#list method
/**
* Get the organization list
*/
@ApiOperation("Get the organization list")
@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
/**
* Get details by organization ID
*/
@ApiOperation("Get details by organization ID")
@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
/**
* Get organization roles
* @param deptId organization 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
/**
* Check whether there is data permission for the user
*
* @param userId user 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("You do not have permission to access user data!");
}
SysUser user = SpringUtils.getAopProxy(this).selectUserById(userId);
if (ObjectUtil.isNull(user)) {
throw new ServiceException("You do not have permission to access user data!");
}
if (null == curUser.getDeptId() || null == user.getDeptId()) {
throw new ServiceException("You do not have permission to access user data!");
}
String dataScope = getDataScope();
if (DataScopeAspect.DATA_SCOPE_SELF.equals(dataScope)) {
throw new ServiceException("You do not have permission to access user data!");
} else if (DataScopeAspect.DATA_SCOPE_DEPT.equals(dataScope)) {
if (!curUser.getDeptId().equals(user.getDeptId())) {
throw new ServiceException("You do not have permission to access user data!");
}
} 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("You do not have permission to access user data!");
}
}
}
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("You do not have permission to access user data!");
}
}- com.fastbee.controller.system.SysUserController#list method
/**
* Get the user list
*/
@ApiOperation("Get the paged user list")
@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("Export the user list")
@Log(title = "User Management", 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(), "User Data");
}- com.fastbee.controller.system.SysUserController#authRole method
/**
* Get authorized roles by user ID
*/
@ApiOperation("Get authorized roles by user ID")
@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
/**
* Authorize roles for a user
*/
@ApiOperation("Authorize roles for a user")
@PreAuthorize("@ss.hasPermi('system:user:edit')")
@Log(title = "User Management", 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("Please check the role id");
}
sysUserService.insertUserAuth(userId, roleIds);
return success();
}- com.fastbee.controller.system.SysUserController#deptTree method
/**
* Get the department tree list
*/
@ApiOperation("Get the department tree list")
@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
/**
* Get the terminal user list
* @param user user information
* @return com.fastbee.common.core.page.TableDataInfo
*/
@ApiOperation("Get the paged user list")
@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
/**
* Get all non-admin users of the current organization by organization 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
/**
* Check whether there is data permission for the role
*
* @param roleId role 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("You do not have permission to access role data!");
} 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("You do not have permission to access role data!");
}
Long bindDeptId = sysRoleDept.getDeptId();
if (DataScopeAspect.DATA_SCOPE_SELF.equals(dataScope)) {
throw new ServiceException("You do not have permission to access role data!");
} else if (DataScopeAspect.DATA_SCOPE_DEPT.equals(dataScope)) {
if (!curUser.getDeptId().equals(bindDeptId)) {
throw new ServiceException("You do not have permission to access role data!");
}
} 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("You do not have permission to access role data!");
}
}
}
}
}- com.fastbee.system.service.impl.SysRoleServiceImpl#selectRoleList method
/**
* Query role data by condition with pagination
*
* @param role role information
* @return role data list
*/
@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("Get the paged role list")
@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);
// Sort by the roleSort field
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("Export the role list")
@Log(title = "Role Management", 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, "Role Data");
}- com.fastbee.controller.system.SysRoleController#optionselect method
/**
* Get the role select box list
*/
@ApiOperation("Get the role select box list")
@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
/**
* Query the allocated user role list
*/
@ApiOperation("Query the allocated user role list")
@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
/**
* Query the unallocated user role list
*/
@ApiOperation("Query the unallocated user role list")
@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
/**
* Cancel an authorized user
*/
@ApiOperation("Cancel an authorized user")
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "Role Management", 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
/**
* Batch cancel authorized users
*/
@ApiOperation("Batch cancel authorized users")
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "Role Management", 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
/**
* Get the department tree list for the role
*/
@ApiOperation("Get the department tree list for the role")
@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;
}5.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
/**
* Check whether there is data permission for the department
*
* @param deptId department 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("You do not have permission to access department data!");
}
if (null == curUser.getDeptId()) {
throw new ServiceException("You do not have permission to access department data!");
} else {
if (!curUser.getDeptId().equals(deptId)) {
throw new ServiceException("You do not have permission to access department data!");
}
}
}- com.fastbee.controller.system.SysDeptController#list method
/**
* Get the organization list
*/
@ApiOperation("Get the organization list")
@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
/**
* Get organization roles
* @param deptId organization 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
/**
* Check whether there is data permission for the user
*
* @param userId user 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("You do not have permission to access user data!");
}
SysUser user = SpringUtils.getAopProxy(this).selectUserById(userId);
if (ObjectUtil.isNull(user)) {
throw new ServiceException("You do not have permission to access user data!");
}
if (null == curUser.getDeptId() || null == user.getDeptId()) {
throw new ServiceException("You do not have permission to access user data!");
}
if (!curUser.getDeptId().equals(user.getDeptId())) {
throw new ServiceException("You do not have permission to access user data!");
}
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("You do not have permission to access user data!");
}
}- com.fastbee.controller.system.SysUserController#list method
/**
* Get the user list
*/
@ApiOperation("Get the paged user list")
@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("Export the user list")
@Log(title = "User Management", 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(), "User Data");
}- com.fastbee.controller.system.SysUserController#authRole method
/**
* Get authorized roles by user ID
*/
@ApiOperation("Get authorized roles by user ID")
@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
/**
* Authorize roles for a user
*/
@ApiOperation("Authorize roles for a user")
@PreAuthorize("@ss.hasPermi('system:user:edit')")
@Log(title = "User Management", 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("Please check the role id");
}
sysUserService.insertUserAuth(userId, roleIds);
return success();
}- com.fastbee.controller.system.SysUserController#deptTree method
/**
* Get the department tree list
*/
@ApiOperation("Get the department tree list")
@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
/**
* Get the terminal user list
* @param user user information
* @return com.fastbee.common.core.page.TableDataInfo
*/
@ApiOperation("Get the paged user list")
@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
/**
* Check whether there is data permission for the role
*
* @param roleId role 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("You do not have permission to access role data!");
} 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("You do not have permission to access role data!");
}
if (!curUser.getDeptId().equals(sysRoleDept.getDeptId())) {
throw new ServiceException("You do not have permission to access role data!");
}
}
}- com.fastbee.controller.system.SysRoleController#list method
@ApiOperation("Get the paged role list")
@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);
// Sort by the roleSort field
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("Export the role list")
@Log(title = "Role Management", 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, "Role Data");
}- com.fastbee.controller.system.SysRoleController#optionselect method
/**
* Get the role select box list
*/
@ApiOperation("Get the role select box list")
@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
/**
* Query the allocated user role list
*/
@ApiOperation("Query the allocated user role list")
@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
/**
* Query the unallocated user role list
*/
@ApiOperation("Query the unallocated user role list")
@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
/**
* Cancel an authorized user
*/
@ApiOperation("Cancel an authorized user")
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "Role Management", 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
/**
* Batch cancel authorized users
*/
@ApiOperation("Batch cancel authorized users")
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "Role Management", 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
/**
* Get the department tree list for the role
*/
@ApiOperation("Get the department tree list for the role")
@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;
}
