提交 9f43851e 编写于 作者: Z zhengjie

1.7版本发布,详情查看版本说明

上级 1402e584
# eladmin
项目基于 Spring Boot 2.1.0 、 Spring boot Jpa、 Spring Security、redis、Vue的前后端分离的权限管理系统,项目采用分模块开发方式, 权限控制采用 RBAC(Role-Based Access Control,基于角色的访问控制),前端菜单支持动态路由
项目基于 Spring Boot 2.1.0 、 Spring boot Jpa、 Spring Security、redis、Vue的前后端分离的权限管理系统,项目采用分模块开发方式, 权限控制采用 RBAC(Role-Based Access Control,基于角色的访问控制),支持数据字典、数据权限管理、前端菜单支持动态路由
#### 前端源码
eladmin-qt和eladmin-qd只是命名方式的区别,无其他区别
- 码云:[https://gitee.com/elunez/eladmin-qt](https://gitee.com/elunez/eladmin-qt)
- github:[https://github.com/elunez/eladmin-qd](https://github.com/elunez/eladmin-qd)
#### 项目源码
#### eladmin开发文档
[http://docs.auauz.net/#/](http://docs.auauz.net/#/)
| | 后端源码 | 前端源码 |
|--- |--- | --- |
| github | https://github.com/elunez/eladmin | https://github.com/elunez/eladmin-qd |
| 码云 | https://github.com/elunez/eladmin | https://gitee.com/elunez/eladmin-qt |
#### 开发文档
[https://docs.auauz.net/#/](https://docs.auauz.net/#/)
#### 预览地址
[http://auauz.net](http://auauz.net)
[https://auauz.net](https://auauz.net)
##### 用户账号密码
......@@ -23,7 +24,7 @@ eladmin-qt和eladmin-qd只是命名方式的区别,无其他区别
- JDK:8
- IDE:IntelliJ IDEA (后端)
- IDE:JetBrains WebStorm (前端)
- IDE:JetBrains WebStorm(前端)
- 依赖管理:Maven
- 数据库:MySQL 5.5.59
......@@ -31,19 +32,21 @@ eladmin-qt和eladmin-qd只是命名方式的区别,无其他区别
```
- 系统管理
- 用户管理 提供用户的相关配置
- 角色管理 角色菜单进行权限的分配
- Swagger文档 localhost:8000/swagger-ui.html
- 角色管理 对权限与菜单进行分配
- 权限管理 权限细化到接口
- 菜单管理 已实现菜单动态路由,后端可配置化,支持多级菜单
- 定时任务 整合Quartz做定时任务,加入任务日志,任务运行情况一目了然
- 代码生成 高灵活度一键生成前后端代码,减少百分之80左右的工作任务
- 部门管理与岗位管理
- 字典管理 应广大码友的要求加入字典管理
- 系统监控
- 操作日志 使用apo记录用户操作日志
- 异常日志 记录操作过程中的异常,并且提供查看异常的堆栈信息
- 系统缓存 使用jedis将缓存操作可视化,并提供对redis的基本操作,可根据需求自行扩展
- 实时控制台 实时打印logback日志,来自微强迫症患者的精心配色,更好的监控系统的运行状态
- SQL监控 采用druid 监控数据库访问性能,默认用户名admin,密码123456
- 三方工具
- 系统工具
- 定时任务 整合Quartz做定时任务,加入任务日志,任务运行情况一目了然
- 代码生成 高灵活度一键生成前后端代码,减少百分之80左右的工作任务
- 接口文档 使用的是 swagger-ui
- 邮件工具 配合富文本,发送html格式的邮件
- SM.MS免费图床 挺好用的一个图床,作为公共图片上传使用
- 七牛云存储 这个就不多说了
......@@ -51,6 +54,7 @@ eladmin-qt和eladmin-qd只是命名方式的区别,无其他区别
- 组件管理
- 图标库 系统图标来自 https://www.iconfont.cn/
- 富文本 集成wangEditor富文本
- Markdown编辑器与Yaml编辑器
```
#### 项目结构
```
......@@ -133,8 +137,7 @@ eladmin-qt和eladmin-qd只是命名方式的区别,无其他区别
| 微信 | 支付宝 |
|--- | --- |
| ![](https://i.imgur.com/QJ2pqyg.png) | ![](https://i.imgur.com/eO95P7Q.png) |
| ![](https://i.loli.net/2019/03/28/5c9c951c61a9a.png) | ![](https://i.loli.net/2019/03/28/5c9c95355fecb.png) |
#### 反馈交流
- QQ交流群:891137268
......@@ -19,7 +19,6 @@ import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.time.Duration;
......@@ -31,6 +30,7 @@ import java.time.Duration;
@Slf4j
@Configuration
@EnableCaching
// 自动配置
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig extends CachingConfigurerSupport {
......@@ -91,6 +91,7 @@ public class RedisConfig extends CachingConfigurerSupport {
// value值的序列化采用fastJsonRedisSerializer
template.setValueSerializer(fastJsonRedisSerializer);
template.setHashValueSerializer(fastJsonRedisSerializer);
// 全局开启AutoType,不建议使用
// ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
// 建议使用这种方式,小范围指定白名单
......
......@@ -47,7 +47,7 @@ public class SwaggerConfig {
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("elune 接口文档")
.version("1.5")
.version("1.7")
.build();
}
......
......@@ -95,6 +95,6 @@ public class EncryptUtils {
}
public static void main(String[] args) {
System.out.println(encryptPassword("e10adc3949ba59abbe56e057f20f883e"));
System.out.println(encryptPassword("123456"));
}
}
package me.zhengjie.utils;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.*;
/**
* @author jie
* @date 2019-01-08
*/
@Configuration
public class ThreadPoolUtil {
@Bean
public ExecutorService getThreadPool(){
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("thread-call-runner-%d").build();
int size = 2;
ExecutorService executorService = new ThreadPoolExecutor(size,size,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(),namedThreadFactory);
return executorService;
}
}
......@@ -21,7 +21,7 @@ import org.springframework.stereotype.Component;
@Component
@Aspect
@Slf4j
public class LogAspect {
public class DataScopeAspect {
@Autowired
private LogService logService;
......
......@@ -2,6 +2,7 @@ package me.zhengjie.rest;
import me.zhengjie.domain.Log;
import me.zhengjie.service.query.LogQueryService;
import me.zhengjie.utils.SecurityContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
......@@ -29,6 +30,13 @@ public class LogController {
return new ResponseEntity(logQueryService.queryAll(log,pageable), HttpStatus.OK);
}
@GetMapping(value = "/logs/user")
public ResponseEntity getUserLogs(Log log, Pageable pageable){
log.setLogType("INFO");
log.setUsername(SecurityContextHolder.getUserDetails().getUsername());
return new ResponseEntity(logQueryService.queryAll(log,pageable), HttpStatus.OK);
}
@GetMapping(value = "/logs/error")
@PreAuthorize("hasAnyRole('ADMIN')")
public ResponseEntity getErrorLogs(Log log, Pageable pageable){
......
......@@ -10,7 +10,6 @@ import me.zhengjie.utils.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
......@@ -29,9 +28,6 @@ public class LogServiceImpl implements LogService {
@Autowired
private LogRepository logRepository;
@Value("${jwt.header}")
private String tokenHeader;
private final String LOGINPATH = "login";
@Override
......
此差异已折叠。
package me.zhengjie.config;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.utils.SecurityContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* 数据权限配置
* @author jie
* @date 2019-4-1
*/
@Component
public class DataScope {
private final String[] scopeType = {"全部","本级","自定义"};
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private DeptService deptService;
public Set<Long> getDeptIds() {
User user = userService.findByName(SecurityContextHolder.getUserDetails().getUsername());
// 用于存储部门id
Set<Long> deptIds = new HashSet<>();
// 查询用户角色
List<Role> roleSet = roleService.findByUsers_Id(user.getId());
for (Role role : roleSet) {
if (scopeType[0].equals(role.getDataScope())) {
return new HashSet<>() ;
}
// 存储本级的数据权限
if (scopeType[1].equals(role.getDataScope())) {
deptIds.add(user.getDept().getId());
}
// 存储自定义的数据权限
if (scopeType[2].equals(role.getDataScope())) {
Set<Dept> deptList = role.getDepts();
for (Dept dept : deptList) {
deptIds.add(dept.getId());
List<Dept> deptChildren = deptService.findByPid(dept.getId());
if (deptChildren != null && deptChildren.size() != 0) {
deptIds.addAll(getDeptChildren(deptChildren));
}
}
}
}
return deptIds;
}
public List<Long> getDeptChildren(List<Dept> deptList) {
List<Long> list = new ArrayList<>();
deptList.forEach(dept -> {
if (dept!=null && dept.getEnabled()){
List<Dept> depts = deptService.findByPid(dept.getId());
if(deptList!=null && deptList.size()!=0){
list.addAll(getDeptChildren(depts));
}
list.add(dept.getId());
}
}
);
return list;
}
}
......@@ -11,14 +11,13 @@ import java.util.Date;
/**
* 定义Logfilter拦截输出日志
* @author jie
* @reference https://cloud.tencent.com/developer/article/1096792
* @date 2018-12-24
*/
public class LogFilter extends Filter<ILoggingEvent>{
@Override
public FilterReply decide(ILoggingEvent event) {
String exception = "";
IThrowableProxy iThrowableProxy1 = event.getThrowableProxy();
LogMessage loggerMessage = new LogMessage(
event.getFormattedMessage(),
DateFormat.getDateTimeInstance().format(new Date(event.getTimeStamp())),
......
......@@ -6,7 +6,7 @@ import java.util.concurrent.LinkedBlockingQueue;
/**
* 创建一个阻塞队列,作为日志系统输出的日志的一个临时载体
* @author jie
* @author https://cloud.tencent.com/developer/article/1096792
* @date 2018-12-24
*/
public class LoggerQueue {
......
package me.zhengjie.modules.monitor.config;
import me.zhengjie.modules.monitor.service.VisitsService;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
/**
* 初始化站点统计
* @author jie
*/
@Configuration
public class VisitsInitialization {
@Component
public class VisitsInitialization implements ApplicationRunner {
public VisitsInitialization(VisitsService visitsService){
@Autowired
private VisitsService visitsService;
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("--------------- 初始化站点统计,如果存在今日统计则跳过 ---------------");
visitsService.save();
System.out.println("--------------- 初始化站点统计完成 ---------------");
......
......@@ -9,10 +9,12 @@ import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 配置WebSocket消息代理端点,即stomp服务端
* @author jie
* @reference https://cloud.tencent.com/developer/article/1096792
* @date 2018-12-24
*/
@Slf4j
......@@ -22,8 +24,7 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Autowired
private SimpMessagingTemplate messagingTemplate;
@Autowired
private ExecutorService executorService;
private ExecutorService executorService = Executors.newSingleThreadExecutor();
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
......
......@@ -4,7 +4,7 @@ import lombok.AllArgsConstructor;
import lombok.Data;
/**
* @author 郑杰
* @author https://cloud.tencent.com/developer/article/1096792
* @date 2018-12-24
*/
@Data
......
......@@ -82,7 +82,7 @@ public class RedisServiceImpl implements RedisService {
Jedis jedis = null;
try{
jedis = pool.getResource();
jedis.flushDB();
jedis.flushAll();
}finally{
if(null != jedis){
jedis.close(); // 释放资源还给连接池
......
......@@ -7,6 +7,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import java.util.List;
/**
......
......@@ -7,14 +7,12 @@ import me.zhengjie.modules.quartz.service.QuartzJobService;
import me.zhengjie.utils.SpringContextHolder;
import me.zhengjie.utils.ThrowableUtil;
import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.quartz.QuartzJobBean;
import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
......@@ -25,13 +23,9 @@ import java.util.concurrent.Future;
@Async
public class ExecutionJob extends QuartzJobBean {
@Resource(name = "scheduler")
private Scheduler scheduler;
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private ExecutorService executorService;
private ExecutorService executorService = Executors.newSingleThreadExecutor();
@Override
protected void executeInternal(JobExecutionContext context) {
......
......@@ -110,9 +110,8 @@ public class QuartzManage {
TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId());
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
// 如果不存在则创建一个定时任务
if(trigger == null){
if(trigger == null)
addJob(quartzJob);
}
JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());
scheduler.resumeJob(jobKey);
} catch (Exception e){
......@@ -131,9 +130,8 @@ public class QuartzManage {
TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId());
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
// 如果不存在则创建一个定时任务
if(trigger == null){
if(trigger == null)
addJob(quartzJob);
}
JobDataMap dataMap = new JobDataMap();
dataMap.put(QuartzJob.JOB_KEY, quartzJob);
JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());
......
......@@ -93,12 +93,13 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
.antMatchers( HttpMethod.POST,"/auth/"+loginPath).permitAll()
.antMatchers("/websocket/**").permitAll()
.antMatchers("/druid/**").anonymous()
// 支付宝回调
.antMatchers("/api/aliPay/return").anonymous()
.antMatchers("/api/aliPay/notify").anonymous()
// 系统监控
.antMatchers("/actuator/**").anonymous()
// swagger start
.antMatchers("/swagger-ui.html").anonymous()
.antMatchers("/swagger-resources/**").anonymous()
......@@ -110,8 +111,11 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
.antMatchers("/test/**").anonymous()
.antMatchers(HttpMethod.OPTIONS, "/**").anonymous()
.antMatchers("/druid/**").permitAll()
// 所有请求都需要认证
.anyRequest().authenticated();
.anyRequest().authenticated()
// 防止iframe 造成跨域
.and().headers().frameOptions().disable();
httpSecurity
.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
......
......@@ -34,7 +34,6 @@ public class JwtAuthorizationTokenFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
log.debug("processing authentication for '{}'", request.getRequestURL());
final String requestHeader = request.getHeader(this.tokenHeader);
......@@ -49,10 +48,7 @@ public class JwtAuthorizationTokenFilter extends OncePerRequestFilter {
}
}
log.debug("checking authentication for user '{}'", username);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
log.debug("security context was null, so authorizating user");
// It is not compelling necessary to load the use details from the database. You could also store the information
// in the token and read it from it. It's up to you ;)
......
......@@ -30,8 +30,14 @@ public class JwtUser implements UserDetails {
private final String email;
private final String phone;
private final String dept;
private final String job;
@JsonIgnore
private final Collection<? extends GrantedAuthority> authorities;
private final Collection<GrantedAuthority> authorities;
private final boolean enabled;
......
package me.zhengjie.modules.security.service;
import me.zhengjie.modules.system.domain.Permission;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.PermissionRepository;
import me.zhengjie.modules.system.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
@Service
@CacheConfig(cacheNames = "role")
public class JwtPermissionService {
@Autowired
private RoleRepository roleRepository;
@Autowired
private PermissionRepository permissionRepository;
@Cacheable(key = "'loadPermissionByUser:' + #p0.username")
public Collection<GrantedAuthority> mapToGrantedAuthorities(User user) {
System.out.println("--------------------loadPermissionByUser:" + user.getUsername() + "---------------------");
Set<Role> roles = roleRepository.findByUsers_Id(user.getId());
Set<Permission> permissions = new HashSet<>();
for (Role role : roles) {
Set<Role> roleSet = new HashSet<>();
roleSet.add(role);
permissions.addAll(permissionRepository.findByRoles_Id(role.getId()));
}
return permissions.stream()
.map(permission -> new SimpleGrantedAuthority(permission.getName()))
.collect(Collectors.toList());
}
}
......@@ -6,10 +6,10 @@ import me.zhengjie.modules.system.domain.User;
import me.zhengjie.exception.EntityNotFoundException;
import me.zhengjie.modules.system.repository.PermissionRepository;
import me.zhengjie.modules.system.repository.RoleRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.security.security.JwtUser;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
......@@ -31,56 +31,36 @@ import java.util.stream.Collectors;
public class JwtUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
private UserService userService;
@Autowired
private RoleRepository roleRepository;
@Autowired
private PermissionRepository permissionRepository;
private JwtPermissionService permissionService;
@Override
public UserDetails loadUserByUsername(String username){
User user = null;
if(ValidationUtil.isEmail(username)){
user = userRepository.findByEmail(username);
} else {
user = userRepository.findByUsername(username);
}
User user = userService.findByName(username);
if (user == null) {
throw new EntityNotFoundException(User.class, "name", username);
} else {
return create(user);
return createJwtUser(user);
}
}
public UserDetails create(User user) {
public UserDetails createJwtUser(User user) {
return new JwtUser(
user.getId(),
user.getUsername(),
user.getPassword(),
user.getAvatar(),
user.getEmail(),
mapToGrantedAuthorities(roleRepository.findByUsers_Id(user.getId()),permissionRepository),
user.getPhone(),
user.getDept().getName(),
user.getJob().getName(),
permissionService.mapToGrantedAuthorities(user),
user.getEnabled(),
user.getCreateTime(),
user.getLastPasswordResetTime()
);
}
private static List<GrantedAuthority> mapToGrantedAuthorities(Set<Role> roles,PermissionRepository permissionRepository) {
Set<Permission> permissions = new HashSet<>();
for (Role role : roles) {
Set<Role> roleSet = new HashSet<>();
roleSet.add(role);
permissions.addAll(permissionRepository.findByRoles_Id(role.getId()));
}
return permissions.stream()
.map(permission -> new SimpleGrantedAuthority(permission.getName()))
.collect(Collectors.toList());
}
}
package me.zhengjie.modules.system.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.hibernate.annotations.CreationTimestamp;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.sql.Timestamp;
import java.io.Serializable;
import java.util.Set;
/**
* @author jie
* @date 2019-03-25
*/
@Entity
@Data
@Table(name="dept")
public class Dept implements Serializable {
/**
* ID
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
@NotNull(groups = Update.class)
private Long id;
/**
* 名称
*/
@Column(name = "name",nullable = false)
@NotBlank
private String name;
@NotNull
private Boolean enabled;
/**
* 上级部门
*/
@Column(name = "pid",nullable = false)
@NotNull
private Long pid;
@Column(name = "create_time")
@CreationTimestamp
private Timestamp createTime;
@ManyToMany(mappedBy = "depts")
@JsonIgnore
private Set<Role> roles;
public @interface Update {}
}
\ No newline at end of file
package me.zhengjie.modules.system.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
/**
* @author jie
* @date 2019-04-10
*/
@Entity
@Data
@Table(name="dict")
public class Dict implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
@NotNull(groups = Update.class)
private Long id;
/**
* 字典名称
*/
@Column(name = "name",nullable = false,unique = true)
@NotBlank
private String name;
/**
* 描述
*/
@Column(name = "remark")
private String remark;
@OneToMany(mappedBy = "dict",cascade={CascadeType.PERSIST,CascadeType.REMOVE})
private List<DictDetail> dictDetails;
public @interface Update {}
}
\ No newline at end of file
package me.zhengjie.modules.system.domain;
import lombok.Data;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
/**
* @author jie
* @date 2019-04-10
*/
@Entity
@Data
@Table(name="dict_detail")
public class DictDetail implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
@NotNull(groups = Update.class)
private Long id;
/**
* 字典标签
*/
@Column(name = "label",nullable = false)
private String label;
/**
* 字典值
*/
@Column(name = "value",nullable = false)
private String value;
/**
* 排序
*/
@Column(name = "sort")
private String sort = "999";
/**
* 字典id
*/
@ManyToOne
@JoinColumn(name = "dict_id")
private Dict dict;
public @interface Update {}
}
\ No newline at end of file
package me.zhengjie.modules.system.domain;
import lombok.Data;
import org.hibernate.annotations.*;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.sql.Timestamp;
import java.io.Serializable;
/**
* @author jie
* @date 2019-03-29
*/
@Entity
@Data
@Table(name="job")
public class Job implements Serializable {
/**
* ID
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
@NotNull(groups = Update.class)
private Long id;
/**
* 名称
*/
@Column(name = "name",nullable = false)
@NotBlank
private String name;
@Column(unique = true)
@NotNull
private Long sort;
/**
* 状态
*/
@Column(name = "enabled",nullable = false)
@NotNull
private Boolean enabled;
@OneToOne
@JoinColumn(name = "dept_id")
private Dept dept;
/**
* 创建日期
*/
@Column(name = "create_time")
@CreationTimestamp
private Timestamp createTime;
public @interface Update {}
}
\ No newline at end of file
......@@ -30,6 +30,7 @@ public class Menu implements Serializable {
private String name;
@Column(unique = true)
@NotNull
private Long sort;
@Column(name = "path")
......
......@@ -32,6 +32,10 @@ public class Role implements Serializable {
@NotBlank
private String name;
// 数据权限类型 全部 、 本级 、 自定义
@Column(name = "data_scope")
private String dataScope = "本级";
@Column
private String remark;
......@@ -47,6 +51,10 @@ public class Role implements Serializable {
@JoinTable(name = "roles_menus", joinColumns = {@JoinColumn(name = "role_id",referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "menu_id",referencedColumnName = "id")})
private Set<Menu> menus;
@ManyToMany
@JoinTable(name = "roles_depts", joinColumns = {@JoinColumn(name = "role_id",referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "dept_id",referencedColumnName = "id")})
private Set<Dept> depts;
@CreationTimestamp
@Column(name = "create_time")
private Timestamp createTime;
......
......@@ -29,6 +29,7 @@ public class User implements Serializable {
private Long id;
@NotBlank
@Column(unique = true)
private String username;
private String avatar;
......@@ -37,6 +38,9 @@ public class User implements Serializable {
@Pattern(regexp = "([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}",message = "格式错误")
private String email;
@NotBlank
private String phone;
@NotNull
private Boolean enabled;
......@@ -53,6 +57,14 @@ public class User implements Serializable {
@JoinTable(name = "users_roles", joinColumns = {@JoinColumn(name = "user_id",referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "role_id",referencedColumnName = "id")})
private Set<Role> roles;
@OneToOne
@JoinColumn(name = "job_id")
private Job job;
@OneToOne
@JoinColumn(name = "dept_id")
private Dept dept;
@Override
public String toString() {
return "User{" +
......
package me.zhengjie.modules.system.repository;
import me.zhengjie.modules.system.domain.Dept;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import java.util.List;
import java.util.Set;
/**
* @author jie
* @date 2019-03-25
*/
public interface DeptRepository extends JpaRepository<Dept, Long>, JpaSpecificationExecutor {
/**
* findByPid
* @param id
* @return
*/
List<Dept> findByPid(Long id);
Set<Dept> findByRoles_Id(Long id);
}
\ No newline at end of file
package me.zhengjie.modules.system.repository;
import me.zhengjie.modules.system.domain.DictDetail;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @author jie
* @date 2019-04-10
*/
public interface DictDetailRepository extends JpaRepository<DictDetail, Long>, JpaSpecificationExecutor {
}
\ No newline at end of file
package me.zhengjie.modules.system.repository;
import me.zhengjie.modules.system.domain.Dict;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @author jie
* @date 2019-04-10
*/
public interface DictRepository extends JpaRepository<Dict, Long>, JpaSpecificationExecutor {
}
\ No newline at end of file
package me.zhengjie.modules.system.repository;
import me.zhengjie.modules.system.domain.Job;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @author jie
* @date 2019-03-29
*/
public interface JobRepository extends JpaRepository<Job, Long>, JpaSpecificationExecutor {
}
\ No newline at end of file
......@@ -20,4 +20,6 @@ public interface RoleRepository extends JpaRepository<Role, Long>, JpaSpecificat
Role findByName(String name);
Set<Role> findByUsers_Id(Long id);
Set<Role> findByMenus_Id(Long id);
}
package me.zhengjie.modules.system.repository;
import me.zhengjie.modules.system.domain.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import java.util.Date;
import java.util.List;
/**
* @author jie
......@@ -29,28 +33,28 @@ public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificat
/**
* 修改密码
* @param id
* @param username
* @param pass
*/
@Modifying
@Query(value = "update user set password = ?2 , last_password_reset_time = ?3 where id = ?1",nativeQuery = true)
void updatePass(Long id, String pass, Date lastPasswordResetTime);
@Query(value = "update user set password = ?2 , last_password_reset_time = ?3 where username = ?1",nativeQuery = true)
void updatePass(String username, String pass, Date lastPasswordResetTime);
/**
* 修改头像
* @param id
* @param username
* @param url
*/
@Modifying
@Query(value = "update user set avatar = ?2 where id = ?1",nativeQuery = true)
void updateAvatar(Long id, String url);
@Query(value = "update user set avatar = ?2 where username = ?1",nativeQuery = true)
void updateAvatar(String username, String url);
/**
* 修改邮箱
* @param id
* @param username
* @param email
*/
@Modifying
@Query(value = "update user set email = ?2 where id = ?1",nativeQuery = true)
void updateEmail(Long id, String email);
@Query(value = "update user set email = ?2 where username = ?1",nativeQuery = true)
void updateEmail(String username, String email);
}
package me.zhengjie.modules.system.rest;
import me.zhengjie.aop.log.Log;
import me.zhengjie.config.DataScope;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.dto.DeptDTO;
import me.zhengjie.modules.system.service.query.DeptQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Set;
/**
* @author jie
* @date 2019-03-25
*/
@RestController
@RequestMapping("api")
public class DeptController {
@Autowired
private DeptService deptService;
@Autowired
private DeptQueryService deptQueryService;
@Autowired
private DataScope dataScope;
private static final String ENTITY_NAME = "dept";
@Log("查询部门")
@GetMapping(value = "/dept")
@PreAuthorize("hasAnyRole('ADMIN','USER_ALL','USER_SELECT','DEPT_ALL','DEPT_SELECT')")
public ResponseEntity getDepts(DeptDTO resources){
// 数据权限
Set<Long> deptIds = dataScope.getDeptIds();
List<DeptDTO> deptDTOS = deptQueryService.queryAll(resources, deptIds);
return new ResponseEntity(deptService.buildTree(deptDTOS),HttpStatus.OK);
}
@Log("新增部门")
@PostMapping(value = "/dept")
@PreAuthorize("hasAnyRole('ADMIN','DEPT_ALL','DEPT_CREATE')")
public ResponseEntity create(@Validated @RequestBody Dept resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
return new ResponseEntity(deptService.create(resources),HttpStatus.CREATED);
}
@Log("修改部门")
@PutMapping(value = "/dept")
@PreAuthorize("hasAnyRole('ADMIN','DEPT_ALL','DEPT_EDIT')")
public ResponseEntity update(@Validated(Dept.Update.class) @RequestBody Dept resources){
deptService.update(resources);
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
@Log("删除部门")
@DeleteMapping(value = "/dept/{id}")
@PreAuthorize("hasAnyRole('ADMIN','DEPT_ALL','DEPT_DELETE')")
public ResponseEntity delete(@PathVariable Long id){
deptService.delete(id);
return new ResponseEntity(HttpStatus.OK);
}
}
\ No newline at end of file
package me.zhengjie.modules.system.rest;
import me.zhengjie.aop.log.Log;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.Dict;
import me.zhengjie.modules.system.service.DictService;
import me.zhengjie.modules.system.service.dto.DictDTO;
import me.zhengjie.modules.system.service.query.DictQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
/**
* @author jie
* @date 2019-04-10
*/
@RestController
@RequestMapping("api")
public class DictController {
@Autowired
private DictService dictService;
@Autowired
private DictQueryService dictQueryService;
private static final String ENTITY_NAME = "dict";
@Log("查询字典")
@GetMapping(value = "/dict")
@PreAuthorize("hasAnyRole('ADMIN','DICT_ALL','DICT_SELECT')")
public ResponseEntity getDicts(DictDTO resources, Pageable pageable){
return new ResponseEntity(dictQueryService.queryAll(resources,pageable),HttpStatus.OK);
}
@Log("新增字典")
@PostMapping(value = "/dict")
@PreAuthorize("hasAnyRole('ADMIN','DICT_ALL','DICT_CREATE')")
public ResponseEntity create(@Validated @RequestBody Dict resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
return new ResponseEntity(dictService.create(resources),HttpStatus.CREATED);
}
@Log("修改字典")
@PutMapping(value = "/dict")
@PreAuthorize("hasAnyRole('ADMIN','DICT_ALL','DICT_EDIT')")
public ResponseEntity update(@Validated(Dict.Update.class) @RequestBody Dict resources){
dictService.update(resources);
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
@Log("删除字典")
@DeleteMapping(value = "/dict/{id}")
@PreAuthorize("hasAnyRole('ADMIN','DICT_ALL','DICT_DELETE')")
public ResponseEntity delete(@PathVariable Long id){
dictService.delete(id);
return new ResponseEntity(HttpStatus.OK);
}
}
\ No newline at end of file
package me.zhengjie.modules.system.rest;
import me.zhengjie.aop.log.Log;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.service.DictDetailService;
import me.zhengjie.modules.system.service.dto.DictDetailDTO;
import me.zhengjie.modules.system.service.query.DictDetailQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
/**
* @author jie
* @date 2019-04-10
*/
@RestController
@RequestMapping("api")
public class DictDetailController {
@Autowired
private DictDetailService dictDetailService;
@Autowired
private DictDetailQueryService dictDetailQueryService;
private static final String ENTITY_NAME = "dictDetail";
@Log("查询字典详情")
@GetMapping(value = "/dictDetail")
public ResponseEntity getDictDetails(DictDetailDTO resources,
@PageableDefault(value = 10, sort = {"sort"}, direction = Sort.Direction.ASC) Pageable pageable){
return new ResponseEntity(dictDetailQueryService.queryAll(resources,pageable),HttpStatus.OK);
}
@Log("新增字典详情")
@PostMapping(value = "/dictDetail")
@PreAuthorize("hasAnyRole('ADMIN','DICT_ALL','DICT_CREATE')")
public ResponseEntity create(@Validated @RequestBody DictDetail resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
return new ResponseEntity(dictDetailService.create(resources),HttpStatus.CREATED);
}
@Log("修改字典详情")
@PutMapping(value = "/dictDetail")
@PreAuthorize("hasAnyRole('ADMIN','DICT_ALL','DICT_EDIT')")
public ResponseEntity update(@Validated(DictDetail.Update.class) @RequestBody DictDetail resources){
dictDetailService.update(resources);
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
@Log("删除字典详情")
@DeleteMapping(value = "/dictDetail/{id}")
@PreAuthorize("hasAnyRole('ADMIN','DICT_ALL','DICT_DELETE')")
public ResponseEntity delete(@PathVariable Long id){
dictDetailService.delete(id);
return new ResponseEntity(HttpStatus.OK);
}
}
\ No newline at end of file
package me.zhengjie.modules.system.rest;
import me.zhengjie.aop.log.Log;
import me.zhengjie.config.DataScope;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.Job;
import me.zhengjie.modules.system.service.JobService;
import me.zhengjie.modules.system.service.query.JobQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Set;
/**
* @author jie
* @date 2019-03-29
*/
@RestController
@RequestMapping("api")
public class JobController {
@Autowired
private JobService jobService;
@Autowired
private JobQueryService jobQueryService;
@Autowired
private DataScope dataScope;
private static final String ENTITY_NAME = "job";
@Log("查询岗位")
@GetMapping(value = "/job")
@PreAuthorize("hasAnyRole('ADMIN','USERJOB_ALL','USERJOB_SELECT','USER_ALL','USER_SELECT')")
public ResponseEntity getJobs(@RequestParam(required = false) String name,
@RequestParam(required = false) Long deptId,
@RequestParam(required = false) Boolean enabled,
Pageable pageable){
// 数据权限
Set<Long> deptIds = dataScope.getDeptIds();
return new ResponseEntity(jobQueryService.queryAll(name, enabled , deptIds, deptId, pageable),HttpStatus.OK);
}
@Log("新增岗位")
@PostMapping(value = "/job")
@PreAuthorize("hasAnyRole('ADMIN','USERJOB_ALL','USERJOB_CREATE')")
public ResponseEntity create(@Validated @RequestBody Job resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
return new ResponseEntity(jobService.create(resources),HttpStatus.CREATED);
}
@Log("修改岗位")
@PutMapping(value = "/job")
@PreAuthorize("hasAnyRole('ADMIN','USERJOB_ALL','USERJOB_EDIT')")
public ResponseEntity update(@Validated(Job.Update.class) @RequestBody Job resources){
jobService.update(resources);
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
@Log("删除岗位")
@DeleteMapping(value = "/job/{id}")
@PreAuthorize("hasAnyRole('ADMIN','USERJOB_ALL','USERJOB_DELETE')")
public ResponseEntity delete(@PathVariable Long id){
jobService.delete(id);
return new ResponseEntity(HttpStatus.OK);
}
}
\ No newline at end of file
......@@ -8,6 +8,7 @@ import me.zhengjie.modules.system.service.MenuService;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.MenuDTO;
import me.zhengjie.modules.system.service.mapper.MenuMapper;
import me.zhengjie.modules.system.service.query.MenuQueryService;
import me.zhengjie.utils.SecurityContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -39,6 +40,9 @@ public class MenuController {
@Autowired
private RoleService roleService;
@Autowired
private MenuMapper menuMapper;
private static final String ENTITY_NAME = "menu";
/**
......@@ -59,7 +63,7 @@ public class MenuController {
* @return
*/
@GetMapping(value = "/menus/tree")
@PreAuthorize("hasAnyRole('ADMIN','MENU_ALL','MENU_SELECT','ROLES_SELECT','ROLES_ALL')")
@PreAuthorize("hasAnyRole('ADMIN','MENU_ALL','MENU_CREATE','MENU_EDIT','ROLES_SELECT','ROLES_ALL')")
public ResponseEntity getMenuTree(){
return new ResponseEntity(menuService.getMenuTree(menuService.findByPid(0L)),HttpStatus.OK);
}
......@@ -94,6 +98,14 @@ public class MenuController {
@DeleteMapping(value = "/menus/{id}")
@PreAuthorize("hasAnyRole('ADMIN','MENU_ALL','MENU_DELETE')")
public ResponseEntity delete(@PathVariable Long id){
List<Menu> menuList = menuService.findByPid(id);
// 特殊情况,对级联删除进行处理
for (Menu menu : menuList) {
roleService.untiedMenu(menu);
menuService.delete(menu.getId());
}
roleService.untiedMenu(menuService.findOne(id));
menuService.delete(id);
return new ResponseEntity(HttpStatus.OK);
}
......
......@@ -36,8 +36,8 @@ public class PermissionController {
* @return
*/
@GetMapping(value = "/permissions/tree")
@PreAuthorize("hasAnyRole('ADMIN','PERMISSION_ALL','PERMISSION_SELECT','ROLES_SELECT','ROLES_ALL')")
public ResponseEntity getRoleTree(){
@PreAuthorize("hasAnyRole('ADMIN','PERMISSION_ALL','PERMISSION_CREATE','PERMISSION_EDIT','ROLES_SELECT','ROLES_ALL')")
public ResponseEntity getTree(){
return new ResponseEntity(permissionService.getPermissionTree(permissionService.findByPid(0L)),HttpStatus.OK);
}
......
......@@ -40,10 +40,10 @@ public class RoleController {
* 返回全部的角色,新增用户时下拉选择
* @return
*/
@GetMapping(value = "/roles/tree")
@PreAuthorize("hasAnyRole('ADMIN','ROLES_ALL','USER_ALL','USER_SELECT')")
public ResponseEntity getRoleTree(){
return new ResponseEntity(roleService.getRoleTree(),HttpStatus.OK);
@GetMapping(value = "/roles/all")
@PreAuthorize("hasAnyRole('ADMIN','ROLES_ALL','USER_ALL','USER_CREATE','USER_EDIT')")
public ResponseEntity getAll(){
return new ResponseEntity(roleQueryService.queryAll(),HttpStatus.OK);
}
@Log("查询角色")
......
package me.zhengjie.modules.system.rest;
import me.zhengjie.aop.log.Log;
import me.zhengjie.config.DataScope;
import me.zhengjie.domain.Picture;
import me.zhengjie.domain.VerificationCode;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.security.security.JwtUser;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.service.PictureService;
import me.zhengjie.service.VerificationCodeService;
import me.zhengjie.utils.ElAdminConstant;
import me.zhengjie.utils.EncryptUtils;
import me.zhengjie.modules.security.utils.JwtTokenUtil;
import me.zhengjie.utils.*;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.UserDTO;
import me.zhengjie.modules.system.service.query.UserQueryService;
import me.zhengjie.utils.SecurityContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.HashMap;
import java.util.Map;
import java.util.*;
/**
* @author jie
......@@ -44,14 +41,13 @@ public class UserController {
private UserQueryService userQueryService;
@Autowired
private JwtTokenUtil jwtTokenUtil;
private PictureService pictureService;
@Autowired
@Qualifier("jwtUserDetailsService")
private UserDetailsService userDetailsService;
private DataScope dataScope;
@Autowired
private PictureService pictureService;
private DeptService deptService;
@Autowired
private VerificationCodeService verificationCodeService;
......@@ -63,7 +59,34 @@ public class UserController {
@GetMapping(value = "/users")
@PreAuthorize("hasAnyRole('ADMIN','USER_ALL','USER_SELECT')")
public ResponseEntity getUsers(UserDTO userDTO, Pageable pageable){
return new ResponseEntity(userQueryService.queryAll(userDTO,pageable),HttpStatus.OK);
Set<Long> deptSet = new HashSet<>();
Set<Long> result = new HashSet<>();
if (!ObjectUtils.isEmpty(userDTO.getDeptId())) {
deptSet.add(userDTO.getDeptId());
deptSet.addAll(dataScope.getDeptChildren(deptService.findByPid(userDTO.getDeptId())));
}
// 数据权限
Set<Long> deptIds = dataScope.getDeptIds();
// 查询条件不为空并且数据权限不为空则取交集
if (!CollectionUtils.isEmpty(deptIds) && !CollectionUtils.isEmpty(deptSet)){
// 取交集
result.addAll(deptSet);
result.retainAll(deptIds);
// 若无交集,则代表无数据权限
if(result.size() == 0){
return new ResponseEntity(PageUtil.toPage(null,0),HttpStatus.OK);
} else return new ResponseEntity(userQueryService.queryAll(userDTO,result,pageable),HttpStatus.OK);
// 否则取并集
} else {
result.addAll(deptSet);
result.addAll(deptIds);
return new ResponseEntity(userQueryService.queryAll(userDTO,result,pageable),HttpStatus.OK);
}
}
@Log("新增用户")
......@@ -100,10 +123,9 @@ public class UserController {
@GetMapping(value = "/users/validPass/{pass}")
public ResponseEntity validPass(@PathVariable String pass){
UserDetails userDetails = SecurityContextHolder.getUserDetails();
JwtUser jwtUser = (JwtUser)userDetailsService.loadUserByUsername(userDetails.getUsername());
Map map = new HashMap();
map.put("status",200);
if(!jwtUser.getPassword().equals(EncryptUtils.encryptPassword(pass))){
if(!userDetails.getPassword().equals(EncryptUtils.encryptPassword(pass))){
map.put("status",400);
}
return new ResponseEntity(map,HttpStatus.OK);
......@@ -117,11 +139,10 @@ public class UserController {
@GetMapping(value = "/users/updatePass/{pass}")
public ResponseEntity updatePass(@PathVariable String pass){
UserDetails userDetails = SecurityContextHolder.getUserDetails();
JwtUser jwtUser = (JwtUser)userDetailsService.loadUserByUsername(userDetails.getUsername());
if(jwtUser.getPassword().equals(EncryptUtils.encryptPassword(pass))){
if(userDetails.getPassword().equals(EncryptUtils.encryptPassword(pass))){
throw new BadRequestException("新密码不能与旧密码相同");
}
userService.updatePass(jwtUser,EncryptUtils.encryptPassword(pass));
userService.updatePass(userDetails.getUsername(),EncryptUtils.encryptPassword(pass));
return new ResponseEntity(HttpStatus.OK);
}
......@@ -133,9 +154,8 @@ public class UserController {
@PostMapping(value = "/users/updateAvatar")
public ResponseEntity updateAvatar(@RequestParam MultipartFile file){
UserDetails userDetails = SecurityContextHolder.getUserDetails();
JwtUser jwtUser = (JwtUser)userDetailsService.loadUserByUsername(userDetails.getUsername());
Picture picture = pictureService.upload(file,jwtUser.getUsername());
userService.updateAvatar(jwtUser,picture.getUrl());
Picture picture = pictureService.upload(file,userDetails.getUsername());
userService.updateAvatar(userDetails.getUsername(),picture.getUrl());
return new ResponseEntity(HttpStatus.OK);
}
......@@ -145,16 +165,16 @@ public class UserController {
* @param user
* @return
*/
@Log("修改邮箱")
@PostMapping(value = "/users/updateEmail/{code}")
public ResponseEntity updateEmail(@PathVariable String code,@RequestBody User user){
UserDetails userDetails = SecurityContextHolder.getUserDetails();
JwtUser jwtUser = (JwtUser)userDetailsService.loadUserByUsername(userDetails.getUsername());
if(!jwtUser.getPassword().equals(EncryptUtils.encryptPassword(user.getPassword()))){
if(!userDetails.getPassword().equals(EncryptUtils.encryptPassword(user.getPassword()))){
throw new BadRequestException("密码错误");
}
VerificationCode verificationCode = new VerificationCode(code, ElAdminConstant.RESET_MAIL,"email",user.getEmail());
verificationCodeService.validated(verificationCode);
userService.updateEmail(jwtUser,user.getEmail());
userService.updateEmail(userDetails.getUsername(),user.getEmail());
return new ResponseEntity(HttpStatus.OK);
}
}
package me.zhengjie.modules.system.service;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.service.dto.DeptDTO;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import java.util.List;
/**
* @author jie
* @date 2019-03-25
*/
@CacheConfig(cacheNames = "dept")
public interface DeptService {
/**
* findById
* @param id
* @return
*/
@Cacheable(key = "#p0")
DeptDTO findById(Long id);
/**
* create
* @param resources
* @return
*/
@CacheEvict(allEntries = true)
DeptDTO create(Dept resources);
/**
* update
* @param resources
*/
@CacheEvict(allEntries = true)
void update(Dept resources);
/**
* delete
* @param id
*/
@CacheEvict(allEntries = true)
void delete(Long id);
/**
* buildTree
* @param deptDTOS
* @return
*/
@Cacheable(keyGenerator = "keyGenerator")
Object buildTree(List<DeptDTO> deptDTOS);
/**
* findByPid
* @param pid
* @return
*/
@Cacheable(keyGenerator = "keyGenerator")
List<Dept> findByPid(long pid);
}
\ No newline at end of file
package me.zhengjie.modules.system.service;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.service.dto.DictDetailDTO;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
/**
* @author jie
* @date 2019-04-10
*/
@CacheConfig(cacheNames = "dictDetail")
public interface DictDetailService {
/**
* findById
* @param id
* @return
*/
@Cacheable(key = "#p0")
DictDetailDTO findById(Long id);
/**
* create
* @param resources
* @return
*/
@CacheEvict(allEntries = true)
DictDetailDTO create(DictDetail resources);
/**
* update
* @param resources
*/
@CacheEvict(allEntries = true)
void update(DictDetail resources);
/**
* delete
* @param id
*/
@CacheEvict(allEntries = true)
void delete(Long id);
}
\ No newline at end of file
package me.zhengjie.modules.system.service;
import me.zhengjie.modules.system.domain.Dict;
import me.zhengjie.modules.system.service.dto.DictDTO;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
/**
* @author jie
* @date 2019-04-10
*/
@CacheConfig(cacheNames = "dict")
public interface DictService {
/**
* findById
* @param id
* @return
*/
@Cacheable(key = "#p0")
DictDTO findById(Long id);
/**
* create
* @param resources
* @return
*/
@CacheEvict(allEntries = true)
DictDTO create(Dict resources);
/**
* update
* @param resources
*/
@CacheEvict(allEntries = true)
void update(Dict resources);
/**
* delete
* @param id
*/
@CacheEvict(allEntries = true)
void delete(Long id);
}
\ No newline at end of file
package me.zhengjie.modules.system.service;
import me.zhengjie.modules.system.domain.Job;
import me.zhengjie.modules.system.service.dto.JobDTO;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
/**
* @author jie
* @date 2019-03-29
*/
@CacheConfig(cacheNames = "job")
public interface JobService {
/**
* findById
* @param id
* @return
*/
@Cacheable(key = "#p0")
JobDTO findById(Long id);
/**
* create
* @param resources
* @return
*/
@CacheEvict(allEntries = true)
JobDTO create(Job resources);
/**
* update
* @param resources
*/
@CacheEvict(allEntries = true)
void update(Job resources);
/**
* delete
* @param id
*/
@CacheEvict(allEntries = true)
void delete(Long id);
}
\ No newline at end of file
......@@ -74,7 +74,7 @@ public interface MenuService {
* @param roles
* @return
*/
List<MenuDTO> findByRoles(Set<Role> roles);
List<MenuDTO> findByRoles(List<Role> roles);
/**
* buildMenus
......@@ -82,4 +82,6 @@ public interface MenuService {
* @return
*/
Object buildMenus(List<MenuDTO> byRoles);
Menu findOne(Long id);
}
......@@ -5,6 +5,8 @@ import me.zhengjie.modules.system.service.dto.PermissionDTO;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import java.util.Collection;
import java.util.List;
/**
......
package me.zhengjie.modules.system.service;
import me.zhengjie.modules.system.domain.Menu;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.service.dto.RoleDTO;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import java.util.List;
import java.util.Set;
/**
......@@ -45,19 +47,13 @@ public interface RoleService {
@CacheEvict(allEntries = true)
void delete(Long id);
/**
* role tree
* @return
*/
@Cacheable(key = "'tree'")
Object getRoleTree();
/**
* findByUsers_Id
* @param id
* @return
*/
Set<Role> findByUsers_Id(Long id);
@Cacheable(keyGenerator = "keyGenerator")
List<Role> findByUsers_Id(Long id);
/**
* updatePermission
......@@ -74,4 +70,7 @@ public interface RoleService {
*/
@CacheEvict(allEntries = true)
void updateMenu(Role resources, RoleDTO roleDTO);
@CacheEvict(allEntries = true)
void untiedMenu(Menu menu);
}
......@@ -49,30 +49,30 @@ public interface UserService {
* @param userName
* @return
*/
@Cacheable(keyGenerator = "keyGenerator")
@Cacheable(key = "'loadUserByUsername:'+#p0")
User findByName(String userName);
/**
* 修改密码
* @param jwtUser
* @param username
* @param encryptPassword
*/
@CacheEvict(allEntries = true)
void updatePass(JwtUser jwtUser, String encryptPassword);
void updatePass(String username, String encryptPassword);
/**
* 修改头像
* @param jwtUser
* @param username
* @param url
*/
@CacheEvict(allEntries = true)
void updateAvatar(JwtUser jwtUser, String url);
void updateAvatar(String username, String url);
/**
* 修改邮箱
* @param jwtUser
* @param username
* @param email
*/
@CacheEvict(allEntries = true)
void updateEmail(JwtUser jwtUser, String email);
void updateEmail(String username, String email);
}
package me.zhengjie.modules.system.service.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import javax.validation.constraints.NotNull;
import java.sql.Timestamp;
import java.io.Serializable;
import java.util.List;
/**
* @author jie
* @date 2019-03-25
*/
@Data
public class DeptDTO implements Serializable {
/**
* ID
*/
private Long id;
/**
* 名称
*/
private String name;
@NotNull
private Boolean enabled;
/**
* 上级部门
*/
private Long pid;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private List<DeptDTO> children;
private Timestamp createTime;
public String getLabel() {
return name;
}
}
\ No newline at end of file
package me.zhengjie.modules.system.service.dto;
import lombok.Data;
import java.sql.Timestamp;
import java.io.Serializable;
/**
* @author jie
* @date 2019-04-10
*/
@Data
public class DictDTO implements Serializable {
private Long id;
/**
* 字典名称
*/
private String name;
/**
* 描述
*/
private String remark;
}
\ No newline at end of file
package me.zhengjie.modules.system.service.dto;
import lombok.Data;
import java.io.Serializable;
/**
* @author jie
* @date 2019-04-10
*/
@Data
public class DictDetailDTO implements Serializable {
private Long id;
/**
* 字典标签
*/
private String label;
/**
* 字典值
*/
private String value;
/**
* 排序
*/
private String sort;
/**
* 字典id
*/
private String dictName;
}
\ No newline at end of file
package me.zhengjie.modules.system.service.dto;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.sql.Timestamp;
import java.io.Serializable;
/**
* @author jie
* @date 2019-03-29
*/
@Data
@NoArgsConstructor
public class JobDTO implements Serializable {
/**
* ID
*/
private Long id;
private Long sort;
/**
* 名称
*/
private String name;
/**
* 状态
*/
private Boolean enabled;
private DeptDTO dept;
/**
* 创建日期
*/
private Timestamp createTime;
public JobDTO(String name, Boolean enabled) {
this.name = name;
this.enabled = enabled;
}
}
\ No newline at end of file
......@@ -16,11 +16,15 @@ public class RoleDTO implements Serializable {
private String name;
private String dataScope;
private String remark;
private Set<PermissionDTO> permissions;
private Set<MenuDTO> menus;
private Set<DeptDTO> depts;
private Timestamp createTime;
}
......@@ -24,6 +24,8 @@ public class UserDTO implements Serializable {
private String email;
private String phone;
private Boolean enabled;
@JsonIgnore
......@@ -35,4 +37,11 @@ public class UserDTO implements Serializable {
@ApiModelProperty(hidden = true)
private Set<RoleDTO> roles;
@ApiModelProperty(hidden = true)
private JobDTO job;
private DeptDTO dept;
private Long deptId;
}
package me.zhengjie.modules.system.service.impl;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.system.repository.DeptRepository;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.dto.DeptDTO;
import me.zhengjie.modules.system.service.mapper.DeptMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author jie
* @date 2019-03-25
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DeptServiceImpl implements DeptService {
@Autowired
private DeptRepository deptRepository;
@Autowired
private DeptMapper deptMapper;
@Override
public DeptDTO findById(Long id) {
Optional<Dept> dept = deptRepository.findById(id);
ValidationUtil.isNull(dept,"Dept","id",id);
return deptMapper.toDto(dept.get());
}
@Override
public List<Dept> findByPid(long pid) {
return deptRepository.findByPid(pid);
}
@Override
public Object buildTree(List<DeptDTO> deptDTOS) {
Set<DeptDTO> trees = new LinkedHashSet<>();
Set<DeptDTO> depts= new LinkedHashSet<>();
Boolean isChild;
for (DeptDTO deptDTO : deptDTOS) {
isChild = false;
if ("0".equals(deptDTO.getPid().toString())) {
trees.add(deptDTO);
}
for (DeptDTO it : deptDTOS) {
if (it.getPid().equals(deptDTO.getId())) {
isChild = true;
if (deptDTO.getChildren() == null) {
deptDTO.setChildren(new ArrayList<DeptDTO>());
}
deptDTO.getChildren().add(it);
}
}
if(isChild) {
depts.add(deptDTO);
}
}
if (CollectionUtils.isEmpty(trees)) {
trees = depts;
}
Integer totalElements = deptDTOS!=null?deptDTOS.size():0;
Map map = new HashMap();
map.put("totalElements",totalElements);
map.put("content",CollectionUtils.isEmpty(trees)?deptDTOS:trees);
return map;
}
@Override
@Transactional(rollbackFor = Exception.class)
public DeptDTO create(Dept resources) {
return deptMapper.toDto(deptRepository.save(resources));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(Dept resources) {
if(resources.getId().equals(resources.getPid())) {
throw new BadRequestException("上级不能为自己");
}
Optional<Dept> optionalDept = deptRepository.findById(resources.getId());
ValidationUtil.isNull( optionalDept,"Dept","id",resources.getId());
Dept dept = optionalDept.get();
// 此处需自己修改
resources.setId(dept.getId());
deptRepository.save(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Long id) {
deptRepository.deleteById(id);
}
}
\ No newline at end of file
package me.zhengjie.modules.system.service.impl;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.system.repository.DictDetailRepository;
import me.zhengjie.modules.system.service.DictDetailService;
import me.zhengjie.modules.system.service.dto.DictDetailDTO;
import me.zhengjie.modules.system.service.mapper.DictDetailMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
/**
* @author jie
* @date 2019-04-10
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DictDetailServiceImpl implements DictDetailService {
@Autowired
private DictDetailRepository dictDetailRepository;
@Autowired
private DictDetailMapper dictDetailMapper;
@Override
public DictDetailDTO findById(Long id) {
Optional<DictDetail> dictDetail = dictDetailRepository.findById(id);
ValidationUtil.isNull(dictDetail,"DictDetail","id",id);
return dictDetailMapper.toDto(dictDetail.get());
}
@Override
@Transactional(rollbackFor = Exception.class)
public DictDetailDTO create(DictDetail resources) {
return dictDetailMapper.toDto(dictDetailRepository.save(resources));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(DictDetail resources) {
Optional<DictDetail> optionalDictDetail = dictDetailRepository.findById(resources.getId());
ValidationUtil.isNull( optionalDictDetail,"DictDetail","id",resources.getId());
DictDetail dictDetail = optionalDictDetail.get();
// 此处需自己修改
resources.setId(dictDetail.getId());
dictDetailRepository.save(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Long id) {
dictDetailRepository.deleteById(id);
}
}
\ No newline at end of file
package me.zhengjie.modules.system.service.impl;
import me.zhengjie.modules.system.domain.Dict;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.system.repository.DictRepository;
import me.zhengjie.modules.system.service.DictService;
import me.zhengjie.modules.system.service.dto.DictDTO;
import me.zhengjie.modules.system.service.mapper.DictMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
/**
* @author jie
* @date 2019-04-10
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DictServiceImpl implements DictService {
@Autowired
private DictRepository dictRepository;
@Autowired
private DictMapper dictMapper;
@Override
public DictDTO findById(Long id) {
Optional<Dict> dict = dictRepository.findById(id);
ValidationUtil.isNull(dict,"Dict","id",id);
return dictMapper.toDto(dict.get());
}
@Override
@Transactional(rollbackFor = Exception.class)
public DictDTO create(Dict resources) {
return dictMapper.toDto(dictRepository.save(resources));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(Dict resources) {
Optional<Dict> optionalDict = dictRepository.findById(resources.getId());
ValidationUtil.isNull( optionalDict,"Dict","id",resources.getId());
Dict dict = optionalDict.get();
// 此处需自己修改
resources.setId(dict.getId());
dictRepository.save(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Long id) {
dictRepository.deleteById(id);
}
}
\ No newline at end of file
package me.zhengjie.modules.system.service.impl;
import me.zhengjie.modules.system.domain.Job;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.system.repository.JobRepository;
import me.zhengjie.modules.system.service.JobService;
import me.zhengjie.modules.system.service.dto.JobDTO;
import me.zhengjie.modules.system.service.mapper.JobMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
/**
* @author jie
* @date 2019-03-29
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class JobServiceImpl implements JobService {
@Autowired
private JobRepository jobRepository;
@Autowired
private JobMapper jobMapper;
@Override
public JobDTO findById(Long id) {
Optional<Job> job = jobRepository.findById(id);
ValidationUtil.isNull(job,"Job","id",id);
return jobMapper.toDto(job.get());
}
@Override
@Transactional(rollbackFor = Exception.class)
public JobDTO create(Job resources) {
return jobMapper.toDto(jobRepository.save(resources));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(Job resources) {
Optional<Job> optionalJob = jobRepository.findById(resources.getId());
ValidationUtil.isNull( optionalJob,"Job","id",resources.getId());
Job job = optionalJob.get();
// 此处需自己修改
resources.setId(job.getId());
jobRepository.save(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Long id) {
jobRepository.deleteById(id);
}
}
\ No newline at end of file
......@@ -37,7 +37,7 @@ public class MenuServiceImpl implements MenuService {
}
@Override
public List<MenuDTO> findByRoles(Set<Role> roles) {
public List<MenuDTO> findByRoles(List<Role> roles) {
Set<Menu> menus = new LinkedHashSet<>();
for (Role role : roles) {
List<Menu> menus1 = menuRepository.findByRoles_IdOrderBySortAsc(role.getId()).stream().collect(Collectors.toList());
......@@ -61,6 +61,9 @@ public class MenuServiceImpl implements MenuService {
@Override
public void update(Menu resources) {
if(resources.getId().equals(resources.getPid())) {
throw new BadRequestException("上级不能为自己");
}
Optional<Menu> optionalPermission = menuRepository.findById(resources.getId());
ValidationUtil.isNull(optionalPermission,"Permission","id",resources.getId());
......@@ -87,10 +90,6 @@ public class MenuServiceImpl implements MenuService {
@Override
public void delete(Long id) {
List<Menu> menuList = menuRepository.findByPid(id);
for (Menu menu : menuList) {
menuRepository.delete(menu);
}
menuRepository.deleteById(id);
}
......@@ -193,4 +192,11 @@ public class MenuServiceImpl implements MenuService {
);
return list;
}
@Override
public Menu findOne(Long id) {
Optional<Menu> menu = menuRepository.findById(id);
ValidationUtil.isNull(menu,"Menu","id",id);
return menu.get();
}
}
......@@ -47,8 +47,10 @@ public class PermissionServiceImpl implements PermissionService {
@Override
@Transactional(rollbackFor = Exception.class)
public void update(Permission resources) {
Optional<Permission> optionalPermission = permissionRepository.findById(resources.getId());
if(resources.getId().equals(resources.getPid())) {
throw new BadRequestException("上级不能为自己");
}
ValidationUtil.isNull(optionalPermission,"Permission","id",resources.getId());
Permission permission = optionalPermission.get();
......
package me.zhengjie.modules.system.service.impl;
import me.zhengjie.modules.system.domain.Menu;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.exception.EntityExistException;
......@@ -13,6 +14,7 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author jie
......@@ -61,6 +63,8 @@ public class RoleServiceImpl implements RoleService {
role.setName(resources.getName());
role.setRemark(resources.getRemark());
role.setDataScope(resources.getDataScope());
role.setDepts(resources.getDepts());
roleRepository.save(role);
}
......@@ -79,28 +83,23 @@ public class RoleServiceImpl implements RoleService {
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Long id) {
roleRepository.deleteById(id);
public void untiedMenu(Menu menu) {
Set<Role> roles = roleRepository.findByMenus_Id(menu.getId());
for (Role role : roles) {
menu.getRoles().remove(role);
role.getMenus().remove(menu);
roleRepository.save(role);
}
}
@Override
public Object getRoleTree() {
List<Role> roleList = roleRepository.findAll();
List<Map<String, Object>> list = new ArrayList<>();
for (Role role : roleList) {
Map<String, Object> map = new HashMap<>();
map.put("id",role.getId());
map.put("label",role.getName());
list.add(map);
}
return list;
@Transactional(rollbackFor = Exception.class)
public void delete(Long id) {
roleRepository.deleteById(id);
}
@Override
public Set<Role> findByUsers_Id(Long id) {
return roleRepository.findByUsers_Id(id);
public List<Role> findByUsers_Id(Long id) {
return roleRepository.findByUsers_Id(id).stream().collect(Collectors.toList());
}
}
package me.zhengjie.modules.system.service.impl;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.exception.EntityNotFoundException;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.security.security.JwtUser;
import me.zhengjie.modules.security.utils.JwtTokenUtil;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.UserDTO;
import me.zhengjie.modules.system.service.mapper.UserMapper;
......@@ -32,9 +29,6 @@ public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Override
public UserDTO findById(long id) {
Optional<User> user = userRepository.findById(id);
......@@ -54,20 +48,15 @@ public class UserServiceImpl implements UserService {
throw new EntityExistException(User.class,"email",resources.getEmail());
}
if(resources.getRoles() == null || resources.getRoles().size() == 0){
throw new BadRequestException("角色不能为空");
}
// 默认密码 123456,此密码是 MD5加密后的字符
resources.setPassword("14e1b600b1fd579f47433b88e8d85291");
resources.setAvatar("https://i.loli.net/2018/12/06/5c08894d8de21.jpg");
// 默认密码 123456,此密码是加密后的字符
resources.setPassword("e10adc3949ba59abbe56e057f20f883e");
resources.setAvatar("https://aurora-1255840532.cos.ap-chengdu.myqcloud.com/8918a306ea314404835a9196585c4b75.jpeg");
return userMapper.toDto(userRepository.save(resources));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(User resources) {
Optional<User> userOptional = userRepository.findById(resources.getId());
ValidationUtil.isNull(userOptional,"User","id",resources.getId());
......@@ -76,10 +65,6 @@ public class UserServiceImpl implements UserService {
User user1 = userRepository.findByUsername(user.getUsername());
User user2 = userRepository.findByEmail(user.getEmail());
if(resources.getRoles() == null || resources.getRoles().size() == 0){
throw new BadRequestException("角色不能为空");
}
if(user1 !=null&&!user.getId().equals(user1.getId())){
throw new EntityExistException(User.class,"username",resources.getUsername());
}
......@@ -92,7 +77,9 @@ public class UserServiceImpl implements UserService {
user.setEmail(resources.getEmail());
user.setEnabled(resources.getEnabled());
user.setRoles(resources.getRoles());
user.setDept(resources.getDept());
user.setJob(resources.getJob());
user.setPhone(resources.getPhone());
userRepository.save(user);
}
......@@ -120,19 +107,19 @@ public class UserServiceImpl implements UserService {
@Override
@Transactional(rollbackFor = Exception.class)
public void updatePass(JwtUser jwtUser, String pass) {
userRepository.updatePass(jwtUser.getId(),pass,new Date());
public void updatePass(String username, String pass) {
userRepository.updatePass(username,pass,new Date());
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateAvatar(JwtUser jwtUser, String url) {
userRepository.updateAvatar(jwtUser.getId(),url);
public void updateAvatar(String username, String url) {
userRepository.updateAvatar(username,url);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateEmail(JwtUser jwtUser, String email) {
userRepository.updateEmail(jwtUser.getId(),email);
public void updateEmail(String username, String email) {
userRepository.updateEmail(username,email);
}
}
package me.zhengjie.modules.system.service.mapper;
import me.zhengjie.mapper.EntityMapper;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.service.dto.DeptDTO;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author jie
* @date 2019-03-25
*/
@Mapper(componentModel = "spring",uses = {},unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface DeptMapper extends EntityMapper<DeptDTO, Dept> {
}
\ No newline at end of file
package me.zhengjie.modules.system.service.mapper;
import me.zhengjie.mapper.EntityMapper;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.service.dto.DictDetailDTO;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author jie
* @date 2019-04-10
*/
@Mapper(componentModel = "spring",uses = {},unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface DictDetailMapper extends EntityMapper<DictDetailDTO, DictDetail> {
}
\ No newline at end of file
package me.zhengjie.modules.system.service.mapper;
import me.zhengjie.mapper.EntityMapper;
import me.zhengjie.modules.system.domain.Dict;
import me.zhengjie.modules.system.service.dto.DictDTO;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author jie
* @date 2019-04-10
*/
@Mapper(componentModel = "spring",uses = {},unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface DictMapper extends EntityMapper<DictDTO, Dict> {
}
\ No newline at end of file
package me.zhengjie.modules.system.service.mapper;
import me.zhengjie.mapper.EntityMapper;
import me.zhengjie.modules.system.domain.Job;
import me.zhengjie.modules.system.service.dto.JobDTO;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author jie
* @date 2019-03-29
*/
@Mapper(componentModel = "spring",uses = {DeptMapper.class},unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface JobMapper extends EntityMapper<JobDTO, Job> {
}
\ No newline at end of file
......@@ -10,7 +10,7 @@ import org.mapstruct.ReportingPolicy;
* @author jie
* @date 2018-11-23
*/
@Mapper(componentModel = "spring", uses = {PermissionMapper.class, MenuMapper.class}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
@Mapper(componentModel = "spring", uses = {PermissionMapper.class, MenuMapper.class, DeptMapper.class}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface RoleMapper extends EntityMapper<RoleDTO, Role> {
}
......@@ -10,7 +10,7 @@ import org.mapstruct.ReportingPolicy;
* @author jie
* @date 2018-11-23
*/
@Mapper(componentModel = "spring",uses = {RoleMapper.class},unmappedTargetPolicy = ReportingPolicy.IGNORE)
@Mapper(componentModel = "spring",uses = {RoleMapper.class, DeptMapper.class, JobMapper.class},unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface UserMapper extends EntityMapper<UserDTO, User> {
}
package me.zhengjie.modules.system.service.query;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.service.dto.DeptDTO;
import me.zhengjie.modules.system.repository.DeptRepository;
import me.zhengjie.modules.system.service.mapper.DeptMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* @author jie
* @date 2018-12-03
*/
@Service
@CacheConfig(cacheNames = "dept")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DeptQueryService {
@Autowired
private DeptRepository deptRepository;
@Autowired
private DeptMapper deptMapper;
/**
* 不分页
*/
@Cacheable(keyGenerator = "keyGenerator")
public List queryAll(DeptDTO dept, Set<Long> deptIds){
return deptMapper.toDto(deptRepository.findAll(new Spec(dept, deptIds)));
}
class Spec implements Specification<Dept> {
private DeptDTO dept;
private Set<Long> deptIds;
public Spec(DeptDTO dept, Set<Long> deptIds){
this.dept = dept;
this.deptIds = deptIds;
}
@Override
public Predicate toPredicate(Root<Dept> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
List<Predicate> list = new ArrayList<Predicate>();
if(!ObjectUtils.isEmpty(dept.getName())){
/**
* 模糊
*/
list.add(cb.like(root.get("name").as(String.class),"%"+dept.getName()+"%"));
}
if(!ObjectUtils.isEmpty(dept.getEnabled())){
/**
* 相等
*/
list.add(cb.equal(root.get("enabled").as(Boolean.class),dept.getEnabled()));
}
if(!ObjectUtils.isEmpty(dept.getPid())){
/**
* 相等
*/
list.add(cb.equal(root.get("pid").as(Boolean.class),dept.getPid()));
}
if (!CollectionUtils.isEmpty(deptIds)) {
list.add(root.get("id").in(deptIds));
}
Predicate[] p = new Predicate[list.size()];
return cb.and(list.toArray(p));
}
}
}
\ No newline at end of file
package me.zhengjie.modules.system.service.query;
import me.zhengjie.modules.system.domain.Dict;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.service.dto.DictDetailDTO;
import me.zhengjie.modules.system.repository.DictDetailRepository;
import me.zhengjie.modules.system.service.mapper.DictDetailMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author jie
* @date 2018-12-03
*/
@Service
@CacheConfig(cacheNames = "dictDetail")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DictDetailQueryService {
@Autowired
private DictDetailRepository dictDetailRepository;
@Autowired
private DictDetailMapper dictDetailMapper;
/**
* 分页
*/
@Cacheable(keyGenerator = "keyGenerator")
public Object queryAll(DictDetailDTO dictDetail, Pageable pageable){
Page<DictDetail> page = dictDetailRepository.findAll(new Spec(dictDetail),pageable);
return PageUtil.toPage(page.map(dictDetailMapper::toDto));
}
class Spec implements Specification<DictDetail> {
private DictDetailDTO dictDetail;
public Spec(DictDetailDTO dictDetail){
this.dictDetail = dictDetail;
}
@Override
public Predicate toPredicate(Root<DictDetail> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
List<Predicate> list = new ArrayList<Predicate>();
Join<Dict,DictDetail> join = root.join("dict",JoinType.LEFT);
if(!ObjectUtils.isEmpty(dictDetail.getLabel())){
/**
* 模糊
*/
list.add(cb.like(root.get("label").as(String.class),"%"+dictDetail.getLabel()+"%"));
}
if(!ObjectUtils.isEmpty(dictDetail.getDictName())){
list.add(cb.equal(join.get("name").as(String.class),dictDetail.getDictName()));
}
Predicate[] p = new Predicate[list.size()];
return cb.and(list.toArray(p));
}
}
}
\ No newline at end of file
package me.zhengjie.modules.system.service.query;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.modules.system.domain.Dict;
import me.zhengjie.modules.system.service.dto.DictDTO;
import me.zhengjie.modules.system.repository.DictRepository;
import me.zhengjie.modules.system.service.mapper.DictMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
/**
* @author jie
* @date 2018-12-03
*/
@Service
@CacheConfig(cacheNames = "dict")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DictQueryService {
@Autowired
private DictRepository dictRepository;
@Autowired
private DictMapper dictMapper;
/**
* 分页
*/
@Cacheable(keyGenerator = "keyGenerator")
public Object queryAll(DictDTO dict, Pageable pageable){
Page<Dict> page = dictRepository.findAll(new Spec(dict),pageable);
return PageUtil.toPage(page.map(dictMapper::toDto));
}
/**
* 不分页
*/
@Cacheable(keyGenerator = "keyGenerator")
public Object queryAll(DictDTO dict){
return dictMapper.toDto(dictRepository.findAll(new Spec(dict)));
}
class Spec implements Specification<Dict> {
private DictDTO dict;
public Spec(DictDTO dict){
this.dict = dict;
}
@Override
public Predicate toPredicate(Root<Dict> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
List<Predicate> list = new ArrayList<Predicate>();
if(!ObjectUtils.isEmpty(dict.getName())){
/**
* 模糊
*/
list.add(cb.like(root.get("name").as(String.class),"%"+dict.getName()+"%"));
}
if(!ObjectUtils.isEmpty(dict.getRemark())){
/**
* 模糊
*/
list.add(cb.like(root.get("remark").as(String.class),"%"+dict.getRemark()+"%"));
}
Predicate[] p = new Predicate[list.size()];
return cb.and(list.toArray(p));
}
}
}
\ No newline at end of file
package me.zhengjie.modules.system.service.query;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.modules.system.domain.Job;
import me.zhengjie.modules.system.service.dto.JobDTO;
import me.zhengjie.modules.system.repository.JobRepository;
import me.zhengjie.modules.system.service.mapper.JobMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* @author jie
* @date 2018-12-03
*/
@Service
@CacheConfig(cacheNames = "job")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class JobQueryService {
@Autowired
private JobRepository jobRepository;
@Autowired
private JobMapper jobMapper;
@Cacheable(keyGenerator = "keyGenerator")
public Object queryAll(String name , Boolean enabled, Set<Long> deptIds, Long deptId, Pageable pageable){
Page<Job> page = jobRepository.findAll(new Spec(new JobDTO(name,enabled), deptIds, deptId),pageable);
return PageUtil.toPage(page.map(jobMapper::toDto));
}
class Spec implements Specification<Job> {
private JobDTO job;
private Long deptId;
private Set<Long> deptIds;
public Spec(JobDTO job, Set<Long> deptIds, Long deptId){
this.job = job;
this.deptId = deptId;
this.deptIds = deptIds;
}
@Override
public Predicate toPredicate(Root<Job> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
List<Predicate> list = new ArrayList<Predicate>();
// 数据权限
Join<Dept, Job> join = root.join("dept",JoinType.LEFT);
if (!CollectionUtils.isEmpty(deptIds)) {
list.add(join.get("id").in(deptIds));
}
if(!ObjectUtils.isEmpty(job.getEnabled())){
/**
* 精确
*/
list.add(cb.equal(root.get("enabled").as(Boolean.class),job.getEnabled()));
}
if(!ObjectUtils.isEmpty(job.getName())){
/**
* 模糊
*/
list.add(cb.like(root.get("name").as(String.class),"%"+job.getName()+"%"));
}
if (deptId != null) {
/**
* 精确
*/
list.add(cb.equal(join.get("id").as(Long.class),deptId));
}
Predicate[] p = new Predicate[list.size()];
return cb.and(list.toArray(p));
}
}
}
\ No newline at end of file
......@@ -45,6 +45,15 @@ public class RoleQueryService {
return PageUtil.toPage(page.map(roleMapper::toDto));
}
/**
* 分页
*/
@Cacheable(keyGenerator = "keyGenerator")
public Object queryAll(){
List<Role> roles = roleRepository.findAll(new Spec(null));
return roleMapper.toDto(roles);
}
class Spec implements Specification<Role> {
private String name;
......
package me.zhengjie.modules.system.service.query;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.dto.UserDTO;
......@@ -14,13 +15,13 @@ import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* @author jie
......@@ -41,24 +42,20 @@ public class UserQueryService {
* 分页
*/
@Cacheable(keyGenerator = "keyGenerator")
public Object queryAll(UserDTO user, Pageable pageable){
Page<User> page = userRepo.findAll(new Spec(user),pageable);
public Object queryAll(UserDTO user, Set<Long> deptIds,Pageable pageable){
Page<User> page = userRepo.findAll(new Spec(user,deptIds),pageable);
return PageUtil.toPage(page.map(userMapper::toDto));
}
/**
* 不分页
*/
@Cacheable(keyGenerator = "keyGenerator")
public Object queryAll(UserDTO user){
return userMapper.toDto(userRepo.findAll(new Spec(user)));
}
class Spec implements Specification<User> {
private UserDTO user;
public Spec(UserDTO user){
private Set<Long> deptIds;
public Spec(UserDTO user, Set<Long> deptIds){
this.deptIds = deptIds;
this.user = user;
}
......@@ -67,6 +64,12 @@ public class UserQueryService {
List<Predicate> list = new ArrayList<Predicate>();
// 数据权限, 关联查询
Join<Dept,User> join = root.join("dept",JoinType.LEFT);
if (!CollectionUtils.isEmpty(deptIds)) {
list.add(join.get("id").in(deptIds));
}
if(!ObjectUtils.isEmpty(user.getId())){
/**
* 相等
......
......@@ -59,4 +59,11 @@ jwt:
#是否允许生成代码,生产环境设置为false
generator:
enabled: false
\ No newline at end of file
enabled: false
#如果生产环境要开启swagger,需要配置请求地址
#springfox:
# documentation:
# swagger:
# v2:
# host: # 接口域名或外网ip
\ No newline at end of file
......@@ -41,7 +41,7 @@ spring:
#七牛云
qiniu:
# 文件大小 /M
max-size: 5
max-size: 15
#验证码有效时间/分钟
code:
......
......@@ -67,24 +67,24 @@ public class ${className}QueryService {
List<Predicate> list = new ArrayList<Predicate>();
<#if queryColumns??>
<#list queryColumns as column>
if(!ObjectUtils.isEmpty(${changeClassName}.get${column.capitalColumnName}())){
<#if column.columnQuery = '1'>
/**
* 模糊
*/
list.add(cb.like(root.get("${column.columnName}").as(${column.columnType}.class),"%"+${changeClassName}.get${column.capitalColumnName}()+"%"));
</#if>
<#if column.columnQuery = '2'>
/**
* 精确
*/
list.add(cb.equal(root.get("${column.columnName}").as(${column.columnType}.class),${changeClassName}.get${column.capitalColumnName}()));
</#if>
}
</#list>
</#if>
<#if queryColumns??>
<#list queryColumns as column>
if(!ObjectUtils.isEmpty(${changeClassName}.get${column.capitalColumnName}())){
<#if column.columnQuery = '1'>
/**
* 模糊
*/
list.add(cb.like(root.get("${column.columnName}").as(${column.columnType}.class),"%"+${changeClassName}.get${column.capitalColumnName}()+"%"));
</#if>
<#if column.columnQuery = '2'>
/**
* 精确
*/
list.add(cb.equal(root.get("${column.columnName}").as(${column.columnType}.class),${changeClassName}.get${column.capitalColumnName}()));
</#if>
}
</#list>
</#if>
Predicate[] p = new Predicate[list.size()];
return cb.and(list.toArray(p));
}
......
......@@ -3,7 +3,7 @@
<div class="app-container">
<eHeader :query="query"/>
<!--表格渲染-->
<el-table v-loading="loading" :data="data" size="small" border style="width: 100%;">
<el-table v-loading="loading" :data="data" size="small" style="width: 100%;">
<#if columns??>
<#list columns as column>
<#if column.columnShow = 'true'>
......
......@@ -8,11 +8,15 @@ import me.zhengjie.service.QiNiuService;
import me.zhengjie.service.query.QiNiuQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
......@@ -87,7 +91,9 @@ public class QiniuController {
@Log("下载文件")
@GetMapping(value = "/qiNiuContent/download/{id}")
public ResponseEntity download(@PathVariable Long id){
return new ResponseEntity(qiNiuService.download(qiNiuService.findByContentId(id),qiNiuService.find()),HttpStatus.OK);
Map map = new HashMap();
map.put("url", qiNiuService.download(qiNiuService.findByContentId(id),qiNiuService.find()));
return new ResponseEntity(map,HttpStatus.OK);
}
/**
......
......@@ -39,9 +39,6 @@ public class AlipayServiceImpl implements AlipayService {
AlipayClient alipayClient = new DefaultAlipayClient(alipay.getGatewayUrl(), alipay.getAppID(), alipay.getPrivateKey(), alipay.getFormat(), alipay.getCharset(), alipay.getPublicKey(), alipay.getSignType());
double money = Double.parseDouble(trade.getTotalAmount());
if(money <= 0 || money>=5000){
throw new BadRequestException("测试金额过大");
}
/**
* 创建API对应的request(电脑网页版)
......
......@@ -58,7 +58,7 @@ public class PictureServiceImpl implements PictureService {
picture = JSON.parseObject(jsonObject.get("data").toString(), Picture.class);
picture.setSize(FileUtil.getSize(Integer.valueOf(picture.getSize())));
picture.setUsername(username);
picture.setFilename(FileUtil.getFileNameNoEx(multipartFile.getOriginalFilename())+FileUtil.getExtensionName(multipartFile.getOriginalFilename()));
picture.setFilename(FileUtil.getFileNameNoEx(multipartFile.getOriginalFilename())+"."+FileUtil.getExtensionName(multipartFile.getOriginalFilename()));
pictureRepository.save(picture);
//删除临时文件
FileUtil.deleteFile(file);
......
......@@ -24,6 +24,8 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDate;
import java.util.Optional;
/**
......@@ -84,7 +86,11 @@ public class QiNiuServiceImpl implements QiNiuService {
Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
String upToken = auth.uploadToken(qiniuConfig.getBucket());
try {
Response response = uploadManager.put(file.getBytes(), QiNiuUtil.getKey(file.getOriginalFilename()), upToken);
String key = file.getOriginalFilename();
if(qiniuContentRepository.findByKey(key) != null) {
key = QiNiuUtil.getKey(key);
}
Response response = uploadManager.put(file.getBytes(), key, upToken);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
//存入数据库
......@@ -134,8 +140,7 @@ public class QiNiuServiceImpl implements QiNiuService {
bucketManager.delete(content.getBucket(), content.getKey());
qiniuContentRepository.delete(content);
} catch (QiniuException ex) {
System.err.println(ex.code());
System.err.println(ex.response.toString());
qiniuContentRepository.delete(content);
}
}
......
......@@ -52,6 +52,7 @@ public class QiNiuUtil {
StringBuffer key = new StringBuffer(FileUtil.getFileNameNoEx(file));
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
key.append("-");
key.append(sdf.format(date));
key.append(".");
key.append(FileUtil.getExtensionName(file));
......
......@@ -48,6 +48,10 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
......@@ -97,6 +101,12 @@
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
<!--监控sql日志-->
<dependency>
<groupId>org.bgee.log4jdbc-log4j2</groupId>
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册