Commit dc87f013cbb26703fcfee0de5e465ef2396bb3c7

Authored by guzijian
1 parent ab228c79

feat: 模块整合,取消独立服务,修改login

Showing 30 changed files with 137 additions and 1018 deletions
trash-admin/pom.xml
... ... @@ -90,6 +90,11 @@
90 90 <groupId>com.trash</groupId>
91 91 <artifactId>trash-unit</artifactId>
92 92 </dependency>
  93 + <dependency>
  94 + <groupId>com.trash</groupId>
  95 + <artifactId>trash-garbage</artifactId>
  96 + <version>3.2.0</version>
  97 + </dependency>
93 98 </dependencies>
94 99  
95 100 <build>
... ...
trash-framework/src/main/java/com/trash/framework/config/SecurityConfig.java
... ... @@ -117,6 +117,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter
117 117 .antMatchers("/webjars/**").anonymous()
118 118 .antMatchers("/*/api-docs").anonymous()
119 119 .antMatchers("/druid/**").anonymous()
  120 + .antMatchers("/user/login").anonymous()
  121 + .antMatchers("/user/send/verify").anonymous()
  122 + .antMatchers("/user/logout").anonymous()
120 123 .antMatchers("/system/post/all").anonymous()
121 124 .antMatchers("/system/user/all").anonymous()
122 125 // .antMatchers("/workflow/add").anonymous()//测试
... ...
trash-garbage/pom.xml
... ... @@ -22,16 +22,6 @@
22 22 <groupId>com.trash</groupId>
23 23 <artifactId>trash-common</artifactId>
24 24 </dependency>
25   - <!-- mysql connect-->
26   - <dependency>
27   - <groupId>mysql</groupId>
28   - <artifactId>mysql-connector-java</artifactId>
29   - </dependency>
30   - <dependency>
31   - <groupId>com.alibaba</groupId>
32   - <artifactId>druid-spring-boot-starter</artifactId>
33   - <version>1.2.1</version>
34   - </dependency>
35 25 <!-- mybatis plus-->
36 26 <dependency>
37 27 <groupId>com.baomidou</groupId>
... ... @@ -39,80 +29,31 @@
39 29 <version>3.5.4.1</version>
40 30 </dependency>
41 31 <dependency>
42   - <groupId>org.springframework.boot</groupId>
43   - <artifactId>spring-boot-starter-web</artifactId>
  32 + <groupId>com.trash</groupId>
  33 + <artifactId>trash-activiti</artifactId>
44 34 </dependency>
45   - <!-- knife4j swagger-ui-->
46 35 <dependency>
47   - <groupId>com.github.xiaoymin</groupId>
48   - <artifactId>knife4j-spring-boot-starter</artifactId>
49   - <!--在引用时请在maven中央仓库搜索2.X最新版本号-->
50   - <version>2.0.7</version>
  36 + <groupId>com.trash</groupId>
  37 + <artifactId>trash-framework</artifactId>
51 38 </dependency>
52 39 <dependency>
53   - <groupId>org.projectlombok</groupId>
54   - <artifactId>lombok</artifactId>
  40 + <groupId>com.aliyun</groupId>
  41 + <artifactId>aliyun-java-sdk-core</artifactId>
  42 + <version>4.5.16</version>
55 43 </dependency>
56   - <!-- jjwt -->
57 44 <dependency>
58   - <groupId>io.jsonwebtoken</groupId>
59   - <artifactId>jjwt</artifactId>
  45 + <groupId>com.aliyun</groupId>
  46 + <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
  47 + <version>2.1.0</version>
60 48 </dependency>
61   - <!-- fastjson-->
62 49 <dependency>
63   - <groupId>com.alibaba</groupId>
64   - <artifactId>fastjson</artifactId>
  50 + <groupId>org.projectlombok</groupId>
  51 + <artifactId>lombok</artifactId>
65 52 </dependency>
66   - <!-- hutool 工具包-->
67 53 <dependency>
68 54 <groupId>cn.hutool</groupId>
69 55 <artifactId>hutool-all</artifactId>
70 56 <version>5.3.8</version>
71 57 </dependency>
72   - <!-- 引入redis连接池的依赖 -->
73   - <!-- 我配置文件配置了redis连接池 所以需要这个依赖-->
74   - <dependency>
75   - <groupId>org.apache.commons</groupId>
76   - <artifactId>commons-pool2</artifactId>
77   - <version>2.8.1</version>
78   - </dependency>
79   - <dependency>
80   - <groupId>org.springframework</groupId>
81   - <artifactId>spring-webmvc</artifactId>
82   - </dependency>
83   - <!-- jackson 2.x 相关依赖 -->
84   -
85   - <dependency>
86   - <groupId>com.fasterxml.jackson.core</groupId>
87   - <artifactId>jackson-core</artifactId>
88   - </dependency>
89   - <dependency>
90   - <groupId>com.fasterxml.jackson.core</groupId>
91   - <artifactId>jackson-databind</artifactId>
92   - </dependency>
93   - <dependency>
94   - <groupId>com.fasterxml.jackson.core</groupId>
95   - <artifactId>jackson-annotations</artifactId>
96   - </dependency>
97   - <dependency>
98   - <groupId>com.aliyun</groupId>
99   - <artifactId>aliyun-java-sdk-core</artifactId>
100   - <version>4.5.16</version>
101   - </dependency>
102   - <dependency>
103   - <groupId>com.aliyun</groupId>
104   - <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
105   - <version>2.1.0</version>
106   - </dependency>
107 58 </dependencies>
108   -
109   - <build>
110   - <finalName>garbage</finalName>
111   - <plugins>
112   - <plugin>
113   - <groupId>org.springframework.boot</groupId>
114   - <artifactId>spring-boot-maven-plugin</artifactId>
115   - </plugin>
116   - </plugins>
117   - </build>
118 59 </project>
119 60 \ No newline at end of file
... ...
trash-garbage/src/main/java/com/trash/garbage/GarbageApplication.java deleted 100644 → 0
1   -package com.trash.garbage;
2   -
3   -import lombok.extern.slf4j.Slf4j;
4   -import org.springframework.boot.SpringApplication;
5   -import org.springframework.boot.autoconfigure.SpringBootApplication;
6   -import org.springframework.context.ConfigurableApplicationContext;
7   -import org.springframework.core.env.ConfigurableEnvironment;
8   -import org.springframework.scheduling.annotation.EnableAsync;
9   -
10   -import java.net.InetAddress;
11   -import java.net.UnknownHostException;
12   -import java.util.ArrayList;
13   -import java.util.List;
14   -import java.util.regex.Matcher;
15   -import java.util.regex.Pattern;
16   -
17   -/**
18   - * @author trash
19   - */
20   -@SpringBootApplication
21   -@EnableAsync
22   -@Slf4j
23   -public class GarbageApplication {
24   - public static void main(String[] args) throws UnknownHostException {
25   - ConfigurableApplicationContext run = SpringApplication.run(GarbageApplication.class, args);
26   - ConfigurableEnvironment env = run.getEnvironment();
27   - String ip = InetAddress.getLocalHost().getHostAddress();
28   - String port = env.getProperty("server.port");
29   - String path = env.getProperty("server.servlet.context-path");
30   - String redisPort = env.getProperty("spring.redis.port");
31   - String redisHost = env.getProperty("spring.redis.host");
32   - String sqlUrl = env.getProperty("spring.datasource.druid.url");
33   - List<String> sqlInfo = getSqlInfo(sqlUrl);
34   - log.info(
35   - "\n Swagger访问地址:http://" + ip + ":" + port + path + "/doc.html \n" +
36   - " Redis服务器地址:" + redisHost + ":" + redisPort + "\n" +
37   - " Mysql服务器地址:" + sqlInfo.get(0) + ":" + sqlInfo.get(1));
38   - log.info("--装修垃圾服务启动成功 --");
39   - }
40   - private static List<String> getSqlInfo(String sqlInfo) {
41   - List<String> str = new ArrayList<>(3);
42   - Pattern pattern = Pattern.compile("jdbc:mysql://([a-zA-Z0-9.-]+):(\\d+)/");
43   - Matcher matcher = pattern.matcher(sqlInfo);
44   - if (matcher.find()) {
45   - str.add(matcher.group(1));
46   - str.add(matcher.group(2));
47   - }
48   - return str;
49   - }
50   -}
trash-garbage/src/main/java/com/trash/garbage/config/CorsConfig.java deleted 100644 → 0
1   -package com.trash.garbage.config;
2   -
3   -import org.springframework.context.annotation.Configuration;
4   -import org.springframework.web.servlet.config.annotation.CorsRegistry;
5   -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
6   -
7   -/**
8   - *
9   - * 允许跨域 后期修改 前端做服务代理
10   - * @author 20412
11   - */
12   -@Configuration
13   -public class CorsConfig implements WebMvcConfigurer {
14   -
15   - @Override
16   - public void addCorsMappings(CorsRegistry registry) {
17   - registry.addMapping("/**")
18   - .allowedOrigins("*")
19   - .allowCredentials(true)
20   - .allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH")
21   - .maxAge(3600);
22   - }
23   -
24   -}
trash-garbage/src/main/java/com/trash/garbage/config/RedisConfig.java deleted 100644 → 0
1   -package com.trash.garbage.config;
2   -
3   -import com.trash.garbage.utils.FastJson2JsonRedisSerializer;
4   -import org.springframework.cache.CacheManager;
5   -import org.springframework.context.annotation.Bean;
6   -import org.springframework.context.annotation.Configuration;
7   -import org.springframework.data.redis.cache.RedisCacheConfiguration;
8   -import org.springframework.data.redis.cache.RedisCacheManager;
9   -import org.springframework.data.redis.connection.RedisConnectionFactory;
10   -import org.springframework.data.redis.core.RedisTemplate;
11   -import org.springframework.data.redis.serializer.RedisSerializationContext;
12   -import org.springframework.data.redis.serializer.RedisSerializer;
13   -import org.springframework.data.redis.serializer.StringRedisSerializer;
14   -
15   -import java.time.Duration;
16   -
17   -
18   -/**
19   - * redis 配置文件
20   - * @author 20412
21   - */
22   -// 开启缓存
23   -//@EnableCaching
24   -@Configuration
25   -public class RedisConfig {
26   - @Bean
27   - public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
28   - RedisTemplate<String, Object> template = new RedisTemplate<>();
29   - StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
30   -// Jackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
31   - // 使用fast json来完成反序列
32   - FastJson2JsonRedisSerializer<Object> fastJson2JsonRedisSerializer = new FastJson2JsonRedisSerializer<>(Object.class);
33   -// ObjectMapper om = new ObjectMapper();
34   -// om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
35   - // 解决linkArraylist反序列化问题
36   -// om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance ,ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
37   -// genericJackson2JsonRedisSerializer.setObjectMapper(om);
38   - template.setConnectionFactory(factory);
39   - //key序列化方式
40   - template.setKeySerializer(stringRedisSerializer);
41   - //value序列化
42   - template.setValueSerializer(fastJson2JsonRedisSerializer);
43   - template.setHashKeySerializer(stringRedisSerializer);
44   - //value hashmap序列化 Jackson2JsonRedisSerializer 主要针对String类型的数据
45   - template.setHashValueSerializer(fastJson2JsonRedisSerializer);
46   - return template;
47   - }
48   -
49   - @Bean
50   - public CacheManager cacheManager(RedisConnectionFactory factory) {
51   - RedisSerializer<String> redisSerializer = new StringRedisSerializer();
52   - FastJson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new FastJson2JsonRedisSerializer<>(Object.class);
53   -// 配置序列化(解决乱码的问题),过期时间600秒
54   - RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
55   - .entryTtl(Duration.ofSeconds(600))
56   - .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
57   - .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
58   - .disableCachingNullValues();
59   - RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
60   - .cacheDefaults(config)
61   - .build();
62   - return cacheManager;
63   - }
64   -}
65 0 \ No newline at end of file
trash-garbage/src/main/java/com/trash/garbage/config/RestTemplateConfig.java deleted 100644 → 0
1   -package com.trash.garbage.config;
2   -
3   -import org.springframework.context.annotation.Bean;
4   -import org.springframework.context.annotation.Configuration;
5   -import org.springframework.web.client.RestTemplate;
6   -
7   -@Configuration
8   -public class RestTemplateConfig {
9   - @Bean
10   - public RestTemplate getRestTemplate(){
11   - return new RestTemplate();
12   - }
13   -}
trash-garbage/src/main/java/com/trash/garbage/config/SwaggerConfiguration.java deleted 100644 → 0
1   -package com.trash.garbage.config;
2   -
3   -import com.trash.garbage.global.ResultCode;
4   -import org.springframework.beans.factory.annotation.Autowired;
5   -import org.springframework.context.annotation.Bean;
6   -import org.springframework.context.annotation.Configuration;
7   -import org.springframework.web.bind.annotation.RequestMethod;
8   -import springfox.documentation.builders.ApiInfoBuilder;
9   -import springfox.documentation.builders.PathSelectors;
10   -import springfox.documentation.builders.RequestHandlerSelectors;
11   -import springfox.documentation.builders.ResponseMessageBuilder;
12   -import springfox.documentation.schema.ModelRef;
13   -import springfox.documentation.service.ApiInfo;
14   -import springfox.documentation.service.ResponseMessage;
15   -import springfox.documentation.spi.DocumentationType;
16   -import springfox.documentation.spring.web.plugins.Docket;
17   -import springfox.documentation.swagger2.annotations.EnableSwagger2;
18   -
19   -import java.util.ArrayList;
20   -import java.util.Arrays;
21   -import java.util.List;
22   -
23   -/**
24   - * @author guzijian
25   - * 2020/11/07 9:26
26   - * @since:knife4j-spring-boot-fast-demo 1.0
27   - */
28   -@Configuration
29   -@EnableSwagger2
30   -public class SwaggerConfiguration {
31   -
32   - @Bean(value = "defaultApi2")
33   - public Docket defaultApi2() {
34   - //添加全局响应状态码
35   - List<ResponseMessage> responseMessageList = new ArrayList<>();
36   - Arrays.stream(ResultCode.values()).forEach(errorEnum -> {
37   - responseMessageList.add(
38   - new ResponseMessageBuilder().code(errorEnum.getCode()).message(errorEnum.getMsg()).responseModel(
39   - new ModelRef(errorEnum.getMsg()))
40   - .build()
41   - );
42   - });
43   -
44   - String groupName="学习间swagger";
45   -
46   - Docket docket=new Docket(DocumentationType.SWAGGER_2)
47   - .globalResponseMessage(RequestMethod.GET,responseMessageList)
48   - .globalResponseMessage(RequestMethod.POST,responseMessageList)
49   - .globalResponseMessage(RequestMethod.DELETE,responseMessageList)
50   - .globalResponseMessage(RequestMethod.PUT,responseMessageList)
51   - .host("http://localhost:9090/")
52   - .apiInfo(apiInfo())
53   - .groupName(groupName)
54   - .select()
55   - .apis(RequestHandlerSelectors.basePackage("com.trash.garbage"))
56   - .paths(PathSelectors.any())
57   - .build();
58   - return docket;
59   - }
60   -
61   - private ApiInfo apiInfo() {
62   - return new ApiInfoBuilder()
63   - .description(" 学习间接口文档 ")
64   - .contact("204126329@qq.com")
65   - .version("1.0")
66   - .build();
67   - }
68   -}
69 0 \ No newline at end of file
trash-garbage/src/main/java/com/trash/garbage/config/WebSecurityConfig.java deleted 100644 → 0
1   -package com.trash.garbage.config;
2   -import com.trash.garbage.security.JwtAuthenticationFilterAbstract;
3   -import org.springframework.beans.factory.annotation.Autowired;
4   -import org.springframework.beans.factory.annotation.Value;
5   -import org.springframework.context.annotation.Bean;
6   -import org.springframework.context.annotation.Configuration;
7   -import org.springframework.security.authentication.AuthenticationManager;
8   -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
9   -import org.springframework.security.config.annotation.web.builders.HttpSecurity;
10   -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
11   -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
12   -import org.springframework.security.config.http.SessionCreationPolicy;
13   -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
14   -import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
15   -import org.springframework.security.web.util.matcher.OrRequestMatcher;
16   -import org.springframework.security.web.util.matcher.RequestMatcher;
17   -
18   -/**
19   - * security配置类
20   - * @author gzj
21   - */
22   -@Configuration
23   -@EnableWebSecurity
24   -@EnableGlobalMethodSecurity(prePostEnabled = true)
25   -public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
26   -
27   - @Autowired
28   - private JwtAuthenticationFilterAbstract jwtAuthenticationFilter;
29   -
30   - /**
31   - * 放行路径
32   - */
33   - @Value("${trash.garbage.config.location.exclude}")
34   - private String[] exclude;
35   -
36   - /**
37   - * 放行端口 和security配置
38   - * @param http
39   - * @throws Exception
40   - */
41   - @Override
42   - protected void configure(HttpSecurity http) throws Exception {
43   -
44   - RequestMatcher PUBLIC_URLS = new OrRequestMatcher(
45   - new AntPathRequestMatcher("/**", "OPTIONS"),
46   - new AntPathRequestMatcher("/error/**")
47   - );
48   -
49   - http
50   - // 关闭 csrf
51   - .csrf().disable()
52   - // 前后端分离的项目session就不管用了 不通过session获取securityContext
53   - .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
54   - .and()
55   - .authorizeRequests()
56   - // 对于登录接口 允许匿名访问
57   - .antMatchers(exclude).anonymous()
58   - .requestMatchers(PUBLIC_URLS).permitAll()
59   - // 任意认证成功后都可以访问
60   - .anyRequest().authenticated();
61   -
62   - http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
63   - // spring security 异常处理 用于权限认证
64   -// http.exceptionHandling()
65   - // 权限异常
66   -// .accessDeniedHandler()
67   - // 认证异常
68   -// .authenticationEntryPoint();
69   - }
70   -
71   - /**
72   - * 重写认证管理
73   - * @return
74   - * @throws Exception
75   - */
76   - @Bean
77   - @Override
78   - public AuthenticationManager authenticationManagerBean() throws Exception {
79   - return super.authenticationManagerBean();
80   - }
81   -
82   - /**
83   - * 监听器 监听认证结果 当认证成功后触发
84   - * @param applicationEventPublisher
85   - * @return
86   - */
87   -// @Bean
88   -// public AuthenticationEventPublisher authenticationEventPublisher
89   -// (ApplicationEventPublisher applicationEventPublisher) {
90   -// return new DefaultAuthenticationEventPublisher(applicationEventPublisher);
91   -// }
92   -
93   -
94   -}
95 0 \ No newline at end of file
trash-garbage/src/main/java/com/trash/garbage/controller/GarbageUserController.java
... ... @@ -6,8 +6,6 @@ import com.trash.garbage.pojo.domain.GarAddress;
6 6 import com.trash.garbage.pojo.dto.AddressDto;
7 7 import com.trash.garbage.pojo.dto.LoginDto;
8 8 import com.trash.garbage.service.GarUserService;
9   -import io.swagger.annotations.Api;
10   -import io.swagger.annotations.ApiOperation;
11 9 import org.springframework.beans.factory.annotation.Autowired;
12 10 import org.springframework.validation.annotation.Validated;
13 11 import org.springframework.web.bind.annotation.*;
... ... @@ -19,7 +17,6 @@ import java.util.List;
19 17 */
20 18 @RestController
21 19 @RequestMapping("user")
22   -@Api(tags = "建筑垃圾-用户接口")
23 20 public class GarbageUserController {
24 21  
25 22 @Autowired
... ... @@ -31,13 +28,11 @@ public class GarbageUserController {
31 28 * @param user
32 29 * @return
33 30 */
34   - @ApiOperation("用户接口-用户登录")
35 31 @PostMapping("/login")
36 32 public Result<String> login(@RequestBody LoginDto user) {
37 33 return Result.OK(garUserService.login(user));
38 34 }
39 35  
40   - @ApiOperation("用户接口-发送验证码")
41 36 @GetMapping("/send/verify")
42 37 public Result<?> sendVerify(@RequestParam("tel") String tel) {
43 38 try {
... ... @@ -49,27 +44,23 @@ public class GarbageUserController {
49 44 }
50 45 }
51 46  
52   - @ApiOperation("用户接口-获取用户地址")
53 47 @GetMapping("/query/address/{type}")
54 48 public Result<List<GarAddress>> queryAddress(@PathVariable("type") String type) {
55 49 return Result.OK(garUserService.queryAddress(type));
56 50 }
57 51  
58   - @ApiOperation("用户接口-新增地址")
59 52 @PostMapping("/save/address")
60 53 public Result<String> saveAddress(@Validated @RequestBody AddressDto dto) {
61 54 return Result.OK(null, garUserService.saveAddress(dto));
62 55 }
63 56  
64 57  
65   - @ApiOperation("用户接口-编辑地址")
66 58 @PostMapping("/update/address")
67 59 public Result<String> updateAddress(@Validated @RequestBody AddressDto dto) {
68 60 return Result.OK(null, garUserService.updateAddress(dto));
69 61 }
70 62  
71 63  
72   - @ApiOperation("用户接口-删除地址")
73 64 @DeleteMapping("/delete/address/{addressId}")
74 65 public Result<String> deleteAddress(@PathVariable("addressId") String addressId) {
75 66 return Result.OK(null, garUserService.deleteAddress(addressId));
... ...
trash-garbage/src/main/java/com/trash/garbage/filter/JwtAuthenticationFilter.java deleted 100644 → 0
1   -package com.trash.garbage.filter;
2   -
3   -import com.trash.common.utils.StringUtils;
4   -import com.trash.garbage.global.GlobalRedisProperties;
5   -import com.trash.garbage.security.JwtAuthenticationFilterAbstract;
6   -import com.trash.garbage.security.UserCustom;
7   -import com.trash.garbage.utils.JwtUtils;
8   -import com.trash.garbage.utils.RedisUtils;
9   -import lombok.extern.slf4j.Slf4j;
10   -import org.springframework.beans.factory.annotation.Autowired;
11   -import org.springframework.beans.factory.annotation.Value;
12   -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
13   -import org.springframework.security.core.Authentication;
14   -import org.springframework.security.core.context.SecurityContextHolder;
15   -import org.springframework.security.core.userdetails.UsernameNotFoundException;
16   -import org.springframework.stereotype.Component;
17   -import org.springframework.util.AntPathMatcher;
18   -import javax.servlet.FilterChain;
19   -import javax.servlet.ServletException;
20   -import javax.servlet.http.HttpServletRequest;
21   -import javax.servlet.http.HttpServletResponse;
22   -import java.io.IOException;
23   -import static com.trash.garbage.interfaces.Authorization.AUTHORIZATION;
24   -
25   -/**
26   - * 实现登录认证逻辑
27   - * @author 20412
28   - */
29   -@Component
30   -@Slf4j
31   -public class JwtAuthenticationFilter extends JwtAuthenticationFilterAbstract {
32   -
33   - private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
34   -
35   - @Autowired
36   - private RedisUtils redisUtils;
37   -
38   - @Value("${trash.garbage.config.location.exclude}")
39   - private String[] exclude;
40   -
41   - @Override
42   - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
43   - String token = request.getHeader(AUTHORIZATION);
44   - // 如果为空说明没有认证 进入下一层过滤器进行安全认证
45   - if(StringUtils.isBlank(token) || doCheck(request.getRequestURI())){
46   - filterChain.doFilter(request, response);
47   - return;
48   - }
49   -
50   - String userId = JwtUtils.getUserId(token);
51   - UserCustom customUser = (UserCustom) redisUtils.get(GlobalRedisProperties.REDIS_USER_HEADER.getValue() + userId);
52   - if(customUser == null){
53   - throw new UsernameNotFoundException("认证信息过期,请重新登录");
54   - }
55   - log.info("userId:{}",userId);
56   - Authentication authenticationToken = new UsernamePasswordAuthenticationToken(customUser,null,null);
57   - SecurityContextHolder.getContext().setAuthentication(authenticationToken);
58   - // 放行
59   - filterChain.doFilter(request,response);
60   - }
61   -
62   - private boolean doCheck(String url) {
63   - for (String location : exclude) {
64   - if (PATH_MATCHER.match(location,url)){
65   - return true;
66   - }
67   - }
68   - return false;
69   - }
70   -}
71 0 \ No newline at end of file
trash-garbage/src/main/java/com/trash/garbage/global/GlobalStatus.java
... ... @@ -2,6 +2,7 @@ package com.trash.garbage.global;
2 2  
3 3 /**
4 4 * 全局状态管理
  5 + *
5 6 * @author guzijian
6 7 */
7 8 public class GlobalStatus {
... ... @@ -26,42 +27,55 @@ public class GlobalStatus {
26 27 /**
27 28 * 用户状态管理
28 29 */
29   - public enum UserStatusEnum{
  30 + public enum UserStatusEnum {
30 31 /**
31   - * 管理员
  32 + * 微信登录
32 33 */
33   - WX_LOGIN(1,"微信登录"),
  34 + WX_LOGIN(1, "微信登录"),
34 35 /**
35   - * 普通用户
  36 + * 普通登录
36 37 */
37   - NORMAL_LOGIN(0,"普通登录");
  38 + NORMAL_LOGIN(0, "普通登录"),
  39 + NORMAL_USER(0, "普通用户"),
  40 + DRIVER_USER(1, "驾驶员用户");
38 41  
39 42 private Integer status;
40 43 private String description;
41   - public int getStatus(){
  44 +
  45 + public int getStatus() {
42 46 return this.status;
43 47 }
44   - UserStatusEnum(Integer status,String description){
  48 +
  49 + public String getDescription() {
  50 + return this.description;
  51 + }
  52 +
  53 + UserStatusEnum(Integer status, String description) {
45 54 this.status = status;
46 55 this.description = description;
47 56 }
48 57 }
  58 +
49 59 /**
50 60 * 字典
51 61 */
52 62 public enum GarAddressStatus {
53   - NORMAL_ADDRESS(0,"地址"),
54   - CURRENT_ADDRESS(1,"当前地址");
55   - GarAddressStatus(Integer status,String description){
  63 + NORMAL_ADDRESS(0, "地址"),
  64 + CURRENT_ADDRESS(1, "当前地址");
  65 +
  66 + GarAddressStatus(Integer status, String description) {
56 67 this.status = status;
57 68 this.description = description;
58 69 }
  70 +
59 71 private String description;
60 72 private Integer status;
61   - public Integer getValue(){
  73 +
  74 + public Integer getValue() {
62 75 return this.status;
63 76 }
64   - public String getDescription(){
  77 +
  78 + public String getDescription() {
65 79 return this.description;
66 80 }
67 81  
... ...
trash-garbage/src/main/java/com/trash/garbage/global/Result.java
1 1 package com.trash.garbage.global;
2 2  
3   -import io.swagger.annotations.ApiModel;
4   -import io.swagger.annotations.ApiModelProperty;
5 3 import lombok.Data;
6 4  
7 5 import static com.trash.garbage.global.ResultCode.CODE_200;
... ... @@ -13,19 +11,14 @@ import static com.trash.garbage.global.ResultCode.CODE_500;
13 11 * @author 20412
14 12 */
15 13 @Data
16   -@ApiModel("返回结果")
17 14 public class Result<T extends Object> {
18 15  
19   - @ApiModelProperty(value = "是否成功")
20 16 private Boolean success;
21 17  
22   - @ApiModelProperty(value = "状态码")
23 18 private Integer code;
24 19  
25   - @ApiModelProperty(value = "返回消息")
26 20 private String msg;
27 21  
28   - @ApiModelProperty(value = "返回对象")
29 22 private T data ;
30 23  
31 24 private Result() {}
... ...
trash-garbage/src/main/java/com/trash/garbage/interceptor/MyMetaObjectHandler.java
1 1 package com.trash.garbage.interceptor;
2 2  
3 3 import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
4   -import com.trash.garbage.utils.SecurityUtil;
  4 +import com.trash.common.utils.SecurityUtils;
5 5 import lombok.extern.slf4j.Slf4j;
6 6 import org.apache.ibatis.reflection.MetaObject;
7 7 import org.springframework.stereotype.Component;
8 8  
9 9 import java.util.Date;
10   -import java.util.Objects;
11 10  
12 11 /**
13 12 * mybatis 拦截器全局注入
  13 + *
14 14 * @author 20412
15 15 */
16 16 @Slf4j
... ... @@ -20,39 +20,33 @@ public class MyMetaObjectHandler implements MetaObjectHandler {
20 20 @Override
21 21 public void insertFill(MetaObject metaObject) {
22 22 log.info("start insert fill ....");
23   - if (metaObject.hasGetter("garCreateTime")){
  23 + if (metaObject.hasGetter("garCreateTime")) {
24 24 this.strictInsertFill(metaObject, "garCreateTime", Date.class, new Date());
25 25 }
26 26  
27   - if (metaObject.hasGetter("garCreateBy")){
28   - if (!Objects.isNull(SecurityUtil.getUserCustom())){
29   - this.strictInsertFill(metaObject, "garCreateBy", String.class, SecurityUtil.getUserCustom().getUser().getGarUserId());
30   - }
  27 + if (metaObject.hasGetter("garCreateBy")) {
  28 + this.strictInsertFill(metaObject, "garCreateBy", String.class, SecurityUtils.getLoginUser().getUser().getUserId());
31 29 }
32 30  
33   - if (metaObject.hasGetter("garUpdateTime")){
  31 + if (metaObject.hasGetter("garUpdateTime")) {
34 32 this.strictInsertFill(metaObject, "garUpdateTime", Date.class, new Date());
35 33 }
36   - if (metaObject.hasGetter("garUserId")){
37   - if (!Objects.isNull(SecurityUtil.getUserCustom())) {
38   - this.strictInsertFill(metaObject, "garUserId", String.class, SecurityUtil.getUserCustom().getUser().getGarUserId());
39   - }
  34 + if (metaObject.hasGetter("garUserId")) {
  35 + this.strictInsertFill(metaObject, "garUserId", String.class, SecurityUtils.getLoginUser().getUser().getUserId());
40 36 }
41   - if (metaObject.hasGetter("garUpdateBy")){
42   - if (!Objects.isNull(SecurityUtil.getUserCustom())){
43   - this.strictInsertFill(metaObject, "garUpdateBy", String.class, SecurityUtil.getUserCustom().getUser().getGarUserId());
44   - }
  37 + if (metaObject.hasGetter("garUpdateBy")) {
  38 + this.strictInsertFill(metaObject, "garUpdateBy", String.class, SecurityUtils.getLoginUser().getUser().getUserId());
45 39 }
46 40 }
47 41  
48 42 @Override
49 43 public void updateFill(MetaObject metaObject) {
50 44 log.info("start update fill ....");
51   - if (metaObject.hasGetter("garUpdateTime")){
  45 + if (metaObject.hasGetter("garUpdateTime")) {
52 46 this.strictUpdateFill(metaObject, "garUpdateTime", Date.class, new Date());
53 47 }
54   - if (metaObject.hasGetter("garUpdateBy")){
55   - this.strictUpdateFill(metaObject,"garUpdateBy",String.class,SecurityUtil.getUserCustom().getUser().getGarUserId());
  48 + if (metaObject.hasGetter("garUpdateBy")) {
  49 + this.strictUpdateFill(metaObject, "garUpdateBy", String.class, SecurityUtils.getLoginUser().getUser().getUserId());
56 50 }
57 51 }
58 52 }
59 53 \ No newline at end of file
... ...
trash-garbage/src/main/java/com/trash/garbage/interfaces/Authorization.java deleted 100644 → 0
1   -package com.trash.garbage.interfaces;
2   -
3   -/**
4   - * 请求头规范
5   - * @date 2023-3-21
6   - * @author 20412
7   - */
8   -public interface Authorization {
9   - String AUTHORIZATION = "Authorization";
10   -
11   - /**
12   - * 这个已经被淘汰,请使用AUTHORIZATION
13   - */
14   - @Deprecated
15   - String TOKEN = "X-TOKEN-AUTH";
16   -}
trash-garbage/src/main/java/com/trash/garbage/pojo/domain/GarUser.java
... ... @@ -8,7 +8,6 @@ import java.io.Serializable;
8 8 import java.util.Date;
9 9  
10 10 import com.fasterxml.jackson.annotation.JsonFormat;
11   -import com.trash.garbage.security.UserAbstract;
12 11 import lombok.Data;
13 12  
14 13 /**
... ... @@ -17,7 +16,7 @@ import lombok.Data;
17 16 */
18 17 @TableName(value ="gar_user")
19 18 @Data
20   -public class GarUser extends UserAbstract implements Serializable {
  19 +public class GarUser implements Serializable {
21 20 /**
22 21 * 建筑垃圾用户id
23 22 */
... ... @@ -131,8 +130,4 @@ public class GarUser extends UserAbstract implements Serializable {
131 130 return sb.toString();
132 131 }
133 132  
134   - @Override
135   - public String getTel() {
136   - return this.garUserTel;
137   - }
138 133 }
139 134 \ No newline at end of file
... ...
trash-garbage/src/main/java/com/trash/garbage/pojo/dto/LoginDto.java
1 1 package com.trash.garbage.pojo.dto;
2 2  
3   -import io.swagger.annotations.ApiModel;
4   -import io.swagger.annotations.ApiModelProperty;
5 3 import lombok.Data;
6 4  
7 5 /**
8 6 * @author 20412
9 7 */
10 8 @Data
11   -@ApiModel(value = "登录vo")
12 9 public class LoginDto {
13   - @ApiModelProperty(value = "登录vo-手机号")
14 10 private String tel;
15   - @ApiModelProperty(value = "登录vo-验证码")
16 11 private String code;
17   - @ApiModelProperty(value = "登录vo-用户昵称")
18 12 private String nickname;
19   - @ApiModelProperty(value = "登录vo-wxCode")
20 13 private String wxCode;
21   - @ApiModelProperty(value = "登录vo-loginType:0 手机号登录 , 1 微信登录")
22 14 private Integer loginType;
23 15 private String encryptedData;
24 16 private String iv;
... ...
trash-garbage/src/main/java/com/trash/garbage/security/JwtAuthenticationFilterAbstract.java deleted 100644 → 0
1   -package com.trash.garbage.security;
2   -
3   -import org.springframework.web.filter.OncePerRequestFilter;
4   -
5   -
6   -
7   -/**
8   - * 使用抽象类
9   - * 因为不同的调用者可能需要的过滤不一样
10   - * 由调用者自己实现
11   - * @author 20412
12   - */
13   -public abstract class JwtAuthenticationFilterAbstract extends OncePerRequestFilter {
14   -
15   -}
trash-garbage/src/main/java/com/trash/garbage/security/PasswordCustom.java deleted 100644 → 0
1   -package com.trash.garbage.security;
2   -
3   -import org.springframework.security.crypto.password.PasswordEncoder;
4   -import org.springframework.stereotype.Component;
5   -import org.springframework.util.DigestUtils;
6   -
7   -/**
8   - * @author 20412
9   - */
10   -@Component
11   -public class PasswordCustom implements PasswordEncoder {
12   -
13   - /** 密码加密 */
14   - @Override
15   - public String encode(CharSequence charSequence) {
16   - return "";
17   - }
18   -
19   - /** 密码配对 用户登录的密码加密后是否配对上 */
20   - @Override
21   - public boolean matches(CharSequence rawPassword, String password) {
22   - return true;
23   - }
24   -}
trash-garbage/src/main/java/com/trash/garbage/security/UserAbstract.java deleted 100644 → 0
1   -package com.trash.garbage.security;
2   -
3   -/**
4   - * 封装用户信息必须实现一下模板
5   - * @author guzijian
6   - */
7   -public abstract class UserAbstract {
8   -
9   - /**
10   - * 可选属性 根据需要设置
11   - */
12   - String garUserId;
13   -
14   - /**
15   - * 实现获取用手机号
16   - * @return
17   - */
18   - public abstract String getTel();
19   -
20   - public String getGarUserId(){
21   - return this.garUserId;
22   - }
23   -
24   -}
trash-garbage/src/main/java/com/trash/garbage/security/UserCustom.java deleted 100644 → 0
1   -package com.trash.garbage.security;
2   -
3   -import com.alibaba.fastjson.annotation.JSONField;
4   -import lombok.Data;
5   -import lombok.NoArgsConstructor;
6   -import org.springframework.security.core.GrantedAuthority;
7   -import org.springframework.security.core.authority.SimpleGrantedAuthority;
8   -import org.springframework.security.core.userdetails.UserDetails;
9   -import java.io.Serializable;
10   -import java.util.Collection;
11   -import java.util.List;
12   -import java.util.stream.Collectors;
13   -
14   -/**
15   - * @author 20412
16   - */
17   -@Data
18   -@NoArgsConstructor
19   -public class UserCustom implements Serializable , UserDetails {
20   -
21   - private static final long serialVersionUID = -2L;
22   -
23   - /**
24   - * 用户实体
25   - */
26   - private UserAbstract user;
27   -
28   - /**
29   - * 权限集合
30   - */
31   - private List<String> permissions;
32   - @JSONField(serialize = false)
33   - private Collection<? extends GrantedAuthority> authorities;
34   -
35   - /**
36   - * 初始化构造
37   - * @param user 用户实体
38   - * @param permissions 权限集合
39   - */
40   - public UserCustom(UserAbstract user, List<String> permissions) {
41   - this.user = user;
42   - this.permissions = permissions;
43   - }
44   -
45   - public UserAbstract getUser() {
46   - return this.user;
47   - }
48   -
49   - @Override
50   - public Collection<? extends GrantedAuthority> getAuthorities() {
51   - if (authorities != null){
52   - return authorities;
53   - }
54   -
55   - authorities = permissions.stream()
56   - .map(SimpleGrantedAuthority::new)
57   - .collect(Collectors.toList());
58   -
59   - return this.authorities;
60   - }
61   -
62   - @Override
63   - public String getPassword() {
64   - return this.user.getTel();
65   - }
66   -
67   - @Override
68   - public String getUsername() {
69   - return this.user.getTel();
70   - }
71   -
72   - @Override
73   - public boolean isAccountNonExpired() {
74   - return true;
75   - }
76   -
77   - @Override
78   - public boolean isAccountNonLocked() {
79   - return true;
80   - }
81   -
82   - @Override
83   - public boolean isCredentialsNonExpired() {
84   - return true;
85   - }
86   -
87   - @Override
88   - public boolean isEnabled() {
89   - return true;
90   - }
91   -}
trash-garbage/src/main/java/com/trash/garbage/service/impl/GarUserServiceImpl.java
... ... @@ -4,8 +4,15 @@ import cn.hutool.http.HttpUtil;
4 4 import com.alibaba.fastjson.JSONObject;
5 5 import com.aliyuncs.exceptions.ClientException;
6 6 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  7 +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
7 8 import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
8 9 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  10 +import com.trash.common.core.domain.entity.SysRole;
  11 +import com.trash.common.core.domain.entity.SysUser;
  12 +import com.trash.common.core.domain.model.LoginUser;
  13 +import com.trash.common.core.redis.RedisCache;
  14 +import com.trash.common.utils.SecurityUtils;
  15 +import com.trash.framework.web.service.TokenService;
9 16 import com.trash.garbage.config.WxConfig;
10 17 import com.trash.garbage.custom.BizException;
11 18 import com.trash.garbage.global.GlobalRedisProperties;
... ... @@ -15,7 +22,6 @@ import com.trash.garbage.pojo.domain.GarAddress;
15 22 import com.trash.garbage.pojo.domain.GarUser;
16 23 import com.trash.garbage.pojo.dto.AddressDto;
17 24 import com.trash.garbage.pojo.dto.LoginDto;
18   -import com.trash.garbage.security.UserCustom;
19 25 import com.trash.garbage.service.GarAddressService;
20 26 import com.trash.garbage.service.GarUserService;
21 27 import com.trash.garbage.mapper.GarUserMapper;
... ... @@ -23,8 +29,7 @@ import com.trash.garbage.utils.*;
23 29 import org.apache.commons.codec.binary.Base64;
24 30 import org.springframework.beans.factory.annotation.Autowired;
25 31 import org.springframework.security.authentication.AuthenticationManager;
26   -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
27   -import org.springframework.security.core.Authentication;
  32 +import org.springframework.security.core.authority.SimpleGrantedAuthority;
28 33 import org.springframework.security.core.userdetails.UsernameNotFoundException;
29 34 import org.springframework.stereotype.Service;
30 35 import org.springframework.transaction.annotation.Transactional;
... ... @@ -34,10 +39,7 @@ import javax.crypto.Cipher;
34 39 import javax.crypto.spec.IvParameterSpec;
35 40 import javax.crypto.spec.SecretKeySpec;
36 41 import java.security.spec.AlgorithmParameterSpec;
37   -import java.util.ArrayList;
38   -import java.util.Arrays;
39   -import java.util.List;
40   -import java.util.Objects;
  42 +import java.util.*;
41 43 import java.util.concurrent.TimeUnit;
42 44  
43 45 /**
... ... @@ -51,50 +53,75 @@ public class GarUserServiceImpl extends ServiceImpl&lt;GarUserMapper, GarUser&gt;
51 53 implements GarUserService {
52 54 @Resource
53 55 private WxConfig wxConfig;
54   - @Autowired
55   - private AuthenticationManager authenticationManager;
56 56  
57 57 @Autowired
58 58 private GarAddressService garAddressService;
59 59  
  60 +
60 61 @Resource
61   - private RedisUtils redisUtils;
  62 + private RedisCache redisCache;
  63 +
  64 + @Autowired
  65 + private TokenService tokenService;
62 66  
63 67  
64 68 @Override
65   - public String login(LoginDto user) {
66   - if (Objects.isNull(user)) {
67   - throw new UsernameNotFoundException("当前用户不存在");
  69 + public String login(LoginDto loginDto) {
  70 + if (Objects.isNull(loginDto)) {
  71 + throw new UsernameNotFoundException("当前用户不存在!");
68 72 }
69 73 // TODO 微信登录
70   - if (user.getLoginType().equals(GlobalStatus.UserStatusEnum.WX_LOGIN.getStatus())) {
71   - String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxConfig.getAppId() + "&secret=" + wxConfig.getSecret() + "&js_code=" + user.getWxCode() + "&grant_type=authorization_code";
  74 + if (loginDto.getLoginType().equals(GlobalStatus.UserStatusEnum.WX_LOGIN.getStatus())) {
  75 + String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxConfig.getAppId() + "&secret=" + wxConfig.getSecret() + "&js_code=" + loginDto.getWxCode() + "&grant_type=authorization_code";
72 76 String body = HttpUtil.createGet(url).header("cache-control", "no-cache").execute().body();
73 77 JSONObject open = JSONObject.parseObject(body);
74 78 String sessionKey = open.getString("session_key");
75 79 try {
76   - user.setTel(decrypt(user.getEncryptedData(), sessionKey, user.getIv()));
  80 + loginDto.setTel(decrypt(loginDto.getEncryptedData(), sessionKey, loginDto.getIv()));
77 81 } catch (Exception e) {
78 82 throw new RuntimeException("解密失败");
79 83 }
80 84 }
81 85 // 验证码验证
82   - String code = (String) redisUtils.get(GlobalRedisProperties.REDIS_USER_CODE.getValue() + user.getTel());
83   - if (user.getCode() == null || !user.getCode().equals(code)) {
  86 + String code = redisCache.getCacheObject(GlobalRedisProperties.REDIS_USER_CODE.getValue() + loginDto.getTel());
  87 + if (loginDto.getCode() == null || !loginDto.getCode().equals(code)) {
84 88 throw new BizException(ResultCode.CODE_400, "验证码错误!!");
85 89 }
86   - // 封装成authentication对象
87   - Authentication authentication = new UsernamePasswordAuthenticationToken(user.getTel(), "");
88   - // 开始认证
89   - Authentication authenticate = authenticationManager.authenticate(authentication);
90   - if (Objects.isNull(authenticate)) {
91   - throw new RuntimeException("用户名或密码错误");
  90 + // 查询用户
  91 + QueryWrapper<GarUser> qw = new QueryWrapper<>();
  92 + qw.lambda().eq(GarUser::getGarUserTel, loginDto.getTel());
  93 + GarUser nUser = this.getOne(qw);
  94 + if (Objects.isNull(nUser)) {
  95 + // 不存在就创建用户
  96 + nUser = new GarUser();
  97 + nUser.setGarUserTel(loginDto.getTel());
  98 + nUser.setGarUserDelFlag(GlobalStatus.DEL_FLAG_NO);
  99 + nUser.setGarUserType(GlobalStatus.UserStatusEnum.NORMAL_USER.getDescription());
  100 + this.save(nUser);
  101 + }
  102 + LoginUser loginUser = new LoginUser();
  103 + ArrayList<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
  104 + loginUser.setAuthorities(authorities);
  105 + Set<String> set = new HashSet<String>();
  106 + SysUser user = new SysUser();
  107 + user.setUserId(nUser.getGarUserId());
  108 + user.setUserName(nUser.getGarUserName());
  109 + user.setPhonenumber(loginDto.getTel());
  110 + loginUser.setUser(user);
  111 + set.add("*:*:*");
  112 + SysRole role = new SysRole();
  113 + role.setRoleKey("admin");
  114 + ArrayList<SysRole> roles = new ArrayList<SysRole>();
  115 + roles.add(role);
  116 + user.setRoles(roles);
  117 + loginUser.setPermissions(set);
  118 + String token = JwtUtils.createToken(nUser.getGarUserId(), nUser.getGarUserTel());
  119 + if (!token.contains("Bearer ")) {
  120 + token = "Bearer " + token;
92 121 }
93   - UserCustom userCustom = (UserCustom) authenticate.getPrincipal();
94   - // 存入redis
95   - redisUtils.set(GlobalRedisProperties.REDIS_USER_HEADER.getValue() + userCustom.getUser().getGarUserId(), userCustom);
96   - // 修改在线状态
97   - return JwtUtils.createToken(userCustom.getUser().getTel(), userCustom.getUser().getGarUserId());
  122 + loginUser.setToken(token);
  123 + tokenService.refreshToken(loginUser);
  124 + return token;
98 125 }
99 126  
100 127 @Override
... ... @@ -105,16 +132,13 @@ public class GarUserServiceImpl extends ServiceImpl&lt;GarUserMapper, GarUser&gt;
105 132 // SMSUtils.sendMessage("", tel, validateCode.toString(), "");
106 133 // 保存redis
107 134 System.out.println("code:" + validateCode);
108   - redisUtils.setEx(GlobalRedisProperties.REDIS_USER_CODE.getValue() + tel, validateCode, 60, TimeUnit.SECONDS);
  135 + redisCache.setCacheObject(GlobalRedisProperties.REDIS_USER_CODE.getValue() + tel, validateCode, 60, TimeUnit.SECONDS);
109 136 }
110 137  
111 138 @Override
112 139 public List<GarAddress> queryAddress(String type) {
113   - UserCustom userCustom = SecurityUtil.getUserCustom();
114   - if (Objects.isNull(userCustom)) {
115   - throw new BizException(ResultCode.CODE_401, ResultCode.CODE_401.getMsg());
116   - }
117   - String garUserId = userCustom.getUser().getGarUserId();
  140 + LoginUser user = SecurityUtils.getLoginUser();
  141 + String garUserId = user.getUser().getUserId();
118 142 LambdaQueryWrapper<GarAddress> qw = new LambdaQueryWrapper<>();
119 143 qw.eq(GarAddress::getGarUserId, garUserId);
120 144 if (GlobalStatus.QUERY_ADDRESS_TYPE_CURRENT.equals(type)) {
... ... @@ -127,16 +151,16 @@ public class GarUserServiceImpl extends ServiceImpl&lt;GarUserMapper, GarUser&gt;
127 151  
128 152 @Override
129 153 public String saveAddress(AddressDto dto) {
130   - UserCustom userCustom = SecurityUtil.getUserCustom();
  154 + LoginUser userCustom = SecurityUtils.getLoginUser();
131 155 // 限制地址数
132 156 LambdaQueryWrapper<GarAddress> qw = new LambdaQueryWrapper<>();
133   - qw.eq(GarAddress::getGarUserId, userCustom.getUser().getGarUserId());
  157 + qw.eq(GarAddress::getGarUserId, userCustom.getUser().getUserId());
134 158 List<GarAddress> list = garAddressService.list(qw);
135 159 if (list.size() > 19) {
136 160 throw new BizException(ResultCode.CODE_201, "新增地址数已达上线,请删除地址后新增地址或编辑已有地址!");
137 161 }
138 162 GarAddress address = new GarAddress();
139   - address.setGarUserId(userCustom.getUser().getGarUserId());
  163 + address.setGarUserId(userCustom.getUser().getUserId());
140 164 address.setGarUserAddress(dto.getAddressArea());
141 165 address.setGarUserDefault(dto.getDefaultFlag() ? GlobalStatus.GarAddressStatus.CURRENT_ADDRESS.getValue() : GlobalStatus.GarAddressStatus.NORMAL_ADDRESS.getValue());
142 166 address.setGarUserContactName(dto.getContactPerson());
... ... @@ -150,7 +174,7 @@ public class GarUserServiceImpl extends ServiceImpl&lt;GarUserMapper, GarUser&gt;
150 174 @Override
151 175 public String updateAddress(AddressDto dto) {
152 176 GarAddress address = new GarAddress();
153   - String userId = SecurityUtil.getUserCustom().getUser().getGarUserId();
  177 + String userId = SecurityUtils.getLoginUser().getUser().getUserId();
154 178 address.setGarAddressId(dto.getGarAddressId());
155 179 address.setGarUserId(userId);
156 180 address.setGarUserAddress(dto.getAddressArea());
... ... @@ -177,7 +201,7 @@ public class GarUserServiceImpl extends ServiceImpl&lt;GarUserMapper, GarUser&gt;
177 201  
178 202 @Override
179 203 public String deleteAddress(String addressId) {
180   - String garUserId = SecurityUtil.getUserCustom().getUser().getGarUserId();
  204 + String garUserId = SecurityUtils.getLoginUser().getUser().getUserId();
181 205 LambdaQueryWrapper<GarAddress> qw = new LambdaQueryWrapper<>();
182 206 qw.eq(GarAddress::getGarUserId, garUserId)
183 207 .eq(GarAddress::getGarAddressId, addressId);
... ...
trash-garbage/src/main/java/com/trash/garbage/service/impl/UserDetailServiceImpl.java deleted 100644 → 0
1   -package com.trash.garbage.service.impl;
2   -
3   -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
4   -import com.trash.garbage.global.GlobalStatus;
5   -import com.trash.garbage.pojo.domain.GarUser;
6   -import com.trash.garbage.security.UserCustom;
7   -import com.trash.garbage.service.GarUserService;
8   -import org.springframework.beans.factory.annotation.Autowired;
9   -import org.springframework.security.core.userdetails.UserDetails;
10   -import org.springframework.security.core.userdetails.UserDetailsService;
11   -import org.springframework.security.core.userdetails.UsernameNotFoundException;
12   -import org.springframework.stereotype.Component;
13   -
14   -import java.util.Collections;
15   -import java.util.Objects;
16   -
17   -/**
18   - * 用户信息实现类
19   - * @author 20412
20   - */
21   -@Component
22   -public class UserDetailServiceImpl implements UserDetailsService {
23   -
24   - @Autowired
25   - private GarUserService userService;
26   -
27   - /** 查询数据库中的数据是否配对上 */
28   - @Override
29   - public UserDetails loadUserByUsername(String tel) throws UsernameNotFoundException {
30   - // 查表是否有对应的tel
31   - QueryWrapper<GarUser> qw = new QueryWrapper<>();
32   - qw.lambda().eq(GarUser::getGarUserTel, tel);
33   - GarUser user = userService.getOne(qw);
34   - if (Objects.isNull(user)) {
35   - // 不存在就创建用户
36   - GarUser nUser = new GarUser();
37   - nUser.setGarUserTel(tel);
38   - nUser.setGarUserDelFlag(GlobalStatus.DEL_FLAG_NO);
39   - nUser.setGarUserType("iphone");
40   - if (userService.save(nUser)) {
41   - return new UserCustom(nUser, Collections.emptyList());
42   - }
43   - }
44   - // 第二参数是控制权限 普通用户无需角色认证
45   - return new UserCustom(user, Collections.emptyList());
46   - }
47   -}
trash-garbage/src/main/java/com/trash/garbage/utils/FastJson2JsonRedisSerializer.java deleted 100644 → 0
1   -package com.trash.garbage.utils;
2   -
3   -import com.alibaba.fastjson.JSON;
4   -import com.alibaba.fastjson.parser.ParserConfig;
5   -import com.alibaba.fastjson.serializer.SerializerFeature;
6   -import com.fasterxml.jackson.databind.JavaType;
7   -import com.fasterxml.jackson.databind.ObjectMapper;
8   -import com.fasterxml.jackson.databind.type.TypeFactory;
9   -import org.springframework.data.redis.serializer.RedisSerializer;
10   -import org.springframework.data.redis.serializer.SerializationException;
11   -import org.springframework.util.Assert;
12   -
13   -import java.nio.charset.Charset;
14   -/**
15   - * FastJson2JsonRedisSerializer
16   - * Redis使用FastJson序列化
17   - */
18   -public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
19   - private ObjectMapper objectMapper = new ObjectMapper();
20   - public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
21   -
22   - private Class<T> clazz;
23   -
24   - static {
25   - ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
26   - //如果遇到反序列化autoType is not support错误,请添加并修改一下包名到bean文件路径
27   - // ParserConfig.getGlobalInstance().addAccept("com.xxxxx.xxx");
28   - }
29   - public FastJson2JsonRedisSerializer(Class<T> clazz) {
30   - super();
31   - this.clazz = clazz;
32   - }
33   -
34   - public byte[] serialize(T t) throws SerializationException {
35   - if (t == null) {
36   - return new byte[0];
37   - }
38   - return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
39   - }
40   -
41   - public T deserialize(byte[] bytes) throws SerializationException {
42   - if (bytes == null || bytes.length <= 0) {
43   - return null;
44   - }
45   - String str = new String(bytes, DEFAULT_CHARSET);
46   -
47   - return JSON.parseObject(str, clazz);
48   - }
49   - public void setObjectMapper(ObjectMapper objectMapper) {
50   - Assert.notNull(objectMapper, "'objectMapper' must not be null");
51   - this.objectMapper = objectMapper;
52   - }
53   -
54   - protected JavaType getJavaType(Class<?> clazz) {
55   - return TypeFactory.defaultInstance().constructType(clazz);
56   - }
57   -
58   -}
trash-garbage/src/main/java/com/trash/garbage/utils/JsonUtil.java deleted 100644 → 0
1   -package com.trash.garbage.utils;
2   -
3   -import cn.hutool.core.bean.BeanUtil;
4   -import com.alibaba.fastjson.JSON;
5   -import com.alibaba.fastjson.JSONObject;
6   -import org.slf4j.Logger;
7   -import org.slf4j.LoggerFactory;
8   -
9   -
10   -/**
11   - * @Author : guzijian
12   - * @Description :
13   - **/
14   -public final class JsonUtil {
15   - static Logger log = LoggerFactory.getLogger(JsonUtil.class) ;
16   - /**
17   - * 把Java对象转换成json字符串
18   - *
19   - * @param object 待转化为JSON字符串的Java对象
20   - * @return json 串 or null
21   - */
22   - public static String parseObjToJson(Object object) {
23   - String string = null;
24   - try {
25   - string = JSONObject.toJSONString(object);
26   - } catch (Exception e) {
27   - log.info("把Java对象转换成json字符串转换异常:{}",e.getMessage());
28   - }
29   - return string;
30   - }
31   -
32   - /**
33   - * 将Json字符串信息转换成对应的Java对象
34   - *
35   - * @param json json字符串对象
36   - * @param c 对应的类型
37   - */
38   - public static <T> T parseJsonToObj(String json, Class<T> c) {
39   - try {
40   - JSONObject jsonObject = JSON.parseObject(json);
41   - return JSON.toJavaObject(jsonObject, c);
42   - } catch (Exception e) {
43   - log.info("将Json字符串信息转换成对应的Java对象转换异常:{}",e.getMessage());
44   - return null;
45   - }
46   - }
47   -
48   - public static <T> T parseObjToObj(Object obj,Class<T> clazz){
49   - try {
50   - return BeanUtil.toBean(obj, clazz);
51   - }catch (Exception e){
52   - log.info("将Json字符串信息转换成对应的Java对象转换异常:{}",e.getMessage());
53   - }
54   - return null;
55   - }
56   -}
57 0 \ No newline at end of file
trash-garbage/src/main/java/com/trash/garbage/utils/JwtUtils.java
... ... @@ -19,15 +19,15 @@ public class JwtUtils {
19 19 private final static String tokenSecret = "guzijian";
20 20  
21 21 /** 创建token */
22   - public static String createToken(String username, String userId) {
  22 + public static String createToken(String id, String tel) {
23 23 String token = Jwts.builder()
24 24 // 说明
25 25 .setSubject("AUTH-USER")
26 26 // 过期时间
27 27 .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
28 28 // 加入认证信息
29   - .claim("userId",userId)
30   - .claim("username",username)
  29 + .claim("tel",tel)
  30 + .claim("userId",id)
31 31 // 加密方式 jwt 密钥方便解密
32 32 .signWith(SignatureAlgorithm.HS256, tokenSecret)
33 33 // 压缩方式
... ...
trash-garbage/src/main/java/com/trash/garbage/utils/RedisUtils.java
1 1 package com.trash.garbage.utils;
2 2  
3   -import cn.hutool.core.bean.BeanUtil;
4 3 import org.springframework.beans.factory.annotation.Autowired;
5 4 import org.springframework.data.redis.core.RedisTemplate;
6 5 import org.springframework.stereotype.Component;
... ... @@ -25,10 +24,6 @@ public class RedisUtils {
25 24 return redisTemplate.opsForValue().get(key);
26 25 }
27 26  
28   - public <T> T get(String key,Class<T> clazz){
29   - return BeanUtil.toBean(redisTemplate.opsForValue().get(key), clazz);
30   - }
31   -
32 27 public boolean setNxAndEx(String key,String value,long expireTime){
33 28 return redisTemplate.opsForValue().setIfAbsent(key,value,expireTime, TimeUnit.SECONDS);
34 29 }
... ...
trash-garbage/src/main/java/com/trash/garbage/utils/SecurityUtil.java deleted 100644 → 0
1   -package com.trash.garbage.utils;
2   -
3   -import com.trash.garbage.custom.BizException;
4   -import com.trash.garbage.global.ResultCode;
5   -import com.trash.garbage.security.UserCustom;
6   -import org.springframework.security.core.context.SecurityContextHolder;
7   -
8   -/**
9   - * @author 20412
10   - */
11   -public class SecurityUtil {
12   -
13   -
14   - public static UserCustom getUserCustom() {
15   - if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof UserCustom)
16   - return (UserCustom) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
17   - throw new BizException(ResultCode.CODE_401, ResultCode.CODE_401.getMsg());
18   - }
19   -}
trash-garbage/src/main/resources/application-dev.yml deleted 100644 → 0
1   -spring:
2   - datasource:
3   - type: com.alibaba.druid.pool.DruidDataSource
4   - driverClassName: com.mysql.cj.jdbc.Driver
5   - druid:
6   - # 主库数据源
7   - url: jdbc:mysql://localhost:3306/trash?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&useAffectedRows=true&allowMultiQueries=true
8   - username: root
9   - password: guzijian
10   - # 初始连接数
11   - initialSize: 5
12   - # 最小连接池数量
13   - minIdle: 10
14   - # 最大连接池数量
15   - maxActive: 20
16   - # 配置获取连接等待超时的时间
17   - maxWait: 60000
18   - # 配置连接超时时间
19   - connectTimeout: 30000
20   - # 配置网络超时时间
21   - socketTimeout: 60000
22   - # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
23   - timeBetweenEvictionRunsMillis: 60000
24   - # 配置一个连接在池中最小生存的时间,单位是毫秒
25   - minEvictableIdleTimeMillis: 300000
26   - # 配置一个连接在池中最大生存的时间,单位是毫秒
27   - maxEvictableIdleTimeMillis: 900000
28   - # 配置检测连接是否有效
29   - validationQuery: SELECT 1 FROM DUAL
30   - testWhileIdle: true
31   - testOnBorrow: false
32   - testOnReturn: false
33   - webStatFilter:
34   - enabled: true
35   - statViewServlet:
36   - enabled: true
37   - # 设置白名单,不填则允许所有访问
38   - allow:
39   - url-pattern: /druid/*
40   - # 控制台管理用户名和密码
41   - login-username: ruoyi
42   - login-password: 123456
43   - filter:
44   - stat:
45   - enabled: true
46   - # 慢SQL记录
47   - log-slow-sql: true
48   - slow-sql-millis: 1000
49   - merge-sql: true
50   - wall:
51   - config:
52   - multi-statement-allow: true
53   - redis:
54   - # 地址
55   -# host: 121.41.83.61
56   -# host: 192.168.172.221
57   - host: 127.0.0.1
58   - database: 0
59   - # password: "guzijian"
60   - port: 6379
61   - # 连接超时时间
62   - timeout: 10s
63   - lettuce:
64   - pool:
65   - # 连接池中的最小空闲连接
66   - min-idle: 0
67   - # 连接池中的最大空闲连接
68   - max-idle: 8
69   - # 连接池的最大数据库连接数
70   - max-active: 8
71   - # #连接池最大阻塞等待时间(使用负值表示没有限制)
72   - max-wait: -1ms
73   - #返回json的全局时间格式
74   - jackson:
75   - date-format: yyyy-MM-dd HH:mm:ss
76   - time-zone: GMT+8
77   -
78   -# mybaits 配置
79   -mybatis-plus:
80   - global-config:
81   - # 指定逻辑删除含义
82   - db-config:
83   - logic-delete-value: 1
84   - logic-not-delete-value: 0
85   - configuration:
86   - # 日志打印sql
87   - log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
88   -
89   -trash:
90   - garbage:
91   - config:
92   - location:
93   - # security 放行路径
94   - exclude: /user/login,/user/send/verify,/user/sendCode/**,/doc.html,/swagger-ui.html,/swagger-ui/**,/swagger-resources/**,/v2/api-docs,/v3/api-docs,/webjars/**,/ws/**
95   -
96   -wx:
97   - appId: 'wxc3f60667dc9d6cea'
98   - secret: 'd35996a9f898dff37974efba0b6f23ed'
99 0 \ No newline at end of file
trash-garbage/src/main/resources/application.yml
1   -server:
2   - servlet:
3   - context-path:
4   - port: 9090
5   -spring:
6   - profiles:
7   - active: dev
8 1 \ No newline at end of file
  2 +# mybaits 配置
  3 +mybatis-plus:
  4 + global-config:
  5 + # 指定逻辑删除含义
  6 + db-config:
  7 + logic-delete-value: 1
  8 + logic-not-delete-value: 0
  9 + configuration:
  10 + # 日志打印sql
  11 + log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
9 12 \ No newline at end of file
... ...