Explorar el Código

健康信息和图片接口对外访问修改

yinhao hace 4 años
padre
commit
14694a360a

+ 0 - 1
huimv-smart-apiservice/src/main/java/com/huimv/apiservice/HuimvSmartApiserviceApplication.java

@@ -13,7 +13,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
 public class HuimvSmartApiserviceApplication {
 
     public static void main(String[] args) {
-//        System.setProperty("tomcat.util.http.parser.HttpParser.requestTargetAllow","|{}");
         SpringApplication.run(HuimvSmartApiserviceApplication.class, args);
     }
 

+ 4 - 6
huimv-smart-apiservice/src/main/java/com/huimv/apiservice/MathTestMain.java

@@ -1,12 +1,10 @@
 package com.huimv.apiservice;
 
 /**
- * @Project : huimv.shiwan
- * @Package : com.huimv.apiservice
- * @Description : TODO
- * @Author : yuxuexuan
- * @Create : 2021/5/11 0011 10:00
- **/
+ * main for test
+ *
+ * @author yinhao
+ */
 public class MathTestMain {
 
     public static void main(String[] args) {

+ 39 - 0
huimv-smart-apiservice/src/main/java/com/huimv/apiservice/config/InterceptorConfig.java

@@ -0,0 +1,39 @@
+package com.huimv.apiservice.config;
+
+import com.huimv.apiservice.interceptor.JWTInterceptor;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+/**
+ * 注册验证token的拦截器
+ * @author yinhap
+ * @date 2021/4/19 20:41
+ * @version V1.0
+ */
+@Configuration
+public class InterceptorConfig implements WebMvcConfigurer {
+    @Bean
+    public JWTInterceptor jwtInterceptor(){
+        return new JWTInterceptor();
+    }
+
+    @Override
+    public void addInterceptors(InterceptorRegistry registry) {
+        registry.addInterceptor(jwtInterceptor()).
+                excludePathPatterns("/getToken").
+                excludePathPatterns("/login").
+                excludePathPatterns("/logout").
+                excludePathPatterns("/captcha/send").
+                excludePathPatterns("/swagger-resources/**").
+                excludePathPatterns("/").
+                excludePathPatterns("/*.ico").
+                excludePathPatterns("/js/**").
+                excludePathPatterns("/img/**").
+                excludePathPatterns("/css/**").
+                excludePathPatterns("/druid/**").
+                excludePathPatterns("/doc.html").
+                addPathPatterns("/**");
+    }
+}

+ 16 - 18
huimv-smart-apiservice/src/main/java/com/huimv/apiservice/controller/PigController.java

@@ -6,10 +6,7 @@ import com.huimv.apiservice.limit.annotation.Limit;
 import com.huimv.apiservice.service.PigService;
 import com.huimv.common.utils.R;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.CrossOrigin;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
 
 import java.util.List;
 import java.util.Map;
@@ -29,36 +26,38 @@ public class PigController {
 
     /**
      * 获取猪基本信息
+     *
      * @param accessToken token
      * @param pigEarTagNo 耳标号
      * @return
      */
-    @Limit(key = "pig_getPigInfo",name = "pig/getPigInfo",prefix = "apiservice")
-    @RequestMapping("/getPigInfo")
-    public R getPigInfo(@RequestParam(value = "accessToken", required = false) String accessToken,
+    //@Limit(key = "pig_getPigInfo",name = "pig/getPigInfo",prefix = "apiservice")
+    @GetMapping("/getPigInfo")
+    public R getPigInfo(@RequestParam(value = "accessToken") String accessToken,
                         @RequestParam("pigEarTagNo") String pigEarTagNo) {
         //TODO token校验
-        Map<String,Object> map = pigService.getPigInfoByEarTagNo(pigEarTagNo);
+        Map<String, Object> map = pigService.getPigInfoByEarTagNo(pigEarTagNo);
         return Objects.requireNonNull(R.ok().put("code", 1000)).put("data", map);
     }
 
 
     /**
      * 获取多媒体接口(照片/视频)
+     *
      * @param accessToken token
      * @param pigEarTagNo 耳标号
      * @return
      */
-    @RequestMapping("/getImage")
-    public R getImage(@RequestParam(value = "accessToken", required = false) String accessToken,
+    @GetMapping("/getImage")
+    public R getImage(@RequestParam(value = "accessToken") String accessToken,
                       @RequestParam("pigEarTagNo") String pigEarTagNo) {
         //TODO token校验
         PigImageVo pigImageVo = pigService.getImageByEarTagNo(pigEarTagNo);
         return Objects.requireNonNull(R.ok().put("code", 1000)).put("data", pigImageVo);
     }
 
-    @RequestMapping("/getListByBreed")
-    public R getListByBreed(@RequestParam(value = "accessToken", required = false) String accessToken,
+    @GetMapping("/getListByBreed")
+    public R getListByBreed(@RequestParam(value = "accessToken") String accessToken,
                             @RequestParam("breedName") String breedName) {
         //TODO token校验
         List<PigBaseVo> pigBaseVoList = pigService.getListByBreed(breedName);
@@ -83,7 +82,7 @@ public class PigController {
 
     @RequestMapping("/getIndoorEnv")
     public R getIndoorEnv(@RequestParam(value = "accessToken", required = false) String accessToken,
-                       @RequestParam("pigEarTagNo") String pigEarTagNo) {
+                          @RequestParam("pigEarTagNo") String pigEarTagNo) {
         //TODO token校验
         EnvVo envVo = pigService.getIndoorEnv(pigEarTagNo);
         return Objects.requireNonNull(R.ok().put("code", 1000)).put("data", envVo);
@@ -102,24 +101,23 @@ public class PigController {
     //8.获取当天的睡眠状态数据接⼝
     @RequestMapping("/getSleepStatus")
     public R getSleepStatus(@RequestParam(value = "accessToken", required = false) String accessToken,
-                               @RequestParam("pigEarTagNo") String pigEarTagNo) {
+                            @RequestParam("pigEarTagNo") String pigEarTagNo) {
         //TODO token校验
         SleepStatusEntity sleepStatusEntity = pigService.getSleepStatus(pigEarTagNo);
 
 
-
-        return Objects.requireNonNull(Objects.requireNonNull(R.ok().put("code", 1000)).put("msg", "查询成功")).put("data",sleepStatusEntity );
+        return Objects.requireNonNull(Objects.requireNonNull(R.ok().put("code", 1000)).put("msg", "查询成功")).put("data", sleepStatusEntity);
     }
 
     //9.获取当天的运动数据接⼝
     @RequestMapping("/getActivityAmount")
     public R getActivityAmount(@RequestParam(value = "accessToken", required = false) String accessToken,
-                       @RequestParam("pigEarTagNo") String pigEarTagNo) {
+                               @RequestParam("pigEarTagNo") String pigEarTagNo) {
         //TODO token校验
         PigSportVo pigSportVo = pigService.getActivityAmount(pigEarTagNo);
 
 
-        return Objects.requireNonNull(Objects.requireNonNull(R.ok().put("code", 1000)).put("msg", "查询成功")).put("data",pigSportVo );
+        return Objects.requireNonNull(Objects.requireNonNull(R.ok().put("code", 1000)).put("msg", "查询成功")).put("data", pigSportVo);
     }
 
 }

+ 0 - 1
huimv-smart-apiservice/src/main/java/com/huimv/apiservice/controller/TokenController.java

@@ -3,7 +3,6 @@ package com.huimv.apiservice.controller;
 import cn.hutool.json.JSONObject;
 import com.huimv.common.utils.TokenUtil;
 import org.springframework.beans.factory.annotation.Value;
-import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.RestController;

+ 53 - 0
huimv-smart-apiservice/src/main/java/com/huimv/apiservice/interceptor/JWTInterceptor.java

@@ -0,0 +1,53 @@
+package com.huimv.apiservice.interceptor;
+
+import com.alibaba.fastjson.JSONObject;
+import com.huimv.common.utils.R;
+
+import com.huimv.common.utils.TokenUtil;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.web.method.HandlerMethod;
+import org.springframework.web.servlet.HandlerInterceptor;
+import org.springframework.web.servlet.ModelAndView;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ * <p>
+ *  jwt拦截器
+ * </p>
+ * @author yinhao
+ * @since 2021/4/19
+ */
+
+public class JWTInterceptor implements HandlerInterceptor {
+
+    @Override
+    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
+        // 如果不是映射到方法,则直接通过
+        if (!(handler instanceof HandlerMethod)) {
+            return true;
+        }
+        response.setContentType("application/json;charset=utf-8");
+
+        // 获取token
+        String accessToken = request.getParameter("accessToken");
+
+        if (StringUtils.isEmpty(accessToken) || !TokenUtil.verify(accessToken)) {
+            response.getWriter().write(JSONObject.toJSONString(R.error(1007,"无效令牌,请重新申请!")));
+            return false;
+        }
+        return true;
+    }
+
+
+    @Override
+    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
+
+    }
+
+    @Override
+    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
+
+    }
+}

+ 2 - 2
huimv-smart-apiservice/src/main/java/com/huimv/apiservice/limit/annotation/Limit.java

@@ -9,10 +9,10 @@ import java.lang.annotation.Target;
 
 /**
  * <p>
- * 业务用注解
+ * 业务用注解 接口访问次数限制
  * </p>
  * 示例: @Limit(key = "test_list",name = "test/list",prefix = "management")
- * @author huimv
+ * @author yinhao
  * @since 2021/4/29
  */
 @Target(ElementType.METHOD)

+ 6 - 6
huimv-smart-apiservice/src/main/java/com/huimv/apiservice/service/impl/PigServiceImpl.java

@@ -95,12 +95,12 @@ public class PigServiceImpl extends ServiceImpl<PigDao, YearPigBaseEntity> imple
         //健康状态数据sql构建及查询
         //TODO 健康状态数据库查询
         //模拟数据
-        Map<String, Object> healthData1 = new HashMap<>();
-        healthData1.put(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"), "健康");
-        Map<String, Object> healthData2 = new HashMap<>();
-        healthData2.put(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"), "亚健康");
-        healthStatus.add(healthData1);
-        healthStatus.add(healthData2);
+        //Map<String, Object> healthData1 = new HashMap<>();
+        //healthData1.put(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"), "健康");
+        //Map<String, Object> healthData2 = new HashMap<>();
+        //healthData2.put(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"), "亚健康");
+        //healthStatus.add(healthData1);
+        //healthStatus.add(healthData2);
 
         //采食状态数据sql构建及查询
         LambdaQueryWrapper<EatTimeEntity> eatTimeLambdaQuery = Wrappers.lambdaQuery();

+ 14 - 12
huimv-smart-common/src/main/java/com/huimv/common/utils/TokenUtil.java

@@ -1,11 +1,13 @@
 package com.huimv.common.utils;
 
 
+import cn.hutool.core.date.DateUtil;
 import com.auth0.jwt.JWT;
 import com.auth0.jwt.JWTVerifier;
 import com.auth0.jwt.algorithms.Algorithm;
 import com.auth0.jwt.interfaces.DecodedJWT;
 
+import java.time.format.DateTimeFormatter;
 import java.util.Date;
 
 /**
@@ -17,24 +19,25 @@ import java.util.Date;
  **/
 public class TokenUtil {
 
-    private static final long EXPIRE_TIME = 2*60*60*1000;  //有效时长
+    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;  //有效时长
     private static final String TOKEN_SECRET = "ben";       // 秘钥
 
     /**
      * 签名 生成
+     *
      * @parm userName
-     * */
-    public static String sign(String userName){
+     */
+    public static String sign(String userName) {
         String token = null;
         try {
-            Date expiresAt = new Date(System.currentTimeMillis()+EXPIRE_TIME);
+            Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
             token = JWT.create()
                     .withIssuer("auth0")
-                    .withClaim("userName",userName)
+                    .withClaim("userName", userName)
                     .withExpiresAt(expiresAt)
                     //使用HMAC256算法加密
                     .sign(Algorithm.HMAC256(TOKEN_SECRET));
-        }catch (Exception e){
+        } catch (Exception e) {
             e.printStackTrace();
         }
         return token;
@@ -42,18 +45,17 @@ public class TokenUtil {
 
     /**
      * 签名验证
+     *
      * @param token
-     * */
-    public static boolean verify(String token){
+     */
+    public static boolean verify(String token) {
         try {
             JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET))
                     .withIssuer("auth0").build();
             DecodedJWT jwt = verifier.verify(token);
-            System.out.println("认证通过");
-//            System.out.println("userName:"+jwt.getClaims().toString());
-            System.out.println("过期时间:"+jwt.getExpiresAt());
+            System.out.println("TOKEN过期时间:" + DateUtil.format(jwt.getExpiresAt(), "yyyy-MM-dd HH:mm:ss"));
             return true;
-        }catch (Exception e){
+        } catch (Exception e) {
             return false;
         }
     }

+ 12 - 13
huimv-smart-gateway/src/main/resources/application.yml

@@ -24,9 +24,8 @@ spring:
             - Path=/api/management/**
           filters:
             - RewritePath=/api/management/(?<segment>/?.*), /management/$\{segment}
-
-        - id: admin_route
         # renren-fast后台管理系统的路由(低优先级的放在下面)
+        - id: admin_route
           uri: http://127.0.0.1:9500
           predicates:
             - Path=/api/**
@@ -35,10 +34,10 @@ spring:
 
         - id: apiservice_route
           uri: http://127.0.0.1:9001
+        # apiservice后台接口路由
           predicates:
             - Path=/**
-#          filters:
-#            - RewritePath=/api/apiservice/(?<segment>/?.*), /management/$\{segment}
+
 #      discovery:
 #        locator:
 #          enabled: true                 # 设置为true 请求路径前可以添加微服务名称  http://localhost:88/gateway-provider/goods/findOne/2 -> http://localhost:88/goods/findOne/2
@@ -56,12 +55,12 @@ server:
   port: 88
 
 
-huimv:
-  public-key: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIvJs0JQAJJZ9VYKyo69ByDYzDpCTjyu/bUcw+7SI1PqZtliUYmjUmaQdzKigCjpQH2Sq3x+VSmfnprZhP6COYkCAwEAAQ==
-  # APP模块,是通过jwt认证的,如果要使用APP模块,则需要修改【加密秘钥】
-  jwt:
-    # 加密秘钥
-    secret: f4e2e52034348f86b67cde581c0f9eb5[www.huimv.com]
-    # token有效时长,7天,单位秒
-    expire: 604800
-    header: token
+#huimv:
+#  public-key: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIvJs0JQAJJZ9VYKyo69ByDYzDpCTjyu/bUcw+7SI1PqZtliUYmjUmaQdzKigCjpQH2Sq3x+VSmfnprZhP6COYkCAwEAAQ==
+#  # APP模块,是通过jwt认证的,如果要使用APP模块,则需要修改【加密秘钥】
+#  jwt:
+#    # 加密秘钥
+#    secret: f4e2e52034348f86b67cde581c0f9eb5[www.huimv.com]
+#    # token有效时长,7天,单位秒
+#    expire: 604800
+#    header: token