Compare commits

..

No commits in common. "a9c7236a4e65320e05405a68201601532875bb8d" and "be080ffb3add3d9495fed78a49270e2a92035f20" have entirely different histories.

80 changed files with 502 additions and 1297 deletions

23
pom.xml
View File

@ -5,7 +5,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.0</version>
<version>3.3.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zsc.edu</groupId>
@ -28,14 +28,14 @@
</scm>
<properties>
<java.version>17</java.version>
<mybatis-plus.version>3.5.9</mybatis-plus.version>
<mybatis-plus.version>3.5.8</mybatis-plus.version>
<mapstruct.version>1.6.2</mapstruct.version>
</properties>
<dependencies>
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-data-mongodb</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
@ -91,11 +91,6 @@
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-jsqlparser</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
@ -131,6 +126,12 @@
<artifactId>commons-codec</artifactId>
<version>1.17.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.21</version>
</dependency>
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>

View File

@ -1,93 +1,61 @@
package com.zsc.edu.gateway;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zsc.edu.gateway.modules.system.entity.Authority;
import com.zsc.edu.gateway.modules.system.entity.Dept;
import com.zsc.edu.gateway.modules.system.entity.Role;
import com.zsc.edu.gateway.modules.system.entity.User;
import com.zsc.edu.gateway.modules.system.dto.RoleDto;
import com.zsc.edu.gateway.modules.system.entity.*;
import com.zsc.edu.gateway.modules.system.repo.DeptRepository;
import com.zsc.edu.gateway.modules.system.repo.RoleRepository;
import com.zsc.edu.gateway.modules.system.repo.UserRepository;
import com.zsc.edu.gateway.modules.system.service.AuthorityService;
import com.zsc.edu.gateway.modules.system.service.DeptService;
import com.zsc.edu.gateway.modules.system.repo.UserRolesRepository;
import com.zsc.edu.gateway.modules.system.service.RoleService;
import com.zsc.edu.gateway.modules.system.service.UserService;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* 系统初始化程序
*
* @author harry_yao
* @author zhuang
*/
@AllArgsConstructor
@RequiredArgsConstructor
@Component
@Profile("!test")
public class FirstTimeInitializer implements CommandLineRunner {
private final AuthorityService authorityService;
private final UserService userService;
private final RoleService roleService;
private final DeptService deptService;
private final DeptRepository deptRepo;
private final RoleRepository roleRepo;
private final RoleService roleService;
private final UserRolesRepository userRolesRepo;
private final UserRepository userRepo;
private final PasswordEncoder passwordEncoder;
@Override
public void run(String... args) {
// if (authorityService.count() == 0L) {
// Authority userPerm = new Authority(null, "用户模块", "用户管理", "SYSTEM:USER", true, null);
// Authority rolePerm = new Authority(null, "角色模块", "角色管理", "SYSTEM:ROLE", true, null);
// Authority deptPerm = new Authority(null, "部门模块", "部门管理", "SYSTEM:DEPT", true, null);
// Authority AuthorityPerm = new Authority(null, "权限模块", "权限管理", "SYSTEM:AUTHORITY", true, null);
// authorityService.saveBatch(List.of(userPerm, rolePerm, deptPerm, AuthorityPerm));
// List<Authority> authorities = new ArrayList<>();
// authorities.add(new Authority(userPerm.getId(), "用户管理", "用户列表", "SYSTEM:USER:QUERY", true, null));
// authorities.add(new Authority(userPerm.getId(), "用户管理", "用户新增", "SYSTEM:USER:CREATE",true, null));
// authorities.add(new Authority(userPerm.getId(), "用户管理", "用户修改", "SYSTEM:USER:UPDATE",true, null));
// authorities.add(new Authority(userPerm.getId(), "用户管理", "用户删除", "SYSTEM:USER:DELETE",true, null));
// authorities.add(new Authority(rolePerm.getId(), "角色管理", "角色列表", "SYSTEM:ROLE:QUERY", true, null));
// authorities.add(new Authority(rolePerm.getId(), "角色管理", "角色新增", "SYSTEM:ROLE:CREATE",true, null));
// authorities.add(new Authority(rolePerm.getId(), "角色管理", "角色修改", "SYSTEM:ROLE:UPDATE",true, null));
// authorities.add(new Authority(rolePerm.getId(), "角色管理", "角色删除", "SYSTEM:ROLE:DELETE",true, null));
// authorities.add(new Authority(deptPerm.getId(), "部门管理", "部门列表", "SYSTEM:DEPT:QUERY", true, null));
// authorities.add(new Authority(deptPerm.getId(), "部门管理", "部门新增", "SYSTEM:DEPT:CREATE",true, null));
// authorities.add(new Authority(deptPerm.getId(), "部门管理", "部门修改", "SYSTEM:DEPT:UPDATE",true, null));
// authorities.add(new Authority(deptPerm.getId(), "部门管理", "部门删除", "SYSTEM:DEPT:DELETE",true, null));
// authorities.add(new Authority(AuthorityPerm.getId(), "权限管理", "权限列表", "SYSTEM:AUTHORITY:QUERY", true, null));
// authorities.add(new Authority(AuthorityPerm.getId(), "权限管理", "权限新增", "SYSTEM:AUTHORITY:CREATE",true, null));
// authorities.add(new Authority(AuthorityPerm.getId(), "权限管理", "权限修改", "SYSTEM:AUTHORITY:UPDATE",true, null));
// authorities.add(new Authority(AuthorityPerm.getId(), "权限管理", "权限删除", "SYSTEM:AUTHORITY:DELETE",true, null));
// authorityService.saveBatch(authorities);
// }
if (roleService.count() == 0L) {
Role admin = new Role();
admin.setName("管理员");
admin.setEnabled(true);
roleService.save(admin);
}
if (deptService.count() == 0L) {
Dept dept = new Dept();
dept.setName("总公司");
deptService.save(dept);
}
if (userService.count() == 0L) {
Dept dept = deptService.getOne(new QueryWrapper<>());
Role role = roleService.getOne(new QueryWrapper<>());
User user = new User();
user.setUsername("admin");
user.setPassword(passwordEncoder.encode("admin"));
user.setPhone("15913375741");
user.setEmail("admin@zsc.edu.cn");
user.setName("admin");
user.setRoleId(role.getId());
user.setDeptId(dept.getId());
userService.save(user);
}
@Override
public void run(String... args) throws Exception {
Dept dept1 = new Dept();
Role role = new Role();
if (deptRepo.selectCount(new QueryWrapper<>()) == 0) {
dept1.setName("管理部门");
deptRepo.insert(dept1);
}
if (roleRepo.selectCount(new QueryWrapper<>()) == 0) {
RoleDto dto = new RoleDto();
dto.setName("超级管理员");
// dto.setAuthorities(new HashSet<>(Arrays.asList(Authority.values())));
role = roleService.create(dto);
}
if (userRepo.selectCount(new QueryWrapper<>()) == 0) {
User user = new User();
user.setUsername("管理员");
user.setPassword(passwordEncoder.encode("123456"));
user.setEnableState(true);
user.setPhone("13827993921");
user.setEmail("123@qq.com");
user.setDeptId(dept1.getId());
user.setRoleId(role.getId());
userRepo.insert(user);
}
}
}

View File

@ -1,16 +0,0 @@
package com.zsc.edu.gateway.framework.json;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JsonConfig {
@Bean
public Jackson2ObjectMapperBuilderCustomizer customizer() {
return builder -> builder.serializationInclusion(JsonInclude.Include.NON_NULL)
.serializationInclusion(JsonInclude.Include.NON_EMPTY);
}
}

View File

@ -1,18 +1,13 @@
package com.zsc.edu.gateway.framework.security;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Map;
/**
* @author harry_yao
@ -21,10 +16,12 @@ import java.util.Map;
@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
// private final OnlineUserService onlineUserService;
// private final UserService userService;
// private final LoginLogService loginLogService;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// response.sendRedirect("/api/rest/user/me");
request.getRequestDispatcher("/api/rest/user/me").forward(request, response);
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
// Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// String sessionId = request.getRequestedSessionId();
// String remoteAddr = request.getRemoteAddr();

View File

@ -1,33 +1,30 @@
package com.zsc.edu.gateway.framework.security;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zsc.edu.gateway.exception.ExceptionResult;
import com.zsc.edu.gateway.framework.SpringBeanUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;
/**
* @author harry_yao
*/
@Component
public class CustomSessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException {
ObjectMapper objectMapper = SpringBeanUtil.getBean(ObjectMapper.class);
HttpServletResponse response = event.getResponse();
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType("application/json;charset=utf-8");
ObjectMapper objectMapper = new ObjectMapper();
response.getWriter().print(objectMapper.writeValueAsString(Map.of(
"msg", "会话已过期(有可能是您同时登录了太多的太多的客户端)",
"code", HttpStatus.UNAUTHORIZED.value(),
"timestamp", LocalDateTime.now()
)));
ExceptionResult result = new ExceptionResult("会话已过期(有可能是您同时登录了太多的太多的客户端)",
HttpStatus.UNAUTHORIZED.value(),
LocalDateTime.now());
response.getWriter().print(objectMapper.writeValueAsString(result));
response.flushBuffer();
}
}
}

View File

@ -1,12 +1,8 @@
package com.zsc.edu.gateway.framework.security;
import com.zsc.edu.gateway.exception.StateException;
import com.zsc.edu.gateway.modules.system.entity.Menu;
import com.zsc.edu.gateway.modules.system.entity.RoleAuthority;
import com.zsc.edu.gateway.modules.system.entity.User;
import com.zsc.edu.gateway.modules.system.repo.AuthorityRepository;
import com.zsc.edu.gateway.modules.system.repo.MenuRepository;
import com.zsc.edu.gateway.modules.system.repo.RoleAuthoritiesRepository;
import com.zsc.edu.gateway.modules.system.repo.UserRepository;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
@ -15,10 +11,6 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author harry_yao
*/
@ -27,9 +19,7 @@ import java.util.stream.Collectors;
public class JpaUserDetailsServiceImpl implements UserDetailsService {
private final UserRepository userRepo;
// private final RoleAuthoritiesRepository roleAuthoritiesRepository;
private final AuthorityRepository authorityRepository;
private final MenuRepository menuRepository;
@Override
@Transactional(rollbackFor = Exception.class)
@ -39,10 +29,18 @@ public class JpaUserDetailsServiceImpl implements UserDetailsService {
throw new StateException("用户 '" + username + "' 已被禁用!请联系管理员");
}
// List<RoleAuthority> roleAuthorities= roleAuthoritiesRepository.selectByRoleId(user.getRoleId());
user.role.authorities = authorityRepository.selectAuthoritiesByRoleId(user.getRoleId());
List<Menu> menus = menuRepository.selectByRoleId(user.getRoleId());
Set<String> permissions = menus.stream().map(Menu::getPermissions).collect(Collectors.toSet());
return UserDetailsImpl.from(user, permissions);
// =roleAuthorities.stream()
// .map(i -> Authority.valueOf(i.getAuthority()))
// .collect(Collectors.toSet());
// .orElseThrow(() ->
// new UsernameNotFoundException("用户 '" + username + "' 不存在!")
// );
// user.getIdentities().stream().filter(identity -> identity.role.enableState == EnableState.启用)
// .forEach(identity -> Hibernate.initialize(identity.role.roleAuthorities));
return UserDetailsImpl.from(user);
}
}

View File

@ -14,7 +14,6 @@ import java.io.IOException;
import java.util.Map;
public class JsonAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
@ -26,12 +25,12 @@ public class JsonAuthenticationFilter extends UsernamePasswordAuthenticationFilt
Map map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
String username = map.get("username").toString();
String password = map.get("password").toString();
username = (username != null) ? username : "";
username = username.trim();
password = (password != null) ? password : "";
password = password.trim();
UsernamePasswordAuthenticationToken authRequest =
UsernamePasswordAuthenticationToken.unauthenticated(username, password);
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
@ -41,4 +40,6 @@ public class JsonAuthenticationFilter extends UsernamePasswordAuthenticationFilt
}
return super.attemptAuthentication(request, response);
}
}

View File

@ -1,41 +1,19 @@
package com.zsc.edu.gateway.framework.security;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.Objects;
import java.util.Optional;
/**
* @author Yao
*/
public class SecurityUtil {
public static UserDetailsImpl getUserInfo() {
return getPrincipal();
}
private static UserDetailsImpl getPrincipal() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (Objects.isNull(authentication)) {
return new UserDetailsImpl();
}
return (UserDetailsImpl) authentication.getPrincipal();
}
public static Optional<String> getCurrentAuditor() {
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication instanceof AnonymousAuthenticationToken) {
return Optional.of("system");
} else {
if (authentication == null) {
return Optional.of("system");
}
UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal();
return Optional.of(user.getUsername());
}
} catch (Exception ex) {
// log.error("get user Authentication failed: " + ex.getMessage(), ex);
return Optional.of("system");
}
}
}

View File

@ -8,21 +8,15 @@ import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.util.AntPathMatcher;
import javax.sql.DataSource;
@ -30,7 +24,7 @@ import javax.sql.DataSource;
* @author harry_yao
*/
@AllArgsConstructor
@EnableMethodSecurity
//@EnableMethodSecurity
@Configuration
public class SpringSecurityConfig {
@ -41,22 +35,15 @@ public class SpringSecurityConfig {
private final CustomAccessDeniedHandler customAccessDeniedHandler;
private final SessionRegistry sessionRegistry;
private final SecurityBeanConfig securityBeanConfig;
private final CustomSessionInformationExpiredStrategy customSessionInformationExpiredStrategy;
@Resource
private final DataSource dataSource;
// @Bean
// public BCryptPasswordEncoder bCryptPasswordEncoder() {
// return new BCryptPasswordEncoder();
// };
@Bean
public PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
tokenRepository.setDataSource(dataSource);
return tokenRepository;
}
@Bean
@ -84,48 +71,9 @@ public class SpringSecurityConfig {
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/api/rest/user/menu","/api/rest/user/register","/api/rest/user/send-email").permitAll()
.requestMatchers(HttpMethod.GET, "/api/rest/user/me","/api/rest/user/register","/api/rest/user/send-email").permitAll()
.requestMatchers(HttpMethod.POST, "/api/rest/user/login","/api/rest/user/register").permitAll()
.requestMatchers("/api/rest/user/me").permitAll()
.requestMatchers("/api/**").authenticated()
)
// 不用注解直接通过判断路径实现动态访问权限
// .requestMatchers("/api/**").access((authentication, object) -> {
// //表示请求的 URL 地址和数据库的地址是否匹配上了
// boolean isMatch = false;
// //获取当前请求的 URL 地址
// String requestURI = object.getRequest().getRequestURI();
// List<MenuWithRoleVO> menuWithRole = menuService.getMenuWithRole();
// for (MenuWithRoleVO m : menuWithRole) {
// AntPathMatcher antPathMatcher = new AntPathMatcher();
// if (antPathMatcher.match(m.getUrl(), requestURI)) {
// isMatch = true;
// //说明找到了请求的地址了
// //这就是当前请求需要的角色
// List<Role> roles = m.getRoles();
// //获取当前登录用户的角色
// Collection<? extends GrantedAuthority> authorities = authentication.get().getAuthorities();
// for (GrantedAuthority authority : authorities) {
// for (Role role : roles) {
// if (authority.getAuthority().equals(role.getName())) {
// //说明当前登录用户具备当前请求所需要的角色
// return new AuthorizationDecision(true);
// }
// }
// }
// }
// }
// if (!isMatch) {
// //说明请求的 URL 地址和数据库的地址没有匹配上对于这种请求统一只要登录就能访问
// if (authentication.get() instanceof AnonymousAuthenticationToken) {
// return new AuthorizationDecision(false);
// } else {
// //说明用户已经认证了
// return new AuthorizationDecision(true);
// }
// }
// return new AuthorizationDecision(false);
// }))
.requestMatchers("/api/**").authenticated())
.addFilterAt(jsonAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.formLogin(form -> form
.loginPage("/user/login")
@ -147,7 +95,7 @@ public class SpringSecurityConfig {
.sessionManagement(session -> session
.maximumSessions(3)
.sessionRegistry(sessionRegistry)
.expiredSessionStrategy(customSessionInformationExpiredStrategy))
.expiredSessionStrategy(new CustomSessionInformationExpiredStrategy()))
.build();
}

View File

@ -33,9 +33,8 @@ public class UserDetailsImpl implements UserDetails {
public Dept dept;
public Role role;
public Set<Authority> authorities;
public Set<String> permissions;
public UserDetailsImpl(Long id, String username, String password, String name, Boolean enableState, Dept dept, Role role, Set<Authority> authorities, Set<String> permissions) {
public UserDetailsImpl(Long id, String username, String password, String name, Boolean enableState, Dept dept, Role role, Set<Authority> authorities) {
this.id = id;
this.username = username;
this.password = password;
@ -44,10 +43,9 @@ public class UserDetailsImpl implements UserDetails {
this.dept = dept;
this.role = role;
this.authorities = authorities;
this.permissions = permissions;
}
public static UserDetailsImpl from(User user, Set<String> permissions) {
public static UserDetailsImpl from(User user) {
return new UserDetailsImpl(
user.id,
user.username,
@ -56,15 +54,14 @@ public class UserDetailsImpl implements UserDetails {
user.enableState,
user.dept,
user.role,
user.role.authorities,
permissions
user.role.authorities
);
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
// return authorities.stream().map(authority -> new SimpleGrantedAuthority(authority.getName())).collect(Collectors.toSet());
return permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
return authorities.stream().map(authority -> new SimpleGrantedAuthority(authority.getName())).collect(Collectors.toSet());
}
@Override

View File

@ -52,11 +52,6 @@ public class Attachment implements Serializable {
public LocalDateTime uploadTime;
/**
* 部门ID(权限)
*/
public Long deptId;
/**
* 文件下载链接
*/

View File

@ -76,11 +76,6 @@ public class Device extends BaseEntity {
*/
public Long productId;
/**
* 部门ID(权限)
*/
public Long deptId;
/**
* 所属产品
*/

View File

@ -1,5 +1,7 @@
package com.zsc.edu.gateway.modules.iot.device.service.impl;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
@ -102,6 +104,10 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceRepository, Device> imp
throw new ConstraintException("deviceName", dto.getName(), "设备名称已存在");
}
mapper.convert(dto, device);
String clientId = device.getClientId();
if (redisUtils.hasKey("record:device:properties:" + clientId)) {
redisUtils.set("record:device:properties:" + clientId, String.valueOf(JSONObject.parseObject(device.getProperties())));
}
updateById(device);
return device;
}
@ -138,6 +144,8 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceRepository, Device> imp
public Boolean serve(DeviceServeDto dto) {
Device device = baseMapper.findByClientIdAndStateAndOnline(dto.clientId, Device.Status.ACTIVATED, true);
if (device != null) {
JSONObject json = (JSONObject) JSON.toJSON(dto);
json.put("type", "serve");
// amqpTemplate.convertAndSend(exchange, "send", json);
redisUtils.set("serve:sendTime:" + dto.serveName + ":" + dto.clientId, String.valueOf(new Date()));
return true;

View File

@ -32,7 +32,7 @@ public class ProductController {
* 创建产品
*
* @param dto 创建的产品
* @return 新的产品
* @return
*/
@PostMapping
public Product create(@RequestBody ProductDto dto) {

View File

@ -0,0 +1,20 @@
package com.zsc.edu.gateway.modules.iot.product.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* @author zhuang
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@TableName("iot_product_param")
public class ProductParam {
private Long productId;
private Long paramId;
}

View File

@ -0,0 +1,10 @@
package com.zsc.edu.gateway.modules.iot.product.repo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zsc.edu.gateway.modules.iot.product.entity.ProductParam;
/**
* @author zhuang
*/
public interface ProductParamRepository extends BaseMapper<ProductParam> {
}

View File

@ -15,6 +15,8 @@ public interface ProductService extends IService<Product> {
Product update(ProductDto dto, Long id);
// Page<Product> page(Page<Product> page, ProductQuery query);
Product detail(Long id);
boolean delete(Long id);

View File

@ -0,0 +1,17 @@
package com.zsc.edu.gateway.modules.iot.tsl.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;
/**
* @author zhuang
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@TableName("iot_event_param")
public class EventParam {
private Long eventId;
private Long paramId;
}

View File

@ -0,0 +1,21 @@
package com.zsc.edu.gateway.modules.iot.tsl.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* @author zhuang
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@TableName("iot_serve_param")
public class ServeParam {
private Long serveId;
private Long paramId;
}

View File

@ -0,0 +1,10 @@
package com.zsc.edu.gateway.modules.iot.tsl.repo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zsc.edu.gateway.modules.iot.tsl.entity.EventParam;
/**
* @author zhuang
*/
public interface EventParamRepository extends BaseMapper<EventParam> {
}

View File

@ -0,0 +1,7 @@
package com.zsc.edu.gateway.modules.iot.tsl.repo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zsc.edu.gateway.modules.iot.tsl.entity.ServeParam;
public interface ServeParamRepository extends BaseMapper<ServeParam> {
}

View File

@ -15,6 +15,8 @@ public interface EventService extends IService<Event> {
Event update(EventDto dto, Long id);
// IPage<Event> page(Page<Event> page, EventQuery query);
Event detail(Long id);
boolean delete(Long id);

View File

@ -1,8 +1,14 @@
package com.zsc.edu.gateway.modules.iot.tsl.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.zsc.edu.gateway.modules.iot.product.dto.ProductDto;
import com.zsc.edu.gateway.modules.iot.product.entity.ProductParam;
import com.zsc.edu.gateway.modules.iot.tsl.dto.EventDto;
import com.zsc.edu.gateway.modules.iot.tsl.dto.ParamDto;
import com.zsc.edu.gateway.modules.iot.tsl.dto.ServeDto;
import com.zsc.edu.gateway.modules.iot.tsl.entity.EventParam;
import com.zsc.edu.gateway.modules.iot.tsl.entity.Param;
import com.zsc.edu.gateway.modules.iot.tsl.entity.ServeParam;
import java.util.List;
@ -10,10 +16,7 @@ import java.util.List;
* @author zhuang
*/
public interface ParamService extends IService<Param> {
List<Long> paramCreate(List<ParamDto> params);
Boolean create(List<ParamDto> params, Long id, Param.ForeignType foreignType);
Boolean update(List<ParamDto> paramDto, Long id);
Boolean delete(Long id);
boolean paramUpdate(List<ParamDto> paramDto, List<Long> paramIds);
}

View File

@ -15,6 +15,8 @@ public interface ServeService extends IService<Serve> {
Serve update(ServeDto dto, Long id);
// IPage<Serve> page(Page<Serve> page, ServeQuery query);
Serve detail(Long id);
Boolean delete(Long id);

View File

@ -1,17 +1,30 @@
package com.zsc.edu.gateway.modules.iot.tsl.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.edu.gateway.exception.ConstraintException;
import com.zsc.edu.gateway.modules.iot.tsl.dto.EventDto;
import com.zsc.edu.gateway.modules.iot.tsl.dto.ParamDto;
import com.zsc.edu.gateway.modules.iot.tsl.entity.Event;
import com.zsc.edu.gateway.modules.iot.tsl.entity.EventParam;
import com.zsc.edu.gateway.modules.iot.tsl.entity.Param;
import com.zsc.edu.gateway.modules.iot.tsl.mapper.EventMapper;
import com.zsc.edu.gateway.modules.iot.tsl.mapper.ParamMapper;
import com.zsc.edu.gateway.modules.iot.tsl.query.EventQuery;
import com.zsc.edu.gateway.modules.iot.tsl.repo.EventParamRepository;
import com.zsc.edu.gateway.modules.iot.tsl.repo.EventRepository;
import com.zsc.edu.gateway.modules.iot.tsl.repo.ParamRepository;
import com.zsc.edu.gateway.modules.iot.tsl.service.EventService;
import com.zsc.edu.gateway.modules.iot.tsl.service.ParamService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author Yao
*/
@ -19,6 +32,9 @@ import org.springframework.stereotype.Service;
@AllArgsConstructor
public class EventServiceImpl extends ServiceImpl<EventRepository, Event> implements EventService {
private final EventMapper mapper;
private final ParamMapper paramMapper;
private final ParamRepository paramRepo;
private final EventParamRepository eventParamRepo;
private final ParamService paramService;
/**
@ -31,7 +47,10 @@ public class EventServiceImpl extends ServiceImpl<EventRepository, Event> implem
}
Event event = mapper.toEntity(dto);
save(event);
paramService.create(dto.getOutputs(), event.getId(), Param.ForeignType.EVENT);
List<EventParam> eventParams = paramService.paramCreate(dto.getOutputs()).stream()
.map(paramId -> new EventParam(event.getId(), paramId))
.toList();
eventParamRepo.insert(eventParams);
return event;
}
/**
@ -42,9 +61,24 @@ public class EventServiceImpl extends ServiceImpl<EventRepository, Event> implem
Event event = baseMapper.selectById(id);
mapper.convert(dto, event);
updateById(event);
paramService.update(dto.getOutputs(), event.getId());
paramService.paramUpdate(dto.getOutputs(),
eventParamRepo.selectList(new LambdaQueryWrapper<EventParam>()
.eq(EventParam::getEventId, event.getId()))
.stream()
.map(EventParam::getParamId)
.collect(Collectors.toList()));
return event;
}
/**
* 分页查询物模型事件
*
* @param query 查询表单
* @param page 分页参数
*/
// @Override
// public IPage<Event> page(Page<Event> page, EventQuery query) {
// return baseMapper.page(page, query);
// }
/**
* 查询详情
@ -62,6 +96,16 @@ public class EventServiceImpl extends ServiceImpl<EventRepository, Event> implem
@Override
public boolean delete(Long id) {
removeById(id);
return paramService.delete(id);
LambdaQueryWrapper<EventParam> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(EventParam::getEventId, id);
List<EventParam> eventParams = eventParamRepo.selectList(wrapper);
if (!eventParams.isEmpty()) {
List<Long> paramIds = eventParams.stream()
.map(EventParam::getParamId)
.toList();
paramRepo.deleteByIds(paramIds);
}
eventParamRepo.delete(wrapper);
return true;
}
}

View File

@ -2,16 +2,24 @@ package com.zsc.edu.gateway.modules.iot.tsl.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.edu.gateway.modules.iot.product.dto.ProductDto;
import com.zsc.edu.gateway.modules.iot.product.entity.ProductParam;
import com.zsc.edu.gateway.modules.iot.product.repo.ProductParamRepository;
import com.zsc.edu.gateway.modules.iot.tsl.dto.ParamDto;
import com.zsc.edu.gateway.modules.iot.tsl.dto.ServeDto;
import com.zsc.edu.gateway.modules.iot.tsl.entity.EventParam;
import com.zsc.edu.gateway.modules.iot.tsl.entity.Param;
import com.zsc.edu.gateway.modules.iot.tsl.entity.ServeParam;
import com.zsc.edu.gateway.modules.iot.tsl.mapper.ParamMapper;
import com.zsc.edu.gateway.modules.iot.tsl.repo.EventParamRepository;
import com.zsc.edu.gateway.modules.iot.tsl.repo.ParamRepository;
import com.zsc.edu.gateway.modules.iot.tsl.repo.ServeParamRepository;
import com.zsc.edu.gateway.modules.iot.tsl.service.ParamService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@ -23,24 +31,24 @@ import java.util.stream.IntStream;
public class ParamServiceImpl extends ServiceImpl<ParamRepository, Param> implements ParamService {
private final ParamMapper mapper;
private final ParamMapper paramMapper;
private final EventParamRepository eventParamRepository;
private final ProductParamRepository productParamRepository;
private final ServeParamRepository serveParamRepository;
@Override
public Boolean create(List<ParamDto> params, Long id, Param.ForeignType foreignType) {
public List<Long> paramCreate(List<ParamDto> params) {
List<Long> paramIds = new ArrayList<>();
List<Param> paramsToInsert = params.stream()
.map(dto -> {
Param param = mapper.toEntity(dto);
param.setForeignId(id);
param.setForeignType(foreignType);
return param;
})
.map(mapper::toEntity)
.collect(Collectors.toList());
baseMapper.insert(paramsToInsert);
return true;
paramsToInsert.forEach(param -> paramIds.add(param.getId()));
return paramIds;
}
@Override
public Boolean update(List<ParamDto> paramDto, Long id) {
List<Param> params = baseMapper.selectList(new LambdaQueryWrapper<Param>()
.eq(Objects.nonNull(id), Param::getForeignId, id));
public boolean paramUpdate(List<ParamDto> paramDto, List<Long> paramIds) {
List<Param> params = baseMapper.selectByIds(paramIds);
if (!params.isEmpty() && !paramDto.isEmpty()) {
List<Param> updatedParams = IntStream.range(0, Math.min(params.size(), paramDto.size()))
.parallel()
@ -56,10 +64,5 @@ public class ParamServiceImpl extends ServiceImpl<ParamRepository, Param> implem
return true;
}
@Override
public Boolean delete(Long id) {
return baseMapper.delete(new LambdaQueryWrapper<Param>()
.eq(Objects.nonNull(id), Param::getForeignId, id)) > 0;
}
//TODO 整合方法方法一保持现状但是会有多个联表多个entity多个repo方法二建新联表其中values(product_id,serve_id,event_id,param_id)一表联三表
}

View File

@ -1,11 +1,18 @@
package com.zsc.edu.gateway.modules.iot.tsl.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.edu.gateway.exception.ConstraintException;
import com.zsc.edu.gateway.modules.iot.tsl.dto.ParamDto;
import com.zsc.edu.gateway.modules.iot.tsl.dto.ServeDto;
import com.zsc.edu.gateway.modules.iot.tsl.entity.*;
import com.zsc.edu.gateway.modules.iot.tsl.mapper.ParamMapper;
import com.zsc.edu.gateway.modules.iot.tsl.mapper.ServeMapper;
import com.zsc.edu.gateway.modules.iot.tsl.query.ServeQuery;
import com.zsc.edu.gateway.modules.iot.tsl.repo.ParamRepository;
import com.zsc.edu.gateway.modules.iot.tsl.repo.ServeParamRepository;
import com.zsc.edu.gateway.modules.iot.tsl.repo.ServeRepository;
import com.zsc.edu.gateway.modules.iot.tsl.service.ParamService;
import com.zsc.edu.gateway.modules.iot.tsl.service.ServeService;
@ -14,6 +21,8 @@ import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
@ -24,6 +33,8 @@ import java.util.List;
public class ServeServiceImpl extends ServiceImpl<ServeRepository, Serve> implements ServeService {
private final ServeMapper mapper;
private final ParamRepository paramRepository;
private final ServeParamRepository serveParamRepository;
private final ParamService paramService;
/**
* 新建功能
@ -35,9 +46,10 @@ public class ServeServiceImpl extends ServiceImpl<ServeRepository, Serve> implem
}
Serve serve = mapper.toEntity(dto);
save(serve);
List<ParamDto> params = new ArrayList<>(dto.getInputs());
params.addAll(dto.getOutputs());
paramService.create(params, serve.getId(), Param.ForeignType.SERVE);
List<ServeParam> serveParams = paramService.paramCreate(dto.getParams()).stream()
.map(paramId -> new ServeParam(serve.getId(), paramId))
.toList();
serveParamRepository.insert(serveParams);
return serve;
}
/**
@ -48,12 +60,26 @@ public class ServeServiceImpl extends ServiceImpl<ServeRepository, Serve> implem
Serve serve = baseMapper.selectById(id);
mapper.convert(dto, serve);
updateById(serve);
List<ParamDto> params = new ArrayList<>(dto.getInputs());
params.addAll(dto.getOutputs());
paramService.update(params, serve.getId());
paramService.paramUpdate(dto.getParams(),
serveParamRepository.selectList(new LambdaQueryWrapper<ServeParam>()
.eq(ServeParam::getServeId, serve.getId()))
.stream()
.map(ServeParam::getParamId)
.collect(Collectors.toList()));
return serve;
}
/**
* 分页查询功能
*
* @param query 查询表单
* @param page 分页参数
*/
// @Override
// public IPage<Serve> page(Page<Serve> page, ServeQuery query) {
// return baseMapper.page(page, query);
// }
/**
* 查询详情
* @param id 主键
@ -63,16 +89,19 @@ public class ServeServiceImpl extends ServiceImpl<ServeRepository, Serve> implem
public Serve detail(Long id) {
return baseMapper.selectById(id);
}
/**
* 删除功能
*
* @param id serveId
* @return true
*/
@Override
public Boolean delete(Long id) {
removeById(id);
return paramService.delete(id);
LambdaQueryWrapper<ServeParam> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ServeParam::getServeId, id);
List<ServeParam> serveParam = serveParamRepository.selectList(wrapper);
if (!serveParam.isEmpty()) {
List<Long> paramIds = serveParam.stream()
.map(ServeParam::getParamId)
.toList();
paramRepository.deleteByIds(paramIds);
}
serveParamRepository.delete(wrapper);
return true;
}
}

View File

@ -33,11 +33,6 @@ public class Bulletin extends BaseEntity {
*/
public State state = State.edit;
/**
* 部门ID(权限)
*/
public Long deptId;
/**
* 是否置顶
*/

View File

@ -57,8 +57,4 @@ public class Message extends BaseEntity {
*/
public String content;
/**
* 部门ID(权限)
*/
public Long deptId;
}

View File

@ -31,7 +31,5 @@ public interface UserMessageService extends IService<UserMessage> {
boolean markAsRead(UserDetailsImpl userDetails, List<Long> messageIds);
boolean markAllAsRead(UserDetailsImpl userDetails);
IPage<AdminMessageVo> getAdminMessagePage(Page<UserMessageVo> page, AdminMessageQuery query);
}

View File

@ -1,6 +1,7 @@
package com.zsc.edu.gateway.modules.notice.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
@ -100,7 +101,10 @@ public class UserMessageServiceImpl extends ServiceImpl<UserMessageRepository, U
@Override
public boolean markAsRead(UserDetailsImpl userDetails, List<Long> messageIds) {
if (CollectionUtils.isEmpty(messageIds)) {
throw new RuntimeException("您输入的集合为空");
return this.lambdaUpdate().eq(UserMessage::getUserId, userDetails.getId())
.set(UserMessage::getIsRead, true)
.set(UserMessage::getReadTime, LocalDateTime.now())
.update();
}
return this.lambdaUpdate().eq(UserMessage::getUserId, userDetails.getId())
.in(UserMessage::getMessageId, messageIds)
@ -109,16 +113,6 @@ public class UserMessageServiceImpl extends ServiceImpl<UserMessageRepository, U
.update();
}
/**
* 全部已读
*/
@Override
public boolean markAllAsRead(UserDetailsImpl userDetails) {
return this.lambdaUpdate().eq(UserMessage::getUserId, userDetails.getId())
.set(UserMessage::getIsRead, true)
.set(UserMessage::getReadTime, LocalDateTime.now())
.update();
}
/**
* 管理员查询消息列表
@ -183,7 +177,7 @@ public class UserMessageServiceImpl extends ServiceImpl<UserMessageRepository, U
sms.set(message.sms);
});
Message message = new Message(payload.type, true, email.get(), sms.get(),
payload.html, payload.type.name(), payload.content, null);
payload.html, payload.type.name(), payload.content);
messageRepo.insert(message);
Set<UserMessage> userMessages = receivers.stream().map(user ->
new UserMessage(null, user.getId(), message.getId(), true, null)).collect(Collectors.toSet());

View File

@ -21,49 +21,49 @@ public class AuthorityController {
private AuthorityService service;
/**
* 返回权限列表 hasAuthority('SYSTEM:AUTHORITY:QUERY')
* 返回权限列表 hasAuthority('AUTHORITY_QUERY')
*
* @param query 查询表单
* @return 权限列表
*/
@GetMapping
@PreAuthorize("hasAuthority('SYSTEM:AUTHORITY:QUERY')")
@PreAuthorize("hasAuthority('AUTHORITY_QUERY')")
public Page<Authority> query(AuthorityQuery query, Page<Authority> page) {
return service.page(page, query.wrapper());
}
/**
* 新建权限 hasAuthority('SYSTEM:AUTHORITY:CREATE')
* 新建权限 hasAuthority('AUTHORITY_CREATE')
*
* @param dto 表单数据
* @return Authority 新建的权限
*/
@PostMapping
@PreAuthorize("hasAuthority('SYSTEM:AUTHORITY:CREATE')")
@PreAuthorize("hasAuthority('AUTHORITY_CREATE')")
public Authority create(@RequestBody AuthorityDto dto) {
return service.create(dto);
}
/**
* 更新权限 hasAuthority('SYSTEM:AUTHORITY:UPDATE')
* 更新权限 hasAuthority('AUTHORITY_UPDATE')
*
* @param dto 表单数据
* @param id 权限ID
* @return Dept 更新后的权限信息
*/
@PatchMapping("/{id}")
@PreAuthorize("hasAuthority('SYSTEM:AUTHORITY:UPDATE')")
@PreAuthorize("hasAuthority('AUTHORITY_UPDATE')")
public Boolean update(@RequestBody AuthorityDto dto, @PathVariable("id") Long id) {
return service.update(dto, id);
}
/***
* 删除权限 hasAuthority('SYSTEM:AUTHORITY:DELETE')
* 删除权限 hasAuthority('AUTHORITY_DELETE')
* @param id 权限ID
* @return Boolean 是否删除成功
*/
@DeleteMapping("/{id}")
@PreAuthorize("hasAuthority('SYSTEM:AUTHORITY:DELETE')")
@PreAuthorize("hasAuthority('AUTHORITY_DELETE')")
public Boolean delete(@PathVariable("id") Long id) {
return service.removeById(id);
}
@ -71,7 +71,7 @@ public class AuthorityController {
* 更新权限启用状态
* */
@PatchMapping("/toggle/{id}")
@PreAuthorize("hasAuthority('SYSTEM:AUTHORITY:TOGGLE')")
@PreAuthorize("hasAuthority('AUTHORITY_TOGGLE')")
public Boolean toggle(@PathVariable("id") Long id) {
return service.toggle(id);
}

View File

@ -1,12 +1,10 @@
package com.zsc.edu.gateway.modules.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsc.edu.gateway.exception.ConstraintException;
import com.zsc.edu.gateway.modules.system.dto.DeptDto;
import com.zsc.edu.gateway.modules.system.entity.Dept;
import com.zsc.edu.gateway.modules.system.entity.User;
import com.zsc.edu.gateway.modules.system.query.DeptQuery;
import com.zsc.edu.gateway.modules.system.service.DeptService;
import com.zsc.edu.gateway.modules.system.service.UserService;
import lombok.AllArgsConstructor;
@ -29,75 +27,61 @@ public class DeptController {
private final UserService userService;
/**
* 返回管理部门列表 hasAuthority('SYSTEM:DEPT:QUERY')
*
* @param query 查询表单
* 返回管理部门列表 hasAuthority('DEPT_QUERY')
* @param deptId 部门ID
* @return 部门列表
*/
@GetMapping
@PreAuthorize("hasAuthority('SYSTEM:DEPT:QUERY')")
public Page<Dept> query(DeptQuery query, Page<Dept> page) {
return service.page(page, query.wrapper());
@GetMapping("/{deptId}")
public List<Dept> getDeptTree(@PathVariable Long deptId) {
return service.getDeptTree(deptId);
}
/**
* 返回管理部门列表 hasAuthority('SYSTEM:DEPT:QUERY')
*
* @param id 指定部门id
* @return 部门列表
*/
@GetMapping("/tree")
@PreAuthorize("hasAuthority('SYSTEM:DEPT:QUERY')")
public List<Dept> tree(@RequestParam Long id) {
return service.listTree(id);
}
/**
* 新建管理部门 hasAuthority('SYSTEM:DEPT:CREATE')
* 新建管理部门 hasAuthority('DEPT_CREATE')
*
* @param dto 表单数据
* @return Dept 新建的管理部门
*/
@PostMapping
@PreAuthorize("hasAuthority('SYSTEM:DEPT:CREATE')")
@PreAuthorize("hasAuthority('DEPT_CREATE')")
public Dept create(@RequestBody DeptDto dto) {
return service.create(dto);
}
/**
* 更新管理部门 hasAuthority('SYSTEM:DEPT:UPDATE')
* 更新管理部门 hasAuthority('DEPT_UPDATE')
*
* @param dto 表单数据
* @param id 部门ID
* @return Dept 更新后的部门
*/
@PatchMapping("/{id}")
@PreAuthorize("hasAuthority('SYSTEM:DEPT:UPDATE')")
@PreAuthorize("hasAuthority('DEPT_UPDATE')")
public Boolean update(@RequestBody DeptDto dto, @PathVariable("id") Long id) {
return service.edit(dto, id);
}
/***
* 删除管理部门 hasAuthority('SYSTEM:DEPT:DELETE')
* 删除管理部门 hasAuthority('DEPT_DELETE')
* @param id 部门ID
* @return Boolean 是否删除成功
*/
@DeleteMapping("/{id}")
@PreAuthorize("hasAuthority('SYSTEM:DEPT:DELETE')")
@PreAuthorize("hasAuthority('DEPT_DELETE')")
public Boolean delete(@PathVariable("id") Long id) {
// 是否存在用户绑定此部门
/**
* 是否存在用户绑定此部门
* */
boolean hasUser = userService.count(new LambdaQueryWrapper<User>().eq(User::getDeptId, id)) > 0;
if (hasUser) {
throw new ConstraintException("存在与本部门绑定的用户,请先删除用户");
}
return service.removeById(id);
}
/**
* 更新管理部门状态
* */
@PatchMapping("/toggle/{id}")
@PreAuthorize("hasAuthority('SYSTEM:DEPT:TOGGLE')")
@PreAuthorize("hasAuthority('DEPT_TOGGLE')")
public Boolean toggle(@PathVariable("id") Long id) {
return service.toggle(id);
}

View File

@ -31,38 +31,38 @@ public class RoleController {
private final RoleAuthService roleAuthService;
/**
* 返回所有角色列表 hasAuthority('SYSTEM:ROLE:QUERY')
* 返回所有角色列表 hasAuthority('ROLE_QUERY')
*
* @return 所有角色列表
*/
@GetMapping
@PreAuthorize("hasAuthority('SYSTEM:ROLE:QUERY')")
@PreAuthorize("hasAuthority('ROLE_QUERY')")
public Page<Role> query(RoleQuery query, Page<Role> page) {
return service.page(page, query.wrapper());
}
/**
* 新建角色 hasAuthority('SYSTEM:ROLE:CREATE')
* 新建角色 hasAuthority('ROLE_CREATE')
*
* @param dto 表单数据
* @return Role 新建的角色
*/
@PostMapping
@PreAuthorize("hasAuthority('SYSTEM:ROLE:CREATE')")
@PreAuthorize("hasAuthority('ROLE_CREATE')")
public Boolean create(@RequestBody RoleDto dto) {
Role role= service.create(dto);
return role != null;
}
/**
* 更新角色 hasAuthority('SYSTEM:ROLE:UPDATE')
* 更新角色 hasAuthority('ROLE_UPDATE')
*
* @param dto 表单数据
* @param id ID
* @return Role 更新后的角色
*/
@PatchMapping("{id}")
@PreAuthorize("hasAuthority('SYSTEM:ROLE:UPDATE')")
@PreAuthorize("hasAuthority('ROLE_UPDATE')")
public Boolean update(@RequestBody RoleDto dto, @PathVariable("id") Long id) {
// Role role = roleMapper.toEntity(dto);
// role.setId(id);
@ -70,48 +70,48 @@ public class RoleController {
}
/**
* 切换角色"启动/禁用"状态 hasAuthority('SYSTEM:ROLE:UPDATE')
* 切换角色"启动/禁用"状态 hasAuthority('ROLE_UPDATE')
*
* @param id ID
* @return Role 更新后的角色
*/
@PatchMapping("{id}/toggle")
@PreAuthorize("hasAuthority('SYSTEM:ROLE:UPDATE')")
@PreAuthorize("hasAuthority('ROLE_UPDATE')")
public Boolean toggle(@PathVariable("id") Long id) {
return service.toggle(id);
}
/**
* 查询角色详情 hasAuthority('SYSTEM:ROLE:QUERY')
* 查询角色详情 hasAuthority('ROLE_QUERY')
*
* @param id ID
* @return Role 角色详情
*/
@GetMapping("{id}")
@PreAuthorize("hasAuthority('SYSTEM:ROLE:QUERY')")
@PreAuthorize("hasAuthority('ROLE_QUERY')")
public RoleVo detail(@PathVariable Long id) {
return service.detail(id);
}
/**
* 删除角色 hasAuthority('SYSTEM:ROLE:DELETE')
* 删除角色 hasAuthority('ROLE_DELETE')
*
* @param id ID
* @return Role 更新后的角色
*/
@DeleteMapping("{id}")
@PreAuthorize("hasAuthority('SYSTEM:ROLE:DELETE')")
@PreAuthorize("hasAuthority('ROLE_DELETE')")
public Boolean delete(@PathVariable Long id) {
return service.delete(id);
}
/**
* 为角色添加权限 hasAuthority('SYSTEM:ROLE:AUTHED')
* 为角色添加权限 hasAuthority('ROLE_AUTHED')
*
* @return RoleAuthority 新的角色权限
*/
@PostMapping("/saveAuth/{id}")
@PreAuthorize("hasAuthority('SYSTEM:ROLE:AUTHED')")
@PreAuthorize("hasAuthority('ROLE_AUTHED')")
public Boolean addAuthed(@PathVariable Long id, @RequestBody Set<AuthorityCreateDto> authorities) {
return service.saveRoleAuths(id,authorities);
}

View File

@ -1,29 +1,30 @@
package com.zsc.edu.gateway.modules.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.zsc.edu.gateway.framework.security.UserDetailsImpl;
import com.zsc.edu.gateway.modules.system.dto.UserCreateDto;
import com.zsc.edu.gateway.modules.system.dto.UserSelfUpdateDto;
import com.zsc.edu.gateway.modules.system.dto.UserSelfUpdatePasswordDto;
import com.zsc.edu.gateway.modules.system.dto.UserUpdateDto;
import com.zsc.edu.gateway.modules.system.entity.Authority;
import com.zsc.edu.gateway.modules.system.entity.Menu;
import com.zsc.edu.gateway.modules.system.entity.Role;
import com.zsc.edu.gateway.modules.system.entity.User;
import com.zsc.edu.gateway.modules.system.query.UserQuery;
import com.zsc.edu.gateway.modules.system.service.*;
import com.zsc.edu.gateway.modules.system.utils.TreeUtil;
import com.zsc.edu.gateway.modules.system.vo.MenuVo;
import com.zsc.edu.gateway.modules.system.vo.UserDetail;
import com.zsc.edu.gateway.modules.system.vo.UserVo;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* 用户Controller
@ -40,7 +41,6 @@ public class UserController {
private final RoleService roleService;
private final DeptService deptService;
private final AuthorityService authorityService;
private final MenuService menuService;
/**
* 登录前获取csrfToken信息
@ -50,7 +50,7 @@ public class UserController {
* @param csrfToken csrf令牌
* @return 包含csrf令牌和登录用户的认证主体信息
*/
@RequestMapping(value = "me", method = {RequestMethod.POST, RequestMethod.GET})
@GetMapping("me")
public Map<String, Object> me(@AuthenticationPrincipal Object principal, CsrfToken csrfToken) {
Map<String, Object> map = new LinkedHashMap<>();
map.put("user", principal);
@ -104,14 +104,14 @@ public class UserController {
}
/**
* 分页查询用户信息 hasAuthority('SYSTEM:USER:QUERY')
* 分页查询用户信息 hasAuthority('USER_QUERY')
*
* @param query 查询表单
* @param page 分页
* @return 分页用户信息
*/
@GetMapping
@PreAuthorize("hasAuthority('SYSTEM:USER:QUERY')")
@PreAuthorize("hasAuthority('USER_QUERY·')")
public Page<User> query(UserQuery query, Page<User> page) {
return service.page(page, query.wrapper());
}
@ -119,58 +119,58 @@ public class UserController {
/**
* 新建用户 hasAuthority('SYSTEM:USER:CREATE')
* 新建用户 hasAuthority('USER_CREATE')
*
* @param dto 表单数据
* @return 新建的用户信息
*/
@PostMapping
@PreAuthorize("hasAuthority('SYSTEM:USER:CREATE')")
@PreAuthorize("hasAuthority('USER_CREATE')")
public Boolean create(@RequestBody UserCreateDto dto) {
return service.create(dto);
}
/**
* 更新用户 hasAuthority('SYSTEM:USER:UPDATE')
* 更新用户 hasAuthority('USER_UPDATE')
*
* @param dto 表单数据
* @param id ID
* @return 更新后的用户
*/
@PatchMapping("{id}")
@PreAuthorize("hasAuthority('SYSTEM:USER:UPDATE')")
@PreAuthorize("hasAuthority('USER_UPDATE')")
public Boolean update(@RequestBody UserUpdateDto dto, @PathVariable("id") Long id) {
return service.update(dto, id);
}
/**
* 更新用户密码 hasAuthority('SYSTEM:USER:UPDATE')
* 更新用户密码 hasAuthority('USER_UPDATE')
*
* @param id ID
* @param password 新密码
*/
@PatchMapping("{id}/update-password")
@PreAuthorize("hasAuthority('SYSTEM:USER:UPDATE')")
@PreAuthorize("hasAuthority('USER_UPDATE')")
public Boolean updatePassword(@PathVariable("id") Long id, @RequestParam String password) {
return service.updatePassword(password, id);
}
/**
* 切换用户"启动/禁用"状态 hasAuthority('SYSTEM:USER:DELETE')
* 切换用户"启动/禁用"状态 hasAuthority('USER_DELETE')
*
* @param id ID
* @return Dept 更新后的用户
*/
@PatchMapping("{id}/toggle")
@PreAuthorize("hasAuthority('SYSTEM:USER:DELETE')")
@PreAuthorize("hasAuthority('USER_DELETE')")
public Boolean toggle(@PathVariable("id") Long id) {
return service.toggle(id);
}
/**
* 删除用户 hasAuthority('SYSTEM:USER:DELETE')
* 删除用户 hasAuthority('USER_DELETE')
* */
@DeleteMapping("{id}")
@PreAuthorize("hasAuthority('SYSTEM:USER:DELETE')")
@PreAuthorize("hasAuthority('USER_DELETE')")
public Boolean delete(@PathVariable("id") Long id) {
return service.removeById(id);
}
@ -181,7 +181,6 @@ public class UserController {
public Collection<User> listByDept(@PathVariable("id") Long id) {
return service.list(new QueryWrapper<User>().eq("dept_id", id));
}
/**
* 根据ID查询用户
* */
@ -189,20 +188,6 @@ public class UserController {
public User detail(@PathVariable("id") Long id) {
return service.getById(id);
}
/**
* 根据ID查询用户
* */
@GetMapping("/menu")
public List<MenuVo> menu(@AuthenticationPrincipal UserDetailsImpl userDetails) {
List<MenuVo> list = menuService.selectByUserId(userDetails.getId(), Menu.Type.PAGE).stream().map(MenuVo::new).toList();
return TreeUtil.makeTree(
list,
x -> x.getPid() == null,
(x, y) -> x.getId().equals(y.getPid()),
MenuVo::setChildren
);
}
/**
* 发送邮件
* */

View File

@ -25,11 +25,5 @@ public class Authority extends BaseEntity {
* 启用状态
*/
private Boolean enabled = true;
/**
* 部门ID(权限)
*/
public Long deptId;
}

View File

@ -15,11 +15,13 @@ import java.util.Set;
* 部门
*
* @author Yao
* @since 2023-04-06
*/
@Getter
@Setter
@TableName("sys_dept")
public class Dept extends BaseEntity {
/**
* 上级部门
*/
@ -28,7 +30,7 @@ public class Dept extends BaseEntity {
/**
* 子部门数目
*/
private Integer subCount = 0;
private Integer subCount;
/**
* 名称
@ -38,7 +40,7 @@ public class Dept extends BaseEntity {
/**
* 排序
*/
private Integer deptSort = 1;
private Integer deptSort;
/**
* 状态

View File

@ -1,42 +0,0 @@
package com.zsc.edu.gateway.modules.system.entity;
import com.baomidou.mybatisplus.annotation.EnumValue;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;
/**
* 操作权限
*
* @author harry yao
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
@TableName("sys_menu")
public class Menu extends BaseEntity {
private Long pid;
private Type type;
private String name;
private String path;
private String locale;
private String icon;
private Boolean requiresAuth;
private Boolean hideInMenu;
private Integer menuOrder;
private String permissions;
private String authority;
@Getter
@AllArgsConstructor
public enum Type {
PAGE(1, "页面"),
OPERATION(2, "操作");
@EnumValue
private final Integer code;
private final String desc;
}
}

View File

@ -29,11 +29,6 @@ public class Role extends BaseEntity {
*/
private Boolean enabled = true;
/**
* 部门ID(权限)
*/
public Long deptId;
/**
* 权限集合
*/

View File

@ -1,32 +0,0 @@
package com.zsc.edu.gateway.modules.system.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.io.Serializable;
/**
* sys_role_menu
* @author zhuang
*/
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@TableName("sys_role_menu")
public class RoleMenu implements Serializable {
/**
* 角色ID
*/
private Long roleId;
/**
* 权限ID
*/
private Long menuId;
// @TableField(exist = false)
// private Set<Authority> authorities;
}

View File

@ -66,7 +66,7 @@ public class User extends BaseEntity {
public Long roleId;
/**
* 拥有的当前角色
* 拥有的角色
*/
@TableField(exist = false)
public Role role;

View File

@ -3,7 +3,6 @@ package com.zsc.edu.gateway.modules.system.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serial;
import java.io.Serializable;
/**
@ -22,4 +21,6 @@ public class UserRole implements Serializable {
* 角色ID
*/
private Long roleId;
private static final long serialVersionUID = 1L;
}

View File

@ -1,22 +0,0 @@
package com.zsc.edu.gateway.modules.system.repo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.zsc.edu.gateway.modules.system.entity.Menu;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* @author yao
*/
public interface MenuRepository extends BaseMapper<Menu> {
List<Menu> selectByRoleId(Long roleId);
List<Menu> selectByUserId(Long userId, Menu.Type type);
}

View File

@ -1,11 +0,0 @@
package com.zsc.edu.gateway.modules.system.repo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zsc.edu.gateway.modules.system.entity.RoleMenu;
/**
* @author Yao
*/
public interface RoleMenuRepository extends BaseMapper<RoleMenu> {
}

View File

@ -33,8 +33,8 @@ public interface DeptService extends IService<Dept> {
/**
* 生成部门树结构
* @param id
* @return
*
* @return Dept
*/
List<Dept> listTree(Long id);
List<Dept> getDeptTree(Long deptId);
}

View File

@ -1,16 +0,0 @@
package com.zsc.edu.gateway.modules.system.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.zsc.edu.gateway.modules.system.entity.Menu;
import java.util.List;
/**
* @author zhuang
*/
public interface MenuService extends IService<Menu> {
List<Menu> selectByRoleId(Long roleId);
List<Menu> selectByUserId(Long userId, Menu.Type type);
}

View File

@ -10,7 +10,6 @@ import com.zsc.edu.gateway.modules.system.repo.DeptRepository;
import com.zsc.edu.gateway.modules.system.service.DeptService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
@ -25,11 +24,12 @@ import java.util.Objects;
* @author Yao
* @since 2023-04-06
*/
@RequiredArgsConstructor
@AllArgsConstructor
@Service
public class DeptServiceImpl extends ServiceImpl<DeptRepository, Dept> implements DeptService {
private final DeptMapper mapper;
private final DeptRepository repo;
@Override
public Dept create(DeptDto dto) {
@ -59,8 +59,8 @@ public class DeptServiceImpl extends ServiceImpl<DeptRepository, Dept> implement
}
@Override
public List<Dept> listTree(Long deptId) {
List<Dept> deptTrees = baseMapper.selectDeptTree();
public List<Dept> getDeptTree(Long deptId) {
List<Dept> deptTrees = repo.selectDeptTree();
List<Dept> deptTree = TreeUtil.makeTree(
deptTrees,
department -> department.getPid() == null || department.getPid() == -1L,

View File

@ -1,27 +0,0 @@
package com.zsc.edu.gateway.modules.system.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.edu.gateway.modules.system.entity.Menu;
import com.zsc.edu.gateway.modules.system.repo.MenuRepository;
import com.zsc.edu.gateway.modules.system.service.MenuService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author zhuang
*/
@AllArgsConstructor
@Service
public class MenuServiceImpl extends ServiceImpl<MenuRepository, Menu> implements MenuService {
@Override
public List<Menu> selectByRoleId(Long roleId) {
return baseMapper.selectByRoleId(roleId);
}
@Override
public List<Menu> selectByUserId(Long userId, Menu.Type type) {
return baseMapper.selectByUserId(userId, type);
}
}

View File

@ -1,148 +0,0 @@
package com.zsc.edu.gateway.modules.system.utils;
import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;
/**
* @Description: 树操作方法工具类
* @Copyright: Copyright (c) 赵侠客
* @Date: 2024-07-22 10:42
* @Version: 1.0
*/
public class TreeUtil {
/**
* 将list合成树
*
* @param list 需要合成树的List
* @param rootCheck 判断E中为根节点的条件x->x.getPId()==-1L , x->x.getParentId()==null,x->x.getParentMenuId()==0
* @param parentCheck 判断E中为父节点条件(x,y)->x.getId().equals(y.getPId())
* @param setSubChildren E中设置下级数据方法Menu::setSubMenus
* @param <E> 泛型实体对象
* @return 合成好的树
*/
public static <E> List<E> makeTree(List<E> list, Predicate<E> rootCheck, BiFunction<E, E, Boolean> parentCheck, BiConsumer<E, List<E>> setSubChildren) {
return list.stream()
.filter(rootCheck)
.peek(x -> setSubChildren.accept(x, makeChildren(x, list, parentCheck, setSubChildren)))
.collect(Collectors.toList());
}
/**
* 创建子树
*
* @param parent 父节点
* @param allData 需要合成树的原始List
* @param parentCheck 判断E中为父节点条件(x,y)->x.getId().equals(y.getPId())
* @param children E中设置下级数据方法Menu::setSubMenus
* @param <E> 泛型实体对象
* @return 合成好的子树
*/
private static <E> List<E> makeChildren(E parent, List<E> allData, BiFunction<E, E, Boolean> parentCheck, BiConsumer<E, List<E>> children) {
return allData.stream()
.filter(x -> parentCheck.apply(parent, x))
.peek(x -> children.accept(x, makeChildren(x, allData, parentCheck, children)))
.collect(Collectors.toList());
}
/**
* 将树打平成tree
* @param tree 需要打平的树
* @param getSubChildren 设置下级数据方法Menu::getSubMenus,x->x.setSubMenus(null)
* @param setSubChildren 将下级数据置空方法x->x.setSubMenus(null)
* @return 打平后的数据
* @param <E> 泛型实体对象
*/
public static <E> List<E> flat(List<E> tree, Function<E, List<E>> getSubChildren, Consumer<E> setSubChildren) {
List<E> res = new ArrayList<>();
forPostOrder(
tree,
item -> {
setSubChildren.accept(item);
res.add(item);
},
getSubChildren
);
return res;
}
/**
* 前序遍历
*
* @param tree 需要遍历的树
* @param consumer 遍历后对单个元素的处理方法x-> System.out.println(x) System.out::println打印元素
* @param setSubChildren 设置下级数据方法Menu::getSubMenus,x->x.setSubMenus(null)
* @param <E> 泛型实体对象
*/
public static <E> void forPreOrder(List<E> tree, Consumer<E> consumer, Function<E, List<E>> setSubChildren) {
for (E l : tree) {
consumer.accept(l);
List<E> es = setSubChildren.apply(l);
if (Objects.nonNull(es) && !es.isEmpty()) {
forPreOrder(es, consumer, setSubChildren);
}
}
}
/**
* 层序遍历
*
* @param tree 需要遍历的树
* @param consumer 遍历后对单个元素的处理方法x-> System.out.println(x) System.out::println打印元素
* @param setSubChildren 设置下级数据方法Menu::getSubMenus,x->x.setSubMenus(null)
* @param <E> 泛型实体对象
*/
public static <E> void forLevelOrder(List<E> tree, Consumer<E> consumer, Function<E, List<E>> setSubChildren) {
Queue<E> queue = new LinkedList<>(tree);
while (!queue.isEmpty()) {
E item = queue.poll();
consumer.accept(item);
List<E> childList = setSubChildren.apply(item);
if (Objects.nonNull(childList) && !childList.isEmpty()) {
queue.addAll(childList);
}
}
}
/**
* 后序遍历
*
* @param tree 需要遍历的树
* @param consumer 遍历后对单个元素的处理方法x-> System.out.println(x) System.out::println打印元素
* @param setSubChildren 设置下级数据方法Menu::getSubMenus,x->x.setSubMenus(null)
* @param <E> 泛型实体对象
*/
public static <E> void forPostOrder(List<E> tree, Consumer<E> consumer, Function<E, List<E>> setSubChildren) {
for (E item : tree) {
List<E> childList = setSubChildren.apply(item);
if (Objects.nonNull(childList) && !childList.isEmpty()) {
forPostOrder(childList, consumer, setSubChildren);
}
consumer.accept(item);
}
}
/**
* 对树所有子节点按comparator排序
*
* @param tree 需要排序的树
* @param comparator 排序规则ComparatorComparator.comparing(MenuVo::getRank)按Rank正序 ,(x,y)->y.getRank().compareTo(x.getRank())按Rank倒序
* @param getChildren 获取下级数据方法MenuVo::getSubMenus
* @return 排序好的树
* @param <E> 泛型实体对象
*/
public static <E> List<E> sort(List<E> tree, Comparator<? super E> comparator, Function<E, List<E>> getChildren) {
for (E item : tree) {
List<E> childList = getChildren.apply(item);
if (Objects.nonNull(childList) && !childList.isEmpty()) {
sort(childList,comparator,getChildren);
}
}
tree.sort(comparator);
return tree;
}
}

View File

@ -1,82 +0,0 @@
package com.zsc.edu.gateway.modules.system.vo;
import com.zsc.edu.gateway.modules.system.entity.Menu;
import lombok.Data;
import java.util.List;
/**
* 菜单
*
* @author harry yao
*/
@Data
public class MenuVo {
/**
* 菜单id
*/
private Long id;
/**
* 父菜单id
*/
private Long pid;
/**
* 路由名称
*/
private String name;
/**
* 菜单路径
*/
private String path;
private Meta meta;
/**
* 子菜单
*/
private List<MenuVo> children = null;
public MenuVo(Menu menu) {
this.id = menu.getId();
this.pid = menu.getPid();
this.name = menu.getName();
this.path = menu.getPath();
this.meta = new Meta(menu);
}
}
@Data
class Meta {
/**
* 菜单名称语言包键名
*/
private String locale;
/**
* 菜单icon
*/
private String icon;
/**
* 是否需要登录鉴权
*/
private Boolean requiresAuth;
/**
* 是否隐藏菜单
*/
private Boolean hideInMenu;
/**
* 排序
*/
private Integer order;
/**
* 访问权限使用","隔开的权限字符串
*/
private String[] permissions;
public Meta(Menu menu) {
this.locale = menu.getLocale();
this.icon = menu.getIcon();
this.requiresAuth = menu.getRequiresAuth();
this.hideInMenu = menu.getHideInMenu();
this.order = menu.getMenuOrder();
this.permissions = menu.getPermissions().split(",");
}
}

View File

@ -25,9 +25,6 @@ spring:
multipart:
max-file-size: 40MB
max-request-size: 40MB
jackson:
# 属性为空不序列化
default-property-inclusion: non_null
mail:
# 配置 SMTP 服务器地址
host: smtp.qq.com

View File

@ -495,7 +495,7 @@ VALUES (1, 'Device1', TRUE, 1, 'HW1.0', 'FW1.0', 'FactoryA', 'Client1', 1, '{"pa
(10, 'Device10', FALSE, 10, 'HW1.9', 'FW1.9', 'FactoryJ', 'Client10', 10, '{"param10": "value10"}',
'{"prop10": "value10"}', 'Admin', CURRENT_TIMESTAMP, 'Admin', CURRENT_TIMESTAMP, 'Remark10');
INSERT INTO iot_product (id, name, product_type, model, link, create_by, create_time, update_by, update_time, remark,
INSERT INTO iot_product (id, name, type_string, model, link, create_by, create_time, update_by, update_time, remark,
dept_id)
VALUES (1, 'Product1', 'TypeA', 'ModelX', 1, 'Admin', CURRENT_TIMESTAMP, 'Admin', CURRENT_TIMESTAMP, 'Remark1', 101),
(2, 'Product2', 'TypeB', 'ModelY', 2, 'Admin', CURRENT_TIMESTAMP, 'Admin', CURRENT_TIMESTAMP, 'Remark2', 102),
@ -556,53 +556,4 @@ VALUES (1, 'serve1', 'Service 1', 'This is service 1'),
(9, 'serve9', 'Service 9', 'This is service 9'),
(10, 'serve10', 'Service 10', 'This is service 10');
alter table iot_device
add dept_id bigint;
comment on column iot_device.dept_id is '部门权限id';
alter table iot_param
add dept_id bigint;
comment on column iot_param.dept_id is '部门权限id';
alter table iot_serve
add dept_id bigint;
comment on column iot_serve.dept_id is '部门权限id';
alter table iot_event
add dept_id bigint;
comment on column iot_event.dept_id is '部门权限id';
alter table iot_event
add dept_id bigint;
comment on column iot_event.dept_id is '部门权限id';
alter table sys_bulletin
add dept_id bigint;
comment on column sys_bulletin.dept_id is '部门权限id';
alter table sys_bulletin
add dept_id bigint;
comment on column sys_bulletin.dept_id is '部门权限id';
alter table sys_message
add dept_id bigint;
comment on column sys_message.dept_id is '部门权限id';
alter table sys_authority
add dept_id bigint;
comment on column sys_authority.dept_id is '部门权限id';
alter table sys_role
add dept_id bigint;
comment on column sys_role.dept_id is '部门权限id';

View File

@ -1,17 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zsc.edu.gateway.modules.system.repo.AuthorityRepository">
<select id="selectAuthoritiesByRoleId" resultType="authority">
select sa.* from sys_authority sa
left join sys_role_authorities ra on sa.id=ra.authority_id
where ra.role_id=#{roleId}
</select>
<select id="getAuthorityIdByName" resultType="java.lang.Long">
select sa.id from sys_authority sa where sa.name=#{authName}
</select>
</mapper>

View File

@ -1,12 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zsc.edu.gateway.modules.system.repo.MenuRepository">
<select id="selectByRoleId" resultType="Menu">
select m.* from sys_menu m,sys_role_menu rm where m.id=rm.menu_id and rm.role_id=#{roleId}
</select>
<select id="selectByUserId" resultType="Menu">
select m.* from sys_menu m,sys_role_menu rm, sys_user u
where m.id=rm.menu_id and rm.role_id=u.role_id and u.id=#{userId} and m.type=#{type}
</select>
</mapper>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zsc.edu.gateway.modules.system.repo.RoleAuthoritiesRepository">
</mapper>

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zsc.edu.gateway.modules.system.repo.AuthorityRepository">
<!-- <resultMap id="AuthorityMap" type="com.zsc.bill.modules.system.entity.Authority">-->
<!-- <id column="id" jdbcType="BIGINT" property="id"/>-->
<!-- <result column="name" jdbcType="VARCHAR" property="name"/>-->
<!-- <result column="create_by" jdbcType="VARCHAR" property="createBy"/>-->
<!-- <result column="update_by" jdbcType="VARCHAR" property="updateBy"/>-->
<!-- <result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>-->
<!-- <result column="update_time" jdbcType="TIMESTAMP" property="updateTime"/>-->
<!-- <result column="enabled" jdbcType="BOOLEAN" property="enabled"/>-->
<!-- <result column="remark" jdbcType="VARCHAR" property="remark"/>-->
<!-- </resultMap>-->
<select id="selectAuthoritiesByRoleId" resultType="authority">
select sa.* from sys_authority sa
left join sys_role_authorities ra on sa.id=ra.authority_id
where ra.role_id=#{roleId}
</select>
<select id="getAuthorityIdByName" resultType="java.lang.Long">
select sa.id from sys_authority sa
where sa.name=#{authName}
</select>
</mapper>

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zsc.edu.gateway.modules.system.repo.RoleAuthoritiesRepository">
<!-- <resultMap id="BaseResultMap" type="com.zsc.edu.gateway.modules.system.entity.RoleAuthority">-->
<!-- <result column="role_id" jdbcType="BIGINT" property="roleId"/>-->
<!-- <result column="authority" jdbcType="BIGINT" property="authority"/>-->
<!-- </resultMap>-->
<!-- <select id="selectByRoleId" parameterType="java.lang.Long" resultMap="BaseResultMap">-->
<!-- select * from sys_role_authorities sra where sra.role_id = #{roleId}-->
<!-- </select>-->
</mapper>

View File

@ -19,8 +19,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.Set;
/**
* @author pengzheng
*/
@ -82,7 +80,7 @@ abstract public class BaseServiceTest {
.password(passwordEncoder.encode("user1"))
.build();
userRepo.insert(user2);
userDetails = UserDetailsImpl.from(user1, Set.of());
userDetails = UserDetailsImpl.from(user1);
dataInit = true;
deptRepoStatic = deptRepo;

View File

@ -23,7 +23,6 @@ import org.springframework.test.web.servlet.MockMvc;
import javax.sql.DataSource;
import java.util.HashSet;
import java.util.Set;
/**
* @author pengzheng
@ -61,6 +60,6 @@ abstract public class MockMvcConfigBase {
Role role = RoleBuilder.aRole().authorities(new HashSet<>()).build();
// Role role = RoleBuilder.aRole().authorities(new HashSet<>(Arrays.asList(Authority))).build();
user = UserBuilder.anUser().username("admin").dept(dept).role(role).build();
userDetails = UserDetailsImpl.from(user, Set.of());
userDetails = UserDetailsImpl.from(user);
}
}

View File

@ -1,16 +0,0 @@
package com.zsc.edu.gateway.domain;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
public class BaseParamBuilder {
public Long id = 1L;
public String identifier;
public String name;
public String remark;
public BaseParamBuilder() {
remark = randomAlphabetic(5);
identifier = randomAlphabetic(5);
name = randomAlphabetic(5);
}
}

View File

@ -11,7 +11,7 @@ public class DeptBuilder extends BaseEntityBuilder {
public Dept parent;
public Long pid;
public List<Dept> children;
public HashSet<Dept> children;
public static DeptBuilder aDept(){
@ -34,7 +34,7 @@ public class DeptBuilder extends BaseEntityBuilder {
return this;
}
public DeptBuilder children(List<Dept> children) {
public DeptBuilder children(HashSet<Dept> children) {
this.children = children;
return this;
}
@ -44,7 +44,7 @@ public class DeptBuilder extends BaseEntityBuilder {
Dept dept = new Dept();
dept.setName(name);
dept.setPid(pid);
dept.setChildren(children);
dept.setChildren((List<Dept>) children);
return dept;
}

View File

@ -1,44 +0,0 @@
package com.zsc.edu.gateway.domain;
import com.zsc.edu.gateway.modules.iot.tsl.entity.DataType;
import com.zsc.edu.gateway.modules.iot.tsl.entity.Param;
public class ParamBuilder extends BaseParamBuilder {
public DataType dataType;
public String uint;
public Param.Type type;
public Param.ForeignType foreignType;
public static ParamBuilder aParam() {
return new ParamBuilder();
}
public ParamBuilder dataType(DataType dataType) {
this.dataType = dataType;
return this;
}
public ParamBuilder uint(String uint) {
this.uint = uint;
return this;
}
public ParamBuilder type(Param.Type type) {
this.type = type;
return this;
}
public ParamBuilder foreignType(Param.ForeignType foreignType) {
this.foreignType = foreignType;
return this;
}
public Param build() {
Param param = new Param();
param.setUint(uint);
param.setType(type);
param.setForeignType(foreignType);
param.setDataType(dataType);
return param;
}
}

View File

@ -1,82 +0,0 @@
package com.zsc.edu.gateway.modules.system.service.impl;
import com.zsc.edu.gateway.modules.system.entity.Menu;
import com.zsc.edu.gateway.modules.system.entity.Role;
import com.zsc.edu.gateway.modules.system.entity.RoleMenu;
import com.zsc.edu.gateway.modules.system.repo.RoleMenuRepository;
import com.zsc.edu.gateway.modules.system.service.MenuService;
import com.zsc.edu.gateway.modules.system.service.RoleService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class MenuServiceImplTest {
@Autowired
private MenuService menuService;
@Autowired
private RoleService roleService;
@Autowired
private RoleMenuRepository roleMenuRepository;
@Test
public void insertRootMenu() {
Menu dashboard = new Menu(null, Menu.Type.PAGE, "Dashboard", "/dashboard", "dashboard", "icon-dashboard", true, false, 1, "dashboard", "");
Menu system = new Menu(null, Menu.Type.PAGE, "System", "/system", "menu.system", "icon-computer", true, false, 2, "system", "");
Menu user = new Menu(null, Menu.Type.PAGE, "User", "/user", "menu.user", "icon-user", true, false, 3, "user", "");
Menu message = new Menu(null, Menu.Type.PAGE, "Message", "/message", "消息管理", "icon-message", true, false, 4, "message", "");
menuService.saveBatch(List.of(dashboard, system, user, message));
Menu workplace = new Menu(dashboard.getId(), Menu.Type.PAGE, "Workplace", "workplace", "工作台", "icon-dashboard", true, false, 1, "dashboard:workplace", "");
Menu role = new Menu(system.getId(), Menu.Type.PAGE, "Role", "role", "角色管理", null, true, false, 1, "system:role", "");
Menu dept = new Menu(system.getId(), Menu.Type.PAGE, "Dept", "dept", "部门管理", null, true, false, 2, "system:dept", "");
Menu users = new Menu(system.getId(), Menu.Type.PAGE, "User", "user", "用户管理", null, true, false, 3, "system:user", "");
Menu authority = new Menu(system.getId(), Menu.Type.PAGE, "Authority", "authority", "权限管理", null, true, false, 4, "system:authority", "");
Menu menu = new Menu(system.getId(), Menu.Type.PAGE, "Menu", "menu", "菜单管理", null, true, false, 5, "system:menu", "");
Menu notice = new Menu(message.getId(), Menu.Type.PAGE, "Notice", "notice", "通知管理", null, true, false, 1, "message:notice", "");
Menu bulletin = new Menu(message.getId(), Menu.Type.PAGE, "Bulletin", "bulletin", "公告管理", null, true, false, 2, "message:bulletin", "");
menuService.saveBatch(List.of(workplace, dept, users, authority, menu, notice, bulletin));
Menu roleCreate = new Menu(role.getId(), Menu.Type.OPERATION, "roleCreate", null, "角色新增", null, true, false, 1, "system:role:create", "");
Menu roleDelete = new Menu(role.getId(), Menu.Type.OPERATION, "roleDelete", null, "角色删除", null, true, false, 1, "system:role:delete", "");
Menu roleUpdate = new Menu(role.getId(), Menu.Type.OPERATION, "roleUpdate", null, "角色修改", null, true, false, 1, "system:role:update", "");
Menu roleQuery = new Menu(role.getId(), Menu.Type.OPERATION, "roleQuery", null, "角色查询", null, true, false, 1, "system:role:query", "");
Menu deptSave = new Menu(dept.getId(), Menu.Type.OPERATION, "deptCreate", null, "部门新增", null, true, false, 1, "system:dept:create", "");
Menu deptUpdate = new Menu(dept.getId(), Menu.Type.OPERATION, "deptUpdate", null, "部门修改", null, true, false, 1, "system:dept:update", "");
Menu deptQuery = new Menu(dept.getId(), Menu.Type.OPERATION, "deptQuery", null, "部门查询", null, true, false, 1, "system:dept:query", "");
Menu deptDelete = new Menu(dept.getId(), Menu.Type.OPERATION, "deptDelete", null, "部门删除", null, true, false, 1, "system:dept:delete", "");
Menu userSave = new Menu(dept.getId(), Menu.Type.OPERATION, "userCreate", null, "用户新增", null, true, false, 1, "system:user:create", "");
Menu userUpdate = new Menu(dept.getId(), Menu.Type.OPERATION, "userUpdate", null, "用户修改", null, true, false, 1, "system:user:update", "");
Menu userQuery = new Menu(dept.getId(), Menu.Type.OPERATION, "userQuery", null, "用户查询", null, true, false, 1, "system:user:query", "");
Menu userDelete = new Menu(dept.getId(), Menu.Type.OPERATION, "userDelete", null, "用户删除", null, true, false, 1, "system:user:delete", "");
Menu menuSave = new Menu(menu.getId(), Menu.Type.OPERATION, "menuCreate", null, "菜单新增", null, true, false, 1, "system:menu:create", "");
Menu menuUpdate = new Menu(menu.getId(), Menu.Type.OPERATION, "menuUpdate", null, "菜单修改", null, true, false, 1, "system:menu:update", "");
Menu menuQuery = new Menu(menu.getId(), Menu.Type.OPERATION, "menuQuery", null, "菜单查询", null, true, false, 1, "system:menu:query", "");
Menu menuDelete = new Menu(menu.getId(), Menu.Type.OPERATION, "menuDelete", null, "菜单删除", null, true, false, 1, "system:menu:delete", "");
menuService.saveBatch(List.of(roleCreate, roleDelete, roleUpdate, roleQuery, deptSave, deptUpdate, deptQuery, deptDelete, userSave, userUpdate, userQuery, userDelete, menuSave, menuUpdate, menuQuery, menuDelete));
}
@Test
public void test() {
Role admin = roleService.lambdaQuery().eq(Role::getName, "admin").one();
menuService.list().forEach(menu -> roleMenuRepository.insert(new RoleMenu(admin.getId(), menu.getId())));
}
@Test
public void testRole() {
Role admin = roleService.lambdaQuery().eq(Role::getName, "admin").one();
List<Menu> menus = menuService.selectByRoleId(admin.getId());
assertEquals(27, menus.size());
}
@Test
public void test2() {
Menu menu = menuService.getById(7L);
System.out.println(menu.toString());
}
}

View File

@ -1,91 +0,0 @@
package com.zsc.edu.gateway.rest;
import com.zsc.edu.gateway.MockMvcConfigBase;
import com.zsc.edu.gateway.domain.BulletinBuilder;
import com.zsc.edu.gateway.framework.security.UserDetailsImpl;
import com.zsc.edu.gateway.modules.notice.dto.BulletinDto;
import com.zsc.edu.gateway.modules.notice.entity.Bulletin;
import com.zsc.edu.gateway.modules.notice.service.BulletinService;
import com.zsc.edu.gateway.modules.system.controller.AuthorityController;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.Spy;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import java.util.List;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(AuthorityController.class)
public class BulletinControllerTest extends MockMvcConfigBase {
@Spy
private static Bulletin bulletin1;
private static Bulletin bulletin2;
@MockBean
private BulletinService service;
@BeforeAll
static void beforeAll() {
bulletin1 = BulletinBuilder.bBulletin().title("title1").content("content1").top(true).build();
bulletin1.setId(1L);
bulletin2 = BulletinBuilder.bBulletin().title("title2").content("content2").top(false).build();
}
@Test
void create() throws Exception {
BulletinDto dto = new BulletinDto();
dto.setTitle(bulletin1.getTitle());
dto.setContent(bulletin1.getContent());
dto.setTop(bulletin1.getTop());
when(service.create(any(UserDetailsImpl.class), any(BulletinDto.class))).thenReturn(bulletin1);
mockMvc.perform(post("/api/rest/bulletin")
.with(csrf().asHeader())
.with(user(userDetails))
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(dto))
)
.andExpect(status().isOk())
.andDo(print());
verify(service).create(any(UserDetailsImpl.class), any(BulletinDto.class));
}
@Test
void list() throws Exception {
List<Bulletin> bulletins = Lists.newArrayList(bulletin1, bulletin2);
when(service.list()).thenReturn(bulletins);
mockMvc.perform(get("/api/rest/bulletin").with(user(userDetails))
).andExpect(status().isOk()).andDo(print());
verify(service).list();
}
@Test
void update() throws Exception {
BulletinDto dto = new BulletinDto();
dto.setTitle(bulletin1.getTitle());
dto.setContent(bulletin1.getContent());
dto.setTop(bulletin1.getTop());
when(service.update(any(UserDetailsImpl.class), any(BulletinDto.class), anyLong())).thenReturn(true);
mockMvc.perform(patch("/api/rest/bulletin/{id}", bulletin1.getId())
.with(csrf().asHeader())
.with(user(userDetails))
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(dto))
)
.andExpect(status().isOk())
.andDo(print());
verify(service).update(any(UserDetailsImpl.class), any(BulletinDto.class), anyLong());
}
}

View File

@ -30,13 +30,13 @@ public class AuthorityServiceTest {
private Authority aut1;
private Authority aut2;
// @BeforeEach
// void setUp() {
// aut1 = AuthorityBuilder.aAuthority().name("TEST_AUTHORITY_ONE").build();
// repo.insert(aut1);
// aut2 = AuthorityBuilder.aAuthority().name("TEST_AUTHORITY_TWO").build();
// repo.insert(aut2);
// }
@BeforeEach
void setUp() {
aut1 = AuthorityBuilder.aAuthority().name("TEST_AUTHORITY_ONE").build();
repo.insert(aut1);
aut2 = AuthorityBuilder.aAuthority().name("TEST_AUTHORITY_TWO").build();
repo.insert(aut2);
}
@Test
void list() {
@ -78,13 +78,8 @@ public class AuthorityServiceTest {
() -> service.update(new AuthorityDto(aut1.getName(), true,null), aut2.id));
}
// @AfterEach
// void tearDown() {
// repo.delete(new QueryWrapper<>());
// }
@Test
void get() {
service.getById(1);
@AfterEach
void tearDown() {
repo.delete(new QueryWrapper<>());
}
}

View File

@ -14,41 +14,25 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
public class BulletinServiceTest {
@Resource
private BulletinService service;
@Resource
private BulletinRepository repo;
private Bulletin bulletin1;
private Bulletin bulletin2;
private UserDetailsImpl userDetails;
Bulletin bulletin1;
Bulletin bulletin2;
@BeforeEach
void setUp() {
userDetails = new UserDetailsImpl();
userDetails.setUsername("admin");
bulletin1 = createAndInsertBulletin("测试1");
bulletin2 = createAndInsertBulletin("测试2");
}
@AfterEach
void tearDown() {
// 清理所有测试公告
List<String> titlesToDelete = Arrays.asList("测试1", "测试2", "测试3", "测试");
repo.delete(new QueryWrapper<Bulletin>().in("title", titlesToDelete));
}
private Bulletin createAndInsertBulletin(String title) {
Bulletin bulletin = BulletinBuilder.bBulletin().title(title).build();
repo.insert(bulletin);
return bulletin;
bulletin1 = BulletinBuilder.bBulletin().title("测试1").build();
repo.insert(bulletin1);
bulletin2 = BulletinBuilder.bBulletin().title("测试2").build();
repo.insert(bulletin2);
}
@Test
@ -61,38 +45,45 @@ public class BulletinServiceTest {
@Test
void createBulletin() {
BulletinDto dto = createBulletinDto("测试", true, "测试测试", "测试公告增加");
BulletinDto dto = new BulletinDto();
dto.setTitle("测试");
dto.setTop(true);
dto.setContent("测试测试");
dto.setRemark("测试公告增加");
BulletinDto dto2 = new BulletinDto();
dto2.setTitle(bulletin2.getTitle());
// dto2.setTop(bulletin2.isTop());
dto2.setRemark(bulletin2.getRemark());
UserDetailsImpl userDetails = new UserDetailsImpl();
userDetails.setUsername("admin");
Bulletin bulletin = service.create(userDetails, dto);
assertNotNull(bulletin.getId());
List<Bulletin> list = service.list();
assertEquals(3, list.size());
// 不能创建其他已存在标题公告
assertThrows(ConstraintException.class, () -> service.create(userDetails, createBulletinDto(bulletin2.getTitle(), false, "", "")));
assertThrows(ConstraintException.class, () -> service.create(userDetails, dto2));
}
@Test
void updateBulletin() {
BulletinDto dto = createBulletinDto("测试3", true, "测试测", "测试公告更新");
assertTrue(service.update(userDetails, dto, bulletin2.getId()));
Bulletin updatedBulletin = service.getOne(new LambdaQueryWrapper<Bulletin>().eq(Bulletin::getTitle, dto.getTitle()));
assertNotNull(updatedBulletin);
assertEquals(dto.getTitle(), updatedBulletin.getTitle());
assertEquals(bulletin2.getId(), updatedBulletin.getId());
// 不能改为其他已存在的同名公告
assertThrows(ConstraintException.class,
() -> service.update(userDetails, createBulletinDto(bulletin1.getTitle(), true, "测试测试", "测试公告更新"), bulletin2.getId()));
BulletinDto dto = new BulletinDto();
dto.setTitle("测试3");
dto.setContent("测试测");
dto.setTop(true);
dto.setRemark("测试公告更新");
UserDetailsImpl userDetails = new UserDetailsImpl();
userDetails.setUsername("admin");
assertTrue(service.update(userDetails, dto, bulletin2.id));
Bulletin bulletin = service.getOne(new LambdaQueryWrapper<Bulletin>().eq(Bulletin::getTitle, dto.getTitle()));
assertEquals(bulletin.getTitle(), dto.getTitle());
assertEquals(bulletin.getId(), bulletin2.id);
// 不能改为其他已存在的同名同代码部门
// assertThrows(ConstraintException.class,
// () -> service.update(userDetails, new BulletinDto(bulletin1.getTitle(), true, null, null), bulletin2.id));
}
private BulletinDto createBulletinDto(String title, boolean top, String content, String remark) {
BulletinDto dto = new BulletinDto();
dto.setTitle(title);
dto.setTop(top);
dto.setContent(content);
dto.setRemark(remark);
return dto;
@AfterEach
void tearDown() {
repo.delete(new QueryWrapper<>());
}
}

View File

@ -58,9 +58,9 @@ class DeptServiceTest {
@Test
void list() {
LambdaQueryWrapper<Dept> queryWrapper = new LambdaQueryWrapper<>();
assertEquals(1, service.list(queryWrapper.like(Dept::getName, "测试部门1")).size());
// assertEquals(1, service.list(queryWrapper.eq(Dept::getName, dept1.getName())).size());
// assertEquals(4, service.list().size());
assertEquals(4, service.list(queryWrapper.like(Dept::getName, "测试部门")).size());
assertEquals(1, service.list(queryWrapper.eq(Dept::getName, dept1.getName())).size());
assertEquals(4, service.list().size());
}
// @Test

View File

@ -1,97 +0,0 @@
package com.zsc.edu.gateway.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zsc.edu.gateway.domain.ParamBuilder;
import com.zsc.edu.gateway.exception.ConstraintException;
import com.zsc.edu.gateway.modules.iot.tsl.dto.ParamDto;
import com.zsc.edu.gateway.modules.iot.tsl.entity.DataType;
import com.zsc.edu.gateway.modules.iot.tsl.entity.Param;
import com.zsc.edu.gateway.modules.iot.tsl.repo.ParamRepository;
import com.zsc.edu.gateway.modules.iot.tsl.service.ParamService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
public class ParamServiceTest {
@Autowired
private ParamService service;
@Autowired
private ParamRepository repo;
private Param param1;
private Param param2;
@BeforeEach
void setUp() {
param1 = ParamBuilder.aParam().uint("测试1").build();
repo.insert(param1);
param2 = ParamBuilder.aParam().uint("测试2").build();
repo.insert(param2);
}
@Test
void list() {
LambdaQueryWrapper<Param> queryWrapper = new LambdaQueryWrapper<>();
assertEquals(2, service.list(queryWrapper.like(Param::getUint, "测试")).size());
assertEquals(1, service.list(queryWrapper.eq(Param::getUint, param1.getUint())).size());
// assertEquals(2, service.list().size());
}
@Test
void createParams() {
List<ParamDto> params = createParamDtoList();
Long foreignId = 1L;
Boolean result = service.create(params, foreignId, null);
assertTrue(result);
List<Param> insertedParams = service.list(new LambdaQueryWrapper<Param>().like(Param::getName, "PARAM_NAME"));
assertEquals(2, insertedParams.size()); // 因为setUp方法已经插入了两个参数
}
@Test
void updateParams() {
ParamDto dto = new ParamDto();
dto.setName("PARAM_NAME_UPDATE");
dto.setIdentifier("测试更新");
List<ParamDto> params = new ArrayList<>();
params.add(dto);
assertTrue(service.update(params, param2.getId()));
// 确保获取到的 param 对象是最新的
Param param = repo.selectById(param2.getId());
assertNotNull(param); // 确保 param 不为空
// 更新后的 identifier 应该是 "测试更新"
assertEquals("测试更新", param.getIdentifier());
assertEquals(param2.getId(), param.getId());
}
@AfterEach
void tearDown() {
repo.delete(new LambdaQueryWrapper<Param>()
.in(Param::getId, param1.getId(), param2.getId())
.or()
.in(Param::getName, "PARAM_NAME_1", "PARAM_NAME_2", "PARAM_NAME_UPDATE"));
}
private List<ParamDto> createParamDtoList() {
ParamDto paramDto1 = new ParamDto();
paramDto1.setName("PARAM_NAME_1");
paramDto1.setIdentifier("PARAM_VALUE_1");
paramDto1.setDataType(DataType.DATE);
ParamDto paramDto2 = new ParamDto();
paramDto2.setName("PARAM_NAME_2");
paramDto2.setIdentifier("PARAM_VALUE_2");
paramDto2.setDataType(DataType.DATE);
return Arrays.asList(paramDto1, paramDto2);
}
}

View File

@ -41,24 +41,24 @@ class RoleServiceTest {
// @Resource
private AuthorityRepository authorityRepository;
// @BeforeEach
// void setUp() {
// role1 = RoleBuilder.aRole().name("超级管理员").build();
// repo.insert(role1);
// role2 = RoleBuilder.aRole().name("普通用户").build();
// repo.insert(role2);
// }
//
// @AfterEach
// void tearDown() {
// repo.delete(new QueryWrapper<>());
// }
@BeforeEach
void setUp() {
role1 = RoleBuilder.aRole().name("超级管理员").build();
repo.insert(role1);
role2 = RoleBuilder.aRole().name("普通用户").build();
repo.insert(role2);
}
@AfterEach
void tearDown() {
repo.delete(new QueryWrapper<>());
}
@Test
void list() {
assertEquals(1, service.list().size());
assertEquals(0, service.list(new LambdaQueryWrapper<Role>().like(Role::getName, "普通用户")).size());
// assertEquals(1, service.list(new LambdaQueryWrapper<Role>().eq(Role::getName, role1.getName())).size());
assertEquals(2, service.list().size());
assertEquals(1, service.list(new LambdaQueryWrapper<Role>().like(Role::getName, "普通用户")).size());
assertEquals(1, service.list(new LambdaQueryWrapper<Role>().eq(Role::getName, role1.getName())).size());
}
@Test

View File

@ -8,7 +8,6 @@ import com.zsc.edu.gateway.modules.system.repo.UserRepository;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.Set;
@ -24,9 +23,6 @@ public class UserServiceTest {
private UserRepository userRepository;
@Resource
private AuthorityRepository authorityRepository;
@Resource
private PasswordEncoder passwordEncoder;
@Test
void test() {
User user=userRepository.selectByUsername("admin");
@ -37,9 +33,8 @@ public class UserServiceTest {
}
@Test
void test1() {
// User user=userRepository.selectByUsername("admin");
// System.out.println(user);
String admin = passwordEncoder.encode("admin");
System.out.println(admin);
User user=userRepository.selectByUsername("admin");
System.out.println(user);
}
}