Merge branch 'dev' of https://gitee.com/log4j/pig into dev

This commit is contained in:
寻欢·李 2018-02-28 11:10:22 +08:00
commit 0cd66252cf
32 changed files with 343 additions and 120 deletions

View File

@ -15,7 +15,7 @@
1. [课程介绍项目介绍](http://p3blpcsde.bkt.clouddn.com/1.mp4) 1. [课程介绍项目介绍](http://p3blpcsde.bkt.clouddn.com/1.mp4)
2. [环境搭建运行展示](http://p3blpcsde.bkt.clouddn.com/2.mp4) 2. [环境搭建运行展示](http://p3blpcsde.bkt.clouddn.com/2.mp4)
3. Spring security oAuth2 源码详解 ...还在录 3. [oAuth2认证授权及其源码详解](http://p3blpcsde.bkt.clouddn.com/3.mp4)
### now ### now
@ -74,5 +74,6 @@ pig
![image](http://p0hpm86wj.bkt.clouddn.com/23.png) ![image](http://p0hpm86wj.bkt.clouddn.com/23.png)
![image](http://p0hpm86wj.bkt.clouddn.com/24.png) ![image](http://p0hpm86wj.bkt.clouddn.com/24.png)
![image](http://p0hpm86wj.bkt.clouddn.com/26.png) ![image](http://p0hpm86wj.bkt.clouddn.com/26.png)
![image](http://obq1lvsd9.bkt.clouddn.com/daemon.png)

View File

@ -1,5 +0,0 @@
FROM java:8-jre
MAINTAINER Pig lengleng <wangiegie@gmail.com>
ADD ./jar/pig-admin-service.jar /app/
CMD ["java", "-Xmx200m", "-jar", "/app/pig-admin-service.jar"]

View File

@ -1,5 +1,7 @@
FROM java:8-jre FROM java:8-jre
MAINTAINER Pig lengleng <wangiegie@gmail.com> MAINTAINER Pig lengleng <wangiegie@gmail.com>
ADD ./jar/pig-auth-service.jar /app/ ADD ./jar/pig-auth.jar /app/
CMD ["java", "-Xmx200m", "-jar", "/app/pig-auth-service.jar"] ADD ./jar/pinpoint-agent /app/pinpoint-agent
CMD ["java", "-Xmx200m", "-javaagent:/app/pinpoint-agent/pinpoint-bootstrap-1.5.0.jar", "-Dpinpoint.agentId=pig-auth", "-Dpinpoint.applicationName=AUTH", "-jar", "/app/pig-auth.jar"]

View File

@ -2,6 +2,8 @@ FROM java:8-jre
MAINTAINER Pig lengleng <wangiegie@gmail.com> MAINTAINER Pig lengleng <wangiegie@gmail.com>
ADD ./jar/pig-gateway.jar /app/ ADD ./jar/pig-gateway.jar /app/
CMD ["java", "-Xmx200m", "-jar", "/app/pig-gateway.jar"] ADD ./jar/pinpoint-agent /app/pinpoint-agent
CMD ["java", "-Xmx200m", "-javaagent:/app/pinpoint-agent/pinpoint-bootstrap-1.5.0.jar", "-Dpinpoint.agentId=pig-gateway", "-Dpinpoint.applicationName=GATEWAY", "-jar", "/app/pig-gateway.jar"]
EXPOSE 9999 EXPOSE 9999

View File

@ -0,0 +1,8 @@
FROM java:8-jre
MAINTAINER Pig lengleng <wangiegie@gmail.com>
ADD ./jar/pig-upms-service.jar /app/
ADD ./jar/pinpoint-agent /app/pinpoint-agent
CMD ["java", "-Xmx200m", "-javaagent:/app/pinpoint-agent/pinpoint-bootstrap-1.5.0.jar", "-Dpinpoint.agentId=pig-upms-service", "-Dpinpoint.applicationName=PIG-UPMS-SERVICE", "-jar", "/app/pig-upms-service.jar"]

View File

@ -7,20 +7,12 @@ services:
restart: always restart: always
ports: ports:
- 59025:1025 - 59025:1025
logging:
options:
max-size: "10m"
max-file: "10"
pig-config: pig-config:
build: build:
context: ./ context: ./
dockerfile: Dockerfile-config dockerfile: Dockerfile-config
restart: always restart: always
logging:
options:
max-size: "10m"
max-file: "10"
pig-gateway: pig-gateway:
build: build:
@ -29,27 +21,15 @@ services:
restart: always restart: always
ports: ports:
- 59999:9999 - 59999:9999
logging:
options:
max-size: "10m"
max-file: "10"
pig-auth-service: pig-auth:
build: build:
context: ./ context: ./
dockerfile: Dockerfile-auth dockerfile: Dockerfile-auth
restart: always restart: always
logging:
options:
max-size: "10m"
max-file: "10"
pig-admin-service: pig-upms-service:
build: build:
context: ./ context: ./
dockerfile: Dockerfile-admin dockerfile: Dockerfile-upms
restart: always restart: always
logging:
options:
max-size: "10m"
max-file: "10"

View File

@ -60,10 +60,21 @@
<groupId>mysql</groupId> <groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId> <artifactId>mysql-connector-java</artifactId>
</dependency> </dependency>
<!--spring data source-->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId> <artifactId>spring-boot-starter-jdbc</artifactId>
<exclusions>
<!--去掉默认的tomcat-jdbc的依赖-->
<exclusion>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--HikariCP连接池-->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency> </dependency>
</dependencies> </dependencies>

View File

@ -5,6 +5,7 @@ import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.common.exceptions.UnsupportedResponseTypeException;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator; import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -25,6 +26,8 @@ import org.springframework.stereotype.Component;
@Component @Component
public class PigWebResponseExceptionTranslator extends DefaultWebResponseExceptionTranslator { public class PigWebResponseExceptionTranslator extends DefaultWebResponseExceptionTranslator {
public static final String BAD_MSG = "坏的凭证";
/** /**
* @param e spring security内部异常 * @param e spring security内部异常
* @return 经过处理的异常信息 * @return 经过处理的异常信息
@ -33,12 +36,12 @@ public class PigWebResponseExceptionTranslator extends DefaultWebResponseExcepti
@Override @Override
public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception { public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
OAuth2Exception oAuth2Exception; OAuth2Exception oAuth2Exception;
if (e instanceof InvalidGrantException && StringUtils.equals("坏的凭证",e.getMessage())) { if (e instanceof InvalidGrantException && StringUtils.equals(BAD_MSG, e.getMessage())) {
oAuth2Exception = new InvalidGrantException("密码错误", e); oAuth2Exception = new InvalidGrantException("密码错误", e);
} else if (e instanceof InternalAuthenticationServiceException) { } else if (e instanceof InternalAuthenticationServiceException) {
oAuth2Exception = new InvalidGrantException("用户名不存在", e); oAuth2Exception = new InvalidGrantException("用户名不存在", e);
} else { } else {
oAuth2Exception = (OAuth2Exception) e; oAuth2Exception = new UnsupportedResponseTypeException("服务处理异常", e);
} }
return super.translate(oAuth2Exception); return super.translate(oAuth2Exception);
} }

View File

@ -4,14 +4,20 @@ import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo; import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact; import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
/** /**
* @author lengleng * @author lengleng
* @date 2017/12/28 * @date 2017/12/28
@ -24,12 +30,22 @@ public class SwaggerConfig {
@Bean @Bean
public Docket createRestApi() { public Docket createRestApi() {
ParameterBuilder tokenBuilder = new ParameterBuilder();
List<Parameter> parameterList = new ArrayList<Parameter>();
tokenBuilder.name("Authorization")
.defaultValue("去其他请求中获取heard中token参数")
.description("令牌")
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(true).build();
parameterList.add(tokenBuilder.build());
return new Docket(DocumentationType.SWAGGER_2) return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()) .apiInfo(apiInfo())
.select() .select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any()) .paths(PathSelectors.any())
.build(); .build()
.globalOperationParameters(parameterList);
} }
private ApiInfo apiInfo() { private ApiInfo apiInfo() {

View File

@ -2,15 +2,17 @@ package com.github.pig.common.bean.interceptor;
import lombok.Data; import lombok.Data;
import java.util.HashMap;
import java.util.List; import java.util.List;
/** /**
* @author lengleng * @author lengleng
* @date 2018/1/19 * @date 2018/1/19
* 数据权限参考guns实现 * 数据权限参考guns实现
* 2018年02月12日 增强查询参数
*/ */
@Data @Data
public class DataScope { public class DataScope extends HashMap {
/** /**
* 限制范围的字段名称 * 限制范围的字段名称
*/ */

View File

@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.plugins.SqlParserHandler;
import com.baomidou.mybatisplus.plugins.pagination.PageHelper; import com.baomidou.mybatisplus.plugins.pagination.PageHelper;
import com.baomidou.mybatisplus.toolkit.PluginUtils; import com.baomidou.mybatisplus.toolkit.PluginUtils;
import com.github.pig.common.util.UserUtils; import com.github.pig.common.util.UserUtils;
import com.github.pig.common.vo.UserVo;
import com.xiaoleilu.hutool.util.CollectionUtil; import com.xiaoleilu.hutool.util.CollectionUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.executor.statement.StatementHandler;
@ -14,6 +15,8 @@ import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject; import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import java.sql.Connection; import java.sql.Connection;
import java.util.ArrayList; import java.util.ArrayList;
@ -24,12 +27,11 @@ import java.util.Properties;
/** /**
* @author lengleng * @author lengleng
* @date 2018/1/19 * @date 2018/1/19
* 数据权限插件参考PaginationInterceptor * 数据权限插件guns
*/ */
@Slf4j @Slf4j
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})}) @Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class DataScopeInterceptor extends SqlParserHandler implements Interceptor { public class DataScopeInterceptor extends SqlParserHandler implements Interceptor {
private static final String DATA_SCOPE = "DataScope";
@Override @Override
public Object intercept(Invocation invocation) throws Throwable { public Object intercept(Invocation invocation) throws Throwable {
@ -42,37 +44,21 @@ public class DataScopeInterceptor extends SqlParserHandler implements Intercepto
return invocation.proceed(); return invocation.proceed();
} }
// 如果mapper方法是DataScope结尾则执行数据权限校验 BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
if (mappedStatement.getId().endsWith(DATA_SCOPE)) { String originalSql = boundSql.getSql();
BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql"); Object parameterObject = boundSql.getParameterObject();
String sql = boundSql.getSql();
//查找参数中包含DataScope类型的参数
Object parameterObject = boundSql.getParameterObject();
DataScope dataScope = findDataScopeObject(parameterObject);
List<Integer> deptIds; //查找参数中包含DataScope类型的参数
String scopeName = "dept_id"; DataScope dataScope = findDataScopeObject(parameterObject);
//如果入参没有数据权限参数则按照默认的本级和下级
if (dataScope == null) {
deptIds = CollectionUtil.newArrayList(1, 2, 3, 4);
} else {
scopeName = dataScope.getScopeName();
deptIds = dataScope.getDeptIds();
String username = UserUtils.getUser(); if (dataScope == null) {
//只查询本部门
if (dataScope.getIsOnly()) {
deptIds = CollectionUtil.newArrayList(1);
} else if (CollectionUtil.isEmpty(deptIds)) {
//deptIds为空是查询本级和下级
deptIds = CollectionUtil.newArrayList(1, 2, 3, 4);
}
}
String join = CollectionUtil.join(deptIds, ",");
sql = "select * from (" + sql + ") temp_data_scope where temp_data_scope." + scopeName + " in (" + join + ")";
metaObject.setValue("delegate.boundSql.sql", sql);
return invocation.proceed(); return invocation.proceed();
} else { } else {
String scopeName = dataScope.getScopeName();
List<Integer> deptIds = dataScope.getDeptIds();
String join = CollectionUtil.join(deptIds, ",");
originalSql = "select * from (" + originalSql + ") temp_data_scope where temp_data_scope." + scopeName + " in (" + join + ")";
metaObject.setValue("delegate.boundSql.sql", originalSql);
return invocation.proceed(); return invocation.proceed();
} }
} }

View File

@ -32,7 +32,7 @@
<dependency> <dependency>
<groupId>com.marcosbarbero.cloud</groupId> <groupId>com.marcosbarbero.cloud</groupId>
<artifactId>spring-cloud-zuul-ratelimit</artifactId> <artifactId>spring-cloud-zuul-ratelimit</artifactId>
<version>1.3.4.RELEASE</version> <version>1.5.0.RELEASE</version>
</dependency> </dependency>
<!--oauth2.0--> <!--oauth2.0-->
<dependency> <dependency>

View File

@ -20,9 +20,11 @@ import java.io.InputStream;
@Slf4j @Slf4j
@Component @Component
public class AuthFallbackProvider implements FallbackProvider { public class AuthFallbackProvider implements FallbackProvider {
private static final String AUTH_SERVICE_DISABLE = "授权模块不可用";
@Override @Override
public ClientHttpResponse fallbackResponse(Throwable cause) { public ClientHttpResponse fallbackResponse(Throwable cause) {
log.error("调用:{} 异常:{}", getRoute(), cause.getMessage());
return new ClientHttpResponse() { return new ClientHttpResponse() {
@Override @Override
public HttpStatus getStatusCode() { public HttpStatus getStatusCode() {
@ -46,9 +48,11 @@ public class AuthFallbackProvider implements FallbackProvider {
@Override @Override
public InputStream getBody() { public InputStream getBody() {
if (cause != null && cause.getMessage() != null) { if (cause != null && cause.getMessage() != null) {
log.error("调用:{} 异常:{}", getRoute(), cause.getMessage());
return new ByteArrayInputStream(cause.getMessage().getBytes()); return new ByteArrayInputStream(cause.getMessage().getBytes());
} else { } else {
return new ByteArrayInputStream("授权模块不可用".getBytes()); log.error("调用:{} 异常:{}", getRoute(), AUTH_SERVICE_DISABLE);
return new ByteArrayInputStream(AUTH_SERVICE_DISABLE.getBytes());
} }
} }

View File

@ -20,9 +20,11 @@ import java.io.InputStream;
@Slf4j @Slf4j
@Component @Component
public class UpmsFallbackProvider implements FallbackProvider { public class UpmsFallbackProvider implements FallbackProvider {
private static final String UPMS_SERVICE_DISABLE = "权限管理模块不可用";
@Override @Override
public ClientHttpResponse fallbackResponse(Throwable cause) { public ClientHttpResponse fallbackResponse(Throwable cause) {
log.error("调用:{} 异常:{}", getRoute(), cause.getMessage());
return new ClientHttpResponse() { return new ClientHttpResponse() {
@Override @Override
public HttpStatus getStatusCode() { public HttpStatus getStatusCode() {
@ -46,9 +48,11 @@ public class UpmsFallbackProvider implements FallbackProvider {
@Override @Override
public InputStream getBody() { public InputStream getBody() {
if (cause != null && cause.getMessage() != null) { if (cause != null && cause.getMessage() != null) {
log.error("调用:{} 异常:{}", getRoute(), cause.getMessage());
return new ByteArrayInputStream(cause.getMessage().getBytes()); return new ByteArrayInputStream(cause.getMessage().getBytes());
} else { } else {
return new ByteArrayInputStream("权限管理模块不可用".getBytes()); log.error("调用:{} 异常:{}", getRoute(), UPMS_SERVICE_DISABLE);
return new ByteArrayInputStream(UPMS_SERVICE_DISABLE.getBytes());
} }
} }

View File

@ -0,0 +1,37 @@
package com.github.pig.gateway.componet.handler;
import com.marcosbarbero.cloud.autoconfigure.zuul.ratelimit.config.repository.DefaultRateLimiterErrorHandler;
import com.marcosbarbero.cloud.autoconfigure.zuul.ratelimit.config.repository.RateLimiterErrorHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author lengleng
* @date 2018/2/26
* 限流降级处理
*/
@Slf4j
@Configuration
public class ZuulRateLimiterErrorHandler {
@Bean
public RateLimiterErrorHandler rateLimitErrorHandler() {
return new DefaultRateLimiterErrorHandler() {
@Override
public void handleSaveError(String key, Exception e) {
log.error("保存key:[{}]异常", key, e);
}
@Override
public void handleFetchError(String key, Exception e) {
log.error("路由失败:[{}]异常", key);
}
@Override
public void handleError(String msg, Exception e) {
log.error("限流异常:[{}]", msg, e);
}
};
}
}

View File

@ -151,7 +151,7 @@
</logger> </logger>
<!-- root级别 DEBUG --> <!-- root级别 DEBUG -->
<root level="INFO"> <root level="DEBUG">
<!-- 控制台输出 --> <!-- 控制台输出 -->
<appender-ref ref="STDOUT" /> <appender-ref ref="STDOUT" />
<!-- 文件输出 --> <!-- 文件输出 -->

View File

@ -0,0 +1,26 @@
package com.github.pig.daemon.job;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.dataflow.DataflowJob;
import com.zen.elasticjob.spring.boot.annotation.ElasticJobConfig;
import java.util.List;
/**
* @author lengleng
* @date 2018/2/8
*/
@ElasticJobConfig(cron = "0/2 * * * * ?", shardingTotalCount = 3, shardingItemParameters = "0=Beijing,1=Shanghai,2=Guangzhou")
public class PigDataflowJob implements DataflowJob<Integer> {
@Override
public List<Integer> fetchData(ShardingContext shardingContext) {
return null;
}
@Override
public void processData(ShardingContext shardingContext, List<Integer> list) {
}
}

View File

@ -0,0 +1,29 @@
package com.github.pig.daemon.job;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.zen.elasticjob.spring.boot.annotation.ElasticJobConfig;
import lombok.extern.slf4j.Slf4j;
/**
* @author lengleng
* @date 2018/2/7
* 测试Job
*/
@Slf4j
@ElasticJobConfig(cron = "0/2 * * * * ?", shardingTotalCount = 3,
shardingItemParameters = "0=pig1,1=pig2,2=pig3",
startedTimeoutMilliseconds = 5000L,
completedTimeoutMilliseconds = 10000L,
eventTraceRdbDataSource = "dataSource")
public class PigSimpleJob implements SimpleJob {
/**
* 业务执行逻辑
*
* @param shardingContext 分片信息
*/
@Override
public void execute(ShardingContext shardingContext) {
log.info("shardingContext:{}", shardingContext);
}
}

View File

@ -4,11 +4,13 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
/** /**
* @author lengleng * @author lengleng
* @date 2017年10月27日13:59:05 * @date 2017年10月27日13:59:05
*/ */
@EnableAsync
@SpringBootApplication @SpringBootApplication
@EnableDiscoveryClient @EnableDiscoveryClient
@ComponentScan(basePackages = {"com.github.pig.admin", "com.github.pig.common.bean"}) @ComponentScan(basePackages = {"com.github.pig.admin", "com.github.pig.common.bean"})

View File

@ -54,7 +54,7 @@ public class MenuController extends BaseController {
* *
* @return 树形菜单 * @return 树形菜单
*/ */
@GetMapping("/userTree/") @GetMapping("/userTree")
public List<Integer> userTree() { public List<Integer> userTree() {
Set<MenuVo> menus = sysMenuService.findMenuByRole(getRole().get(0)); Set<MenuVo> menus = sysMenuService.findMenuByRole(getRole().get(0));
List<Integer> menuList = new ArrayList<>(); List<Integer> menuList = new ArrayList<>();

View File

@ -5,6 +5,7 @@ import com.github.pig.admin.model.dto.UserDto;
import com.github.pig.admin.model.dto.UserInfo; import com.github.pig.admin.model.dto.UserInfo;
import com.github.pig.admin.model.entity.SysUser; import com.github.pig.admin.model.entity.SysUser;
import com.github.pig.admin.model.entity.SysUserRole; import com.github.pig.admin.model.entity.SysUserRole;
import com.github.pig.admin.service.SysDeptService;
import com.github.pig.admin.service.SysUserService; import com.github.pig.admin.service.SysUserService;
import com.github.pig.common.bean.config.FdfsPropertiesConfig; import com.github.pig.common.bean.config.FdfsPropertiesConfig;
import com.github.pig.common.constant.CommonConstant; import com.github.pig.common.constant.CommonConstant;
@ -19,6 +20,7 @@ import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -46,13 +48,15 @@ public class UserController extends BaseController {
/** /**
* 获取当前用户信息角色权限 * 获取当前用户信息角色权限
* 并且异步初始化用户部门信息
* *
* @param userVo 当前用户信息 * @param userVo 当前用户信息
* @return 用户名 * @return 用户名
*/ */
@GetMapping("/info") @GetMapping("/info")
public R<UserInfo> user(UserVo userVo) { public R<UserInfo> user(UserVo userVo) {
return new R<>(userService.findUserInfo(userVo)); UserInfo userInfo = userService.findUserInfo(userVo);
return new R<>(userInfo);
} }
/** /**
@ -72,8 +76,8 @@ public class UserController extends BaseController {
* @param id ID * @param id ID
* @return R * @return R
*/ */
@ApiOperation(value="删除用户", notes="根据ID删除用户") @ApiOperation(value = "删除用户", notes = "根据ID删除用户")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer") @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public R<Boolean> userDel(@PathVariable Integer id) { public R<Boolean> userDel(@PathVariable Integer id) {
SysUser sysUser = userService.selectById(id); SysUser sysUser = userService.selectById(id);
@ -135,13 +139,15 @@ public class UserController extends BaseController {
/** /**
* 通过OpenId查询 * 通过OpenId查询
*
* @param openId openid * @param openId openid
* @return 对象 * @return 对象
*/ */
@GetMapping("/findUserByOpenId/{openId}") @GetMapping("/findUserByOpenId/{openId}")
public UserVo findUserByOpenId(@PathVariable String openId){ public UserVo findUserByOpenId(@PathVariable String openId) {
return userService.findUserByOpenId(openId); return userService.findUserByOpenId(openId);
} }
/** /**
* 分页查询用户 * 分页查询用户
* *
@ -165,7 +171,7 @@ public class UserController extends BaseController {
String fileExt = FileUtil.extName(file.getOriginalFilename()); String fileExt = FileUtil.extName(file.getOriginalFilename());
Map<String, String> resultMap = new HashMap<>(1); Map<String, String> resultMap = new HashMap<>(1);
try { try {
StorePath storePath = fastFileStorageClient.uploadFile(file.getBytes(),fileExt); StorePath storePath = fastFileStorageClient.uploadFile(file.getBytes(), fileExt);
resultMap.put("filename", fdfsPropertiesConfig.getFileHost() + storePath.getFullPath()); resultMap.put("filename", fdfsPropertiesConfig.getFileHost() + storePath.getFullPath());
} catch (IOException e) { } catch (IOException e) {
logger.error("文件上传异常", e); logger.error("文件上传异常", e);
@ -185,5 +191,4 @@ public class UserController extends BaseController {
public R<Boolean> editInfo(@RequestBody UserDto userDto, UserVo userVo) { public R<Boolean> editInfo(@RequestBody UserDto userDto, UserVo userVo) {
return new R<>(userService.updateUserInfo(userDto, userVo.getUsername())); return new R<>(userService.updateUserInfo(userDto, userVo.getUsername()));
} }
} }

View File

@ -24,14 +24,6 @@ public interface SysDeptMapper extends BaseMapper<SysDept> {
*/ */
List<SysDept> selectDeptDtoList(String delFlag); List<SysDept> selectDeptDtoList(String delFlag);
/**
* 维护部门关系表
*
* @param deptRelation 部门关系
* @return 成功失败
*/
void insertDeptRelation(SysDeptRelation deptRelation);
/** /**
* 删除部门关系表数据 * 删除部门关系表数据
* @param id 部门ID * @param id 部门ID

View File

@ -0,0 +1,16 @@
package com.github.pig.admin.mapper;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.github.pig.admin.model.entity.SysDeptRelation;
/**
* <p>
* Mapper 接口
* </p>
*
* @author lengleng
* @since 2018-02-12
*/
public interface SysDeptRelationMapper extends BaseMapper<SysDeptRelation> {
}

View File

@ -2,8 +2,10 @@ package com.github.pig.admin.mapper;
import com.baomidou.mybatisplus.mapper.BaseMapper; import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.github.pig.admin.model.entity.SysUser; import com.github.pig.admin.model.entity.SysUser;
import com.github.pig.common.bean.interceptor.DataScope;
import com.github.pig.common.util.Query; import com.github.pig.common.util.Query;
import com.github.pig.common.vo.UserVo; import com.github.pig.common.vo.UserVo;
import org.apache.ibatis.annotations.Param;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -28,11 +30,11 @@ public interface SysUserMapper extends BaseMapper<SysUser> {
/** /**
* 分页查询用户信息含角色 * 分页查询用户信息含角色
* *
* @param query 查询条件 * @param dataScope 数据权限
* @param params 参数 * @param query 查询条件
* @return list * @return list
*/ */
List selectUserVoPage(Query query, Map<String, Object> params); List selectUserVoPageDataScope(Query query, DataScope dataScope);
/** /**
* 通过手机号查询用户信息含有角色信息 * 通过手机号查询用户信息含有角色信息
@ -52,6 +54,7 @@ public interface SysUserMapper extends BaseMapper<SysUser> {
/** /**
* 通过ID查询用户信息 * 通过ID查询用户信息
*
* @param id 用户ID * @param id 用户ID
* @return userVo * @return userVo
*/ */

View File

@ -0,0 +1,16 @@
package com.github.pig.admin.service;
import com.baomidou.mybatisplus.service.IService;
import com.github.pig.admin.model.entity.SysDeptRelation;
/**
* <p>
* 服务类
* </p>
*
* @author lengleng
* @since 2018-02-12
*/
public interface SysDeptRelationService extends IService<SysDeptRelation> {
}

View File

@ -0,0 +1,20 @@
package com.github.pig.admin.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.pig.admin.mapper.SysDeptRelationMapper;
import com.github.pig.admin.model.entity.SysDeptRelation;
import com.github.pig.admin.service.SysDeptRelationService;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author lengleng
* @since 2018-02-12
*/
@Service
public class SysDeptRelationServiceImpl extends ServiceImpl<SysDeptRelationMapper, SysDeptRelation> implements SysDeptRelationService {
}

View File

@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl; import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.pig.admin.common.util.TreeUtil; import com.github.pig.admin.common.util.TreeUtil;
import com.github.pig.admin.mapper.SysDeptMapper; import com.github.pig.admin.mapper.SysDeptMapper;
import com.github.pig.admin.mapper.SysDeptRelationMapper;
import com.github.pig.admin.model.dto.DeptTree; import com.github.pig.admin.model.dto.DeptTree;
import com.github.pig.admin.model.entity.SysDept; import com.github.pig.admin.model.entity.SysDept;
import com.github.pig.admin.model.entity.SysDeptRelation; import com.github.pig.admin.model.entity.SysDeptRelation;
@ -29,6 +30,8 @@ import java.util.List;
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService { public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {
@Autowired @Autowired
private SysDeptMapper sysDeptMapper; private SysDeptMapper sysDeptMapper;
@Autowired
private SysDeptRelationMapper sysDeptRelationMapper;
/** /**
* 添加信息部门 * 添加信息部门
@ -41,12 +44,28 @@ public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> impl
SysDept sysDept = new SysDept(); SysDept sysDept = new SysDept();
BeanUtils.copyProperties(dept, sysDept); BeanUtils.copyProperties(dept, sysDept);
this.insert(sysDept); this.insert(sysDept);
this.insertDeptRelation(sysDept);
return Boolean.TRUE;
}
/**
* 维护部门关系
* @param sysDept 部门
*/
private void insertDeptRelation(SysDept sysDept) {
//增加部门关系表 //增加部门关系表
SysDeptRelation deptRelation = new SysDeptRelation(); SysDeptRelation deptRelation = new SysDeptRelation();
deptRelation.setAncestor(dept.getParentId()); deptRelation.setDescendant(sysDept.getParentId());
deptRelation.setDescendant(sysDept.getDeptId()); List<SysDeptRelation> deptRelationList = sysDeptRelationMapper.selectList(new EntityWrapper<>(deptRelation));
sysDeptMapper.insertDeptRelation(deptRelation); for (SysDeptRelation sysDeptRelation : deptRelationList) {
return Boolean.TRUE; sysDeptRelation.setDescendant(sysDept.getDeptId());
sysDeptRelationMapper.insert(sysDeptRelation);
}
//自己也要维护到关系表中
SysDeptRelation own = new SysDeptRelation();
own.setDescendant(sysDept.getDeptId());
own.setAncestor(sysDept.getDeptId());
sysDeptRelationMapper.insert(own);
} }
/** /**
@ -79,10 +98,7 @@ public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> impl
//删除部门关系 //删除部门关系
sysDeptMapper.deleteDeptRealtion(sysDept.getDeptId()); sysDeptMapper.deleteDeptRealtion(sysDept.getDeptId());
//新建部门关系 //新建部门关系
SysDeptRelation deptRelation = new SysDeptRelation(); this.insertDeptRelation(sysDept);
deptRelation.setAncestor(sysDept.getParentId());
deptRelation.setDescendant(sysDept.getDeptId());
sysDeptMapper.insertDeptRelation(deptRelation);
return null; return null;
} }

View File

@ -5,22 +5,27 @@ import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl; import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.pig.admin.model.dto.UserDto; import com.github.pig.admin.model.dto.UserDto;
import com.github.pig.admin.model.dto.UserInfo; import com.github.pig.admin.model.dto.UserInfo;
import com.github.pig.admin.model.entity.SysDeptRelation;
import com.github.pig.admin.model.entity.SysUser; import com.github.pig.admin.model.entity.SysUser;
import com.github.pig.admin.model.entity.SysUserRole; import com.github.pig.admin.model.entity.SysUserRole;
import com.github.pig.admin.mapper.SysUserMapper; import com.github.pig.admin.mapper.SysUserMapper;
import com.github.pig.admin.service.SysDeptRelationService;
import com.github.pig.admin.service.SysMenuService; import com.github.pig.admin.service.SysMenuService;
import com.github.pig.admin.service.SysUserRoleService; import com.github.pig.admin.service.SysUserRoleService;
import com.github.pig.admin.service.SysUserService; import com.github.pig.admin.service.SysUserService;
import com.github.pig.common.bean.interceptor.DataScope;
import com.github.pig.common.constant.CommonConstant; import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.constant.MqQueueConstant; import com.github.pig.common.constant.MqQueueConstant;
import com.github.pig.common.constant.SecurityConstants; import com.github.pig.common.constant.SecurityConstants;
import com.github.pig.common.util.Query; import com.github.pig.common.util.Query;
import com.github.pig.common.util.UserUtils;
import com.github.pig.common.util.template.MobileMsgTemplate; import com.github.pig.common.util.template.MobileMsgTemplate;
import com.github.pig.common.vo.SysRole; import com.github.pig.common.vo.SysRole;
import com.github.pig.common.vo.UserVo; import com.github.pig.common.vo.UserVo;
import com.xiaoleilu.hutool.util.CollectionUtil; import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.RandomUtil; import com.xiaoleilu.hutool.util.RandomUtil;
import com.xiaoleilu.hutool.util.StrUtil; import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.amqp.rabbit.core.RabbitTemplate;
@ -56,6 +61,8 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
private RabbitTemplate rabbitTemplate; private RabbitTemplate rabbitTemplate;
@Autowired @Autowired
private SysUserRoleService sysUserRoleService; private SysUserRoleService sysUserRoleService;
@Autowired
private SysDeptRelationService sysDeptRelationService;
@Override @Override
public UserInfo findUserInfo(UserVo userVo) { public UserInfo findUserInfo(UserVo userVo) {
@ -115,7 +122,12 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
@Override @Override
public Page selectWithRolePage(Query query) { public Page selectWithRolePage(Query query) {
query.setRecords(sysUserMapper.selectUserVoPage(query, query.getCondition())); DataScope dataScope = new DataScope();
dataScope.setScopeName("deptId");
dataScope.setIsOnly(true);
dataScope.setDeptIds(getChildDepts());
dataScope.putAll(query.getCondition());
query.setRecords(sysUserMapper.selectUserVoPageDataScope(query, dataScope));
return query; return query;
} }
@ -185,12 +197,11 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
public Boolean updateUserInfo(UserDto userDto, String username) { public Boolean updateUserInfo(UserDto userDto, String username) {
UserVo userVo = this.findUserByUsername(username); UserVo userVo = this.findUserByUsername(username);
if (!ENCODER.matches(userDto.getPassword(), userVo.getPassword())) {
return Boolean.FALSE;
}
SysUser sysUser = new SysUser(); SysUser sysUser = new SysUser();
if (ENCODER.matches(userDto.getPassword(), userVo.getPassword())) {
sysUser.setPassword(ENCODER.encode(userDto.getNewpassword1()));
}
sysUser.setUserId(userVo.getUserId()); sysUser.setUserId(userVo.getUserId());
sysUser.setPassword(ENCODER.encode(userDto.getNewpassword1()));
sysUser.setAvatar(userDto.getAvatar()); sysUser.setAvatar(userDto.getAvatar());
return this.updateById(sysUser); return this.updateById(sysUser);
} }
@ -209,4 +220,27 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
sysUserRole.setRoleId(userDto.getRole()); sysUserRole.setRoleId(userDto.getRole());
return sysUserRoleService.update(sysUserRole, new EntityWrapper<>(condition)); return sysUserRoleService.update(sysUserRole, new EntityWrapper<>(condition));
} }
/**
* 获取当前用户的子部门信息
*
* @return 子部门列表
*/
private List<Integer> getChildDepts() {
//获取当前用户的部门
String username = UserUtils.getUser();
UserVo userVo = findUserByUsername(username);
Integer deptId = userVo.getDeptId();
//获取当前部门的子部门
SysDeptRelation deptRelation = new SysDeptRelation();
deptRelation.setAncestor(deptId);
List<SysDeptRelation> deptRelationList = sysDeptRelationService.selectList(new EntityWrapper<>(deptRelation));
List<Integer> deptIds = new ArrayList<>();
for (SysDeptRelation sysDeptRelation : deptRelationList) {
deptIds.add(sysDeptRelation.getDescendant());
}
return deptIds;
}
} }

View File

@ -45,19 +45,4 @@
LEFT JOIN sys_dept_relation dr ON t.dept_id = dr.descendant LEFT JOIN sys_dept_relation dr ON t.dept_id = dr.descendant
WHERE dr.ancestor = 0 WHERE dr.ancestor = 0
</select> </select>
<!--维护部门关系-->
<insert id="insertDeptRelation">
INSERT INTO sys_dept_relation (ancestor, descendant) SELECT
dt.ancestor,
#{descendant}
FROM
sys_dept_relation dt
WHERE
dt.descendant = #{ancestor}
UNION ALL
SELECT
#{descendant},
#{descendant}
</insert>
</mapper> </mapper>

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.github.pig.admin.mapper.SysDeptRelationMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.github.pig.admin.model.entity.SysDeptRelation">
<id column="ancestor" property="ancestor" />
<result column="descendant" property="descendant" />
</resultMap>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
ancestor, descendant
</sql>
</mapper>

View File

@ -106,7 +106,7 @@
`user`.user_id = #{id} `user`.user_id = #{id}
</select> </select>
<select id="selectUserVoPage" resultMap="userVoResultMap" > <select id="selectUserVoPageDataScope" resultMap="userVoResultMap" >
SELECT SELECT
`user`.user_id, `user`.user_id,
`user`.username, `user`.username,

View File

@ -48,6 +48,18 @@
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId> <artifactId>spring-boot-starter-jdbc</artifactId>
<exclusions>
<!--去掉默认的tomcat-jdbc的依赖-->
<exclusion>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--HikariCP连接池-->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency> </dependency>
</dependencies> </dependencies>