From ae21439c2efda64252bb442ade1a080b17abe393 Mon Sep 17 00:00:00 2001 From: Saturneric Date: Sun, 22 Mar 2020 17:57:43 +0800 Subject: [PATCH 1/9] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E8=B1=81=E5=85=8D;=E5=BC=80=E5=A7=8B=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E6=9D=83=E9=99=90=E7=AE=A1=E7=90=86=E5=AD=90=E7=B3=BB=E7=BB=9F?= =?UTF-8?q?=E7=9B=B8=E5=85=B3=E6=8E=A5=E5=8F=A3;=E8=B0=83=E6=95=B4?= =?UTF-8?q?=E9=A1=B9=E7=9B=AE=E6=9E=B6=E6=9E=84;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 8 +++---- .../ASEAccessDeniedHandler.java | 2 +- .../ASEAuthenticationEntryPoint.java | 2 +- .../ASEAuthenticationFailureHandler.java | 2 +- .../ASEAuthenticationSuccessHandler.java | 2 +- .../ASEJSONTokenAuthenticationFilter.java | 10 ++++++-- .../ASEPasswordEncoder.java | 2 +- .../ASESecurityAuthenticationProvider.java | 4 +--- .../ASEUsernameEncoder.java | 2 +- ...EUsernamePasswordAuthenticationFilter.java | 6 ++--- .../ase/configure/AppConfigure.java | 1 + .../configure/CustomWebSecurityConfig.java | 6 +---- .../ase/controller/LeavesController.java | 2 +- .../ase/controller/LoginController.java | 4 +--- .../ase/controller/PermissionContainer.java | 23 +++++++++++++++++++ .../codesdream/ase/service/UserService.java | 4 ++-- .../ase/test/PermissionServiceTest.java | 2 ++ 17 files changed, 52 insertions(+), 30 deletions(-) rename src/main/java/com/codesdream/ase/component/{permission => auth}/ASEAccessDeniedHandler.java (95%) rename src/main/java/com/codesdream/ase/component/{permission => auth}/ASEAuthenticationEntryPoint.java (96%) rename src/main/java/com/codesdream/ase/component/{permission => auth}/ASEAuthenticationFailureHandler.java (97%) rename src/main/java/com/codesdream/ase/component/{permission => auth}/ASEAuthenticationSuccessHandler.java (97%) rename src/main/java/com/codesdream/ase/component/{permission => auth}/ASEJSONTokenAuthenticationFilter.java (90%) rename src/main/java/com/codesdream/ase/component/{permission => auth}/ASEPasswordEncoder.java (91%) rename src/main/java/com/codesdream/ase/component/{permission => auth}/ASESecurityAuthenticationProvider.java (93%) rename src/main/java/com/codesdream/ase/component/{permission => auth}/ASEUsernameEncoder.java (89%) rename src/main/java/com/codesdream/ase/component/{permission => auth}/ASEUsernamePasswordAuthenticationFilter.java (93%) create mode 100644 src/main/java/com/codesdream/ase/controller/PermissionContainer.java diff --git a/pom.xml b/pom.xml index a550983..1307c09 100644 --- a/pom.xml +++ b/pom.xml @@ -139,10 +139,10 @@ - org.mariadb.jdbc - mariadb-java-client - 2.5.4 - + org.mariadb.jdbc + mariadb-java-client + 2.5.4 + com.h2database diff --git a/src/main/java/com/codesdream/ase/component/permission/ASEAccessDeniedHandler.java b/src/main/java/com/codesdream/ase/component/auth/ASEAccessDeniedHandler.java similarity index 95% rename from src/main/java/com/codesdream/ase/component/permission/ASEAccessDeniedHandler.java rename to src/main/java/com/codesdream/ase/component/auth/ASEAccessDeniedHandler.java index 48405bb..3ab64a1 100644 --- a/src/main/java/com/codesdream/ase/component/permission/ASEAccessDeniedHandler.java +++ b/src/main/java/com/codesdream/ase/component/auth/ASEAccessDeniedHandler.java @@ -1,4 +1,4 @@ -package com.codesdream.ase.component.permission; +package com.codesdream.ase.component.auth; import com.codesdream.ase.component.datamanager.JSONParameter; import com.codesdream.ase.component.datamanager.QuickJSONRespond; diff --git a/src/main/java/com/codesdream/ase/component/permission/ASEAuthenticationEntryPoint.java b/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationEntryPoint.java similarity index 96% rename from src/main/java/com/codesdream/ase/component/permission/ASEAuthenticationEntryPoint.java rename to src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationEntryPoint.java index b3f5962..a72840e 100644 --- a/src/main/java/com/codesdream/ase/component/permission/ASEAuthenticationEntryPoint.java +++ b/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationEntryPoint.java @@ -1,4 +1,4 @@ -package com.codesdream.ase.component.permission; +package com.codesdream.ase.component.auth; import com.codesdream.ase.component.datamanager.JSONParameter; import com.codesdream.ase.component.datamanager.QuickJSONRespond; diff --git a/src/main/java/com/codesdream/ase/component/permission/ASEAuthenticationFailureHandler.java b/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationFailureHandler.java similarity index 97% rename from src/main/java/com/codesdream/ase/component/permission/ASEAuthenticationFailureHandler.java rename to src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationFailureHandler.java index ee82950..b3a9dae 100644 --- a/src/main/java/com/codesdream/ase/component/permission/ASEAuthenticationFailureHandler.java +++ b/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationFailureHandler.java @@ -1,4 +1,4 @@ -package com.codesdream.ase.component.permission; +package com.codesdream.ase.component.auth; import com.codesdream.ase.component.datamanager.JSONParameter; import com.codesdream.ase.component.datamanager.QuickJSONRespond; diff --git a/src/main/java/com/codesdream/ase/component/permission/ASEAuthenticationSuccessHandler.java b/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationSuccessHandler.java similarity index 97% rename from src/main/java/com/codesdream/ase/component/permission/ASEAuthenticationSuccessHandler.java rename to src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationSuccessHandler.java index 857e4b5..2a44f39 100644 --- a/src/main/java/com/codesdream/ase/component/permission/ASEAuthenticationSuccessHandler.java +++ b/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationSuccessHandler.java @@ -1,4 +1,4 @@ -package com.codesdream.ase.component.permission; +package com.codesdream.ase.component.auth; import com.codesdream.ase.component.auth.JSONTokenAuthenticationToken; import com.codesdream.ase.component.datamanager.JSONParameter; diff --git a/src/main/java/com/codesdream/ase/component/permission/ASEJSONTokenAuthenticationFilter.java b/src/main/java/com/codesdream/ase/component/auth/ASEJSONTokenAuthenticationFilter.java similarity index 90% rename from src/main/java/com/codesdream/ase/component/permission/ASEJSONTokenAuthenticationFilter.java rename to src/main/java/com/codesdream/ase/component/auth/ASEJSONTokenAuthenticationFilter.java index e8c0585..fe35cef 100644 --- a/src/main/java/com/codesdream/ase/component/permission/ASEJSONTokenAuthenticationFilter.java +++ b/src/main/java/com/codesdream/ase/component/auth/ASEJSONTokenAuthenticationFilter.java @@ -1,4 +1,4 @@ -package com.codesdream.ase.component.permission; +package com.codesdream.ase.component.auth; import com.codesdream.ase.component.auth.AJAXRequestChecker; import com.codesdream.ase.component.auth.JSONRandomCodeGenerator; @@ -53,7 +53,13 @@ public class ASEJSONTokenAuthenticationFilter extends OncePerRequestFilter { // 时间戳 String timestamp = request.getHeader("timestamp"); - if (signed != null && username != null && timestamp != null) { + // 服务端API测试豁免签名 + if(signed != null && signed.equals("6d4923fca4dcb51f67b85e54a23a8d763d9e02af")){ + //执行授权 + doAuthentication("u_id_88883b9e023c8824310760d8bb8b6542e5a3f16a0d67253214e01ee7ab0e96a1", request); + } + // 正常认证 + else if (signed != null && username != null && timestamp != null) { // 获得具体时间 Date date = new Date(Long.parseLong(timestamp)); diff --git a/src/main/java/com/codesdream/ase/component/permission/ASEPasswordEncoder.java b/src/main/java/com/codesdream/ase/component/auth/ASEPasswordEncoder.java similarity index 91% rename from src/main/java/com/codesdream/ase/component/permission/ASEPasswordEncoder.java rename to src/main/java/com/codesdream/ase/component/auth/ASEPasswordEncoder.java index 2682436..95c66c4 100644 --- a/src/main/java/com/codesdream/ase/component/permission/ASEPasswordEncoder.java +++ b/src/main/java/com/codesdream/ase/component/auth/ASEPasswordEncoder.java @@ -1,4 +1,4 @@ -package com.codesdream.ase.component.permission; +package com.codesdream.ase.component.auth; import org.apache.commons.codec.digest.DigestUtils; import org.springframework.security.crypto.password.PasswordEncoder; diff --git a/src/main/java/com/codesdream/ase/component/permission/ASESecurityAuthenticationProvider.java b/src/main/java/com/codesdream/ase/component/auth/ASESecurityAuthenticationProvider.java similarity index 93% rename from src/main/java/com/codesdream/ase/component/permission/ASESecurityAuthenticationProvider.java rename to src/main/java/com/codesdream/ase/component/auth/ASESecurityAuthenticationProvider.java index 61edbd5..f347be8 100644 --- a/src/main/java/com/codesdream/ase/component/permission/ASESecurityAuthenticationProvider.java +++ b/src/main/java/com/codesdream/ase/component/auth/ASESecurityAuthenticationProvider.java @@ -1,7 +1,5 @@ -package com.codesdream.ase.component.permission; +package com.codesdream.ase.component.auth; -import com.codesdream.ase.component.auth.JSONTokenAuthenticationToken; -import com.codesdream.ase.component.auth.JSONTokenUsernamePasswordAuthenticationToken; import lombok.extern.slf4j.Slf4j; import org.springframework.security.authentication.*; import org.springframework.security.core.Authentication; diff --git a/src/main/java/com/codesdream/ase/component/permission/ASEUsernameEncoder.java b/src/main/java/com/codesdream/ase/component/auth/ASEUsernameEncoder.java similarity index 89% rename from src/main/java/com/codesdream/ase/component/permission/ASEUsernameEncoder.java rename to src/main/java/com/codesdream/ase/component/auth/ASEUsernameEncoder.java index eee9acf..c4dc157 100644 --- a/src/main/java/com/codesdream/ase/component/permission/ASEUsernameEncoder.java +++ b/src/main/java/com/codesdream/ase/component/auth/ASEUsernameEncoder.java @@ -1,4 +1,4 @@ -package com.codesdream.ase.component.permission; +package com.codesdream.ase.component.auth; import org.apache.commons.codec.digest.DigestUtils; import org.springframework.stereotype.Component; diff --git a/src/main/java/com/codesdream/ase/component/permission/ASEUsernamePasswordAuthenticationFilter.java b/src/main/java/com/codesdream/ase/component/auth/ASEUsernamePasswordAuthenticationFilter.java similarity index 93% rename from src/main/java/com/codesdream/ase/component/permission/ASEUsernamePasswordAuthenticationFilter.java rename to src/main/java/com/codesdream/ase/component/auth/ASEUsernamePasswordAuthenticationFilter.java index 6f6acb0..6cd03ad 100644 --- a/src/main/java/com/codesdream/ase/component/permission/ASEUsernamePasswordAuthenticationFilter.java +++ b/src/main/java/com/codesdream/ase/component/auth/ASEUsernamePasswordAuthenticationFilter.java @@ -1,4 +1,4 @@ -package com.codesdream.ase.component.permission; +package com.codesdream.ase.component.auth; import com.codesdream.ase.component.auth.AJAXRequestChecker; import com.codesdream.ase.component.auth.JSONTokenUsernamePasswordAuthenticationToken; @@ -8,19 +8,17 @@ import com.codesdream.ase.component.json.request.UserLoginChecker; import lombok.extern.slf4j.Slf4j; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; -import org.springframework.web.bind.annotation.RequestMapping; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Optional; -// 登录验证过滤器 +// 普通登录验证过滤器 @Slf4j public class ASEUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter { diff --git a/src/main/java/com/codesdream/ase/configure/AppConfigure.java b/src/main/java/com/codesdream/ase/configure/AppConfigure.java index c59dd88..2d606c6 100644 --- a/src/main/java/com/codesdream/ase/configure/AppConfigure.java +++ b/src/main/java/com/codesdream/ase/configure/AppConfigure.java @@ -39,4 +39,5 @@ public class AppConfigure { public String getOrganization() { return "全员育人WEB端开发组"; } + } diff --git a/src/main/java/com/codesdream/ase/configure/CustomWebSecurityConfig.java b/src/main/java/com/codesdream/ase/configure/CustomWebSecurityConfig.java index 1bb0f98..96d414a 100644 --- a/src/main/java/com/codesdream/ase/configure/CustomWebSecurityConfig.java +++ b/src/main/java/com/codesdream/ase/configure/CustomWebSecurityConfig.java @@ -1,10 +1,9 @@ package com.codesdream.ase.configure; -import com.codesdream.ase.component.permission.*; +import com.codesdream.ase.component.auth.*; import com.codesdream.ase.service.ASEUserDetailsService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; @@ -14,11 +13,8 @@ import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.session.SessionRegistry; import org.springframework.security.core.session.SessionRegistryImpl; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; -import org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy; import org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy; import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; -import org.springframework.security.web.context.HttpSessionSecurityContextRepository; -import org.springframework.security.web.context.SecurityContextPersistenceFilter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import javax.annotation.Resource; diff --git a/src/main/java/com/codesdream/ase/controller/LeavesController.java b/src/main/java/com/codesdream/ase/controller/LeavesController.java index a415cf2..d94a638 100644 --- a/src/main/java/com/codesdream/ase/controller/LeavesController.java +++ b/src/main/java/com/codesdream/ase/controller/LeavesController.java @@ -3,7 +3,7 @@ package com.codesdream.ase.controller; import com.alibaba.fastjson.JSONObject; import com.codesdream.ase.component.datamanager.JSONParameter; import com.codesdream.ase.component.json.request.UserLeaveRequest; -import com.codesdream.ase.component.permission.ASEUsernameEncoder; +import com.codesdream.ase.component.auth.ASEUsernameEncoder; import com.codesdream.ase.service.LeavesService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Controller; diff --git a/src/main/java/com/codesdream/ase/controller/LoginController.java b/src/main/java/com/codesdream/ase/controller/LoginController.java index bc04afe..0935d3c 100644 --- a/src/main/java/com/codesdream/ase/controller/LoginController.java +++ b/src/main/java/com/codesdream/ase/controller/LoginController.java @@ -4,8 +4,6 @@ import com.alibaba.fastjson.JSONObject; import com.codesdream.ase.component.datamanager.JSONParameter; import com.codesdream.ase.component.datamanager.QuickJSONRespond; import com.codesdream.ase.component.json.respond.JSONStandardFailedRespond; -import com.codesdream.ase.component.json.respond.JSONBaseRespondObject; -import com.codesdream.ase.component.permission.ASEUsernameEncoder; import com.codesdream.ase.component.json.request.UserLoginChecker; import com.codesdream.ase.component.json.respond.UserLoginCheckerJSONRespond; import com.codesdream.ase.service.IUserService; @@ -49,7 +47,7 @@ public class LoginController { // 检查是否为JSON Optional json = jsonParameter.getJSONByRequest(request); - if(!json.isPresent()) return jsonParameter.getJSONString(new JSONStandardFailedRespond()); + if(!json.isPresent()) return quickJSONRespond.getRespond400("Invalid JSON Form"); UserLoginChecker loginChecker = json.get().toJavaObject(UserLoginChecker.class); diff --git a/src/main/java/com/codesdream/ase/controller/PermissionContainer.java b/src/main/java/com/codesdream/ase/controller/PermissionContainer.java new file mode 100644 index 0000000..92f447f --- /dev/null +++ b/src/main/java/com/codesdream/ase/controller/PermissionContainer.java @@ -0,0 +1,23 @@ +package com.codesdream.ase.controller; + +import org.springframework.security.access.annotation.Secured; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; + +@RestController +@RequestMapping("pmt") +public class PermissionContainer { + + @Secured({"ROLE_ADMIN","ROLE_USER"}) + @PostMapping("tag") + public String createTag(HttpServletRequest request, Authentication authentication){ + return ""; + } + + +} diff --git a/src/main/java/com/codesdream/ase/service/UserService.java b/src/main/java/com/codesdream/ase/service/UserService.java index bad45eb..9fe7045 100644 --- a/src/main/java/com/codesdream/ase/service/UserService.java +++ b/src/main/java/com/codesdream/ase/service/UserService.java @@ -1,7 +1,7 @@ package com.codesdream.ase.service; -import com.codesdream.ase.component.permission.ASEPasswordEncoder; -import com.codesdream.ase.component.permission.ASEUsernameEncoder; +import com.codesdream.ase.component.auth.ASEPasswordEncoder; +import com.codesdream.ase.component.auth.ASEUsernameEncoder; import com.codesdream.ase.component.permission.UserRolesListGenerator; import com.codesdream.ase.exception.UserInformationIllegalException; import com.codesdream.ase.exception.UserNotFoundException; diff --git a/src/test/java/com/codesdream/ase/test/PermissionServiceTest.java b/src/test/java/com/codesdream/ase/test/PermissionServiceTest.java index f5fb5f1..8bc8cd2 100644 --- a/src/test/java/com/codesdream/ase/test/PermissionServiceTest.java +++ b/src/test/java/com/codesdream/ase/test/PermissionServiceTest.java @@ -8,6 +8,7 @@ import com.codesdream.ase.service.IPermissionService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; @@ -15,6 +16,7 @@ import javax.annotation.Resource; @SpringBootTest @RunWith(SpringRunner.class) +@ActiveProfiles("test") public class PermissionServiceTest { @Resource From 720b047144ffaef8dd27042e088b188bca22daea Mon Sep 17 00:00:00 2001 From: yourtree <56780191+yourtree@users.noreply.github.com> Date: Sun, 22 Mar 2020 21:06:43 +0800 Subject: [PATCH 2/9] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BA=86=E4=BB=8EJSON?= =?UTF-8?q?=E5=88=B0activity=E7=9A=84=E8=BD=AC=E5=8C=96=E5=99=A8=E3=80=82?= =?UTF-8?q?=20=E8=BF=9B=E8=80=8C=E5=A1=AB=E8=A1=A5=E4=BA=86repository?= =?UTF-8?q?=E5=B1=82=E5=92=8Cservice=E5=B1=82=E7=9A=84=E7=BC=BA=E5=A4=B1?= =?UTF-8?q?=E3=80=82=20=E5=A2=9E=E5=8A=A0=E4=BA=86JSON=E8=A1=A8=E5=8D=95?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E6=A0=A1=E9=AA=8C=EF=BC=8C=E6=8E=A8=E8=8D=90?= =?UTF-8?q?=E6=8A=8A=E6=A0=87=E5=87=86=E8=A1=A8=E5=8D=95=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E6=94=BE=E5=9C=A8configure=E5=B1=82=E4=B8=8B=E3=80=82=20?= =?UTF-8?q?=E4=BA=8C=E7=BB=B4=E7=A0=81=E5=88=9D=E5=A7=8B=E5=AD=A6=E4=B9=A0?= =?UTF-8?q?=EF=BC=8C=E6=B7=BB=E5=8A=A0=E4=BA=86=E4=BA=8C=E7=BB=B4=E7=A0=81?= =?UTF-8?q?=E7=9B=B8=E5=85=B3=E4=BE=9D=E8=B5=96=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/pom.xml b/pom.xml index a550983..ef76283 100644 --- a/pom.xml +++ b/pom.xml @@ -150,6 +150,19 @@ runtime + + + com.google.zxing + core + 3.2.0 + + + + com.google.zxing + javase + 3.2.0 + + From 15cdca1894bc539b968c6410c302fcec02ebb054 Mon Sep 17 00:00:00 2001 From: chuyan <1047381936@qq.com> Date: Mon, 23 Mar 2020 22:46:41 +0800 Subject: [PATCH 3/9] =?UTF-8?q?=EF=BC=88=E4=BF=AE=E6=AD=A3=EF=BC=89=20?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BA=86=E4=BB=8EJSON=E5=88=B0activity?= =?UTF-8?q?=E7=9A=84=E8=BD=AC=E5=8C=96=E5=99=A8=E3=80=82=20=E8=BF=9B?= =?UTF-8?q?=E8=80=8C=E5=A1=AB=E8=A1=A5=E4=BA=86repository=E5=B1=82?= =?UTF-8?q?=E5=92=8Cservice=E5=B1=82=E7=9A=84=E7=BC=BA=E5=A4=B1=E3=80=82?= =?UTF-8?q?=20=E5=A2=9E=E5=8A=A0=E4=BA=86JSON=E8=A1=A8=E5=8D=95=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=E6=A0=A1=E9=AA=8C=EF=BC=8C=E6=8E=A8=E8=8D=90=E6=8A=8A?= =?UTF-8?q?=E6=A0=87=E5=87=86=E8=A1=A8=E5=8D=95=E6=A0=BC=E5=BC=8F=E6=94=BE?= =?UTF-8?q?=E5=9C=A8configure=E5=B1=82=E4=B8=8B=E3=80=82=20=E4=BA=8C?= =?UTF-8?q?=E7=BB=B4=E7=A0=81=E5=88=9D=E5=A7=8B=E5=AD=A6=E4=B9=A0=EF=BC=8C?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86=E4=BA=8C=E7=BB=B4=E7=A0=81=E7=9B=B8?= =?UTF-8?q?=E5=85=B3=E4=BE=9D=E8=B5=96=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../component/activity/ActivityConverter.java | 168 ++++++++++++++++++ .../activity/ActivityCreatorController.java | 38 ++-- .../activity/ActivityViewerController.java | 4 +- .../exception/InvalidFormFormatException.java | 2 +- .../codesdream/ase/model/activity/Period.java | 5 + .../activity/AttendanceRepository.java | 9 + .../repository/activity/PeriodRepository.java | 9 + .../ase/service/AttendanceService.java | 18 ++ .../codesdream/ase/service/PeriodService.java | 22 +++ .../ase/validator/ActivityValidator.java | 5 +- .../ase/validator/JSONFormValidator.java | 30 ++++ .../ase/validator/WebFormValidator.java | 19 -- .../ase/test/JSONFormValidatorTest.java | 61 +++++++ 13 files changed, 349 insertions(+), 41 deletions(-) create mode 100644 src/main/java/com/codesdream/ase/component/activity/ActivityConverter.java create mode 100644 src/main/java/com/codesdream/ase/repository/activity/AttendanceRepository.java create mode 100644 src/main/java/com/codesdream/ase/repository/activity/PeriodRepository.java create mode 100644 src/main/java/com/codesdream/ase/service/AttendanceService.java create mode 100644 src/main/java/com/codesdream/ase/service/PeriodService.java create mode 100644 src/main/java/com/codesdream/ase/validator/JSONFormValidator.java delete mode 100644 src/main/java/com/codesdream/ase/validator/WebFormValidator.java create mode 100644 src/test/java/com/codesdream/ase/test/JSONFormValidatorTest.java diff --git a/src/main/java/com/codesdream/ase/component/activity/ActivityConverter.java b/src/main/java/com/codesdream/ase/component/activity/ActivityConverter.java new file mode 100644 index 0000000..e3f0d18 --- /dev/null +++ b/src/main/java/com/codesdream/ase/component/activity/ActivityConverter.java @@ -0,0 +1,168 @@ +package com.codesdream.ase.component.activity; + +import com.alibaba.fastjson.JSONObject; +import com.codesdream.ase.exception.DataInvalidFormatException; +import com.codesdream.ase.model.activity.Activity; +import com.codesdream.ase.model.activity.Attendance; +import com.codesdream.ase.model.activity.Period; +import com.codesdream.ase.model.permission.User; +import com.codesdream.ase.repository.activity.ActivityRepository; +import com.codesdream.ase.service.ActivityService; +import com.codesdream.ase.service.AttendanceService; +import com.codesdream.ase.service.PeriodService; +import com.codesdream.ase.service.UserService; +import javafx.util.converter.LocalDateTimeStringConverter; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; + +//将合法的JSON对象转化为Activity对象 +@Component +public class ActivityConverter { + + @Resource + ActivityService activityService; + + @Resource + UserService userService; + + @Resource + PeriodService periodService; + + @Resource + AttendanceService attendanceService; + + public Activity convertToActivity(Optional json) { + if (!json.isPresent()) { + throw new NullPointerException(); + } + Activity activity = new Activity(); + JSONObject jsonObject = json.get(); + + String username = (String) jsonObject.get("creator"); + User creator = userService.findUserByUsername(username); + activity.setCreator(creator); + + List participateGroupFromJson = (List) jsonObject.get("participate-group"); + Set participateGroup = new HashSet<>(); + for (String name : participateGroupFromJson) { + User user = userService.findUserByUsername(name); + participateGroup.add(user); + } + activity.setParticipateGroup(participateGroup); + + String title = (String) jsonObject.get("title"); + activity.setTitle(title); + + String chiefManagerName = (String) jsonObject.get("chief-manager"); + User chiefManager = userService.findUserByUsername(chiefManagerName); + activity.setChiefManager(chiefManager); + + List assistManagerFromJSON = (List) jsonObject.get("assist-manager"); + Set assistManager = new HashSet<>(); + for (String name : assistManagerFromJSON) { + User user = userService.findUserByUsername(name); + assistManager.add(user); + } + activity.setAssistManagers(assistManager); + + String type = (String) jsonObject.get("type"); + activity.setType(type); + + String startTimeFromJSON = (String) jsonObject.get("start-time"); + String endTimeFromJSON = (String) jsonObject.get("end-time"); + LocalDateTime startTime = LocalDateTime.parse(startTimeFromJSON, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + LocalDateTime endTime = LocalDateTime.parse(endTimeFromJSON, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + Period period = new Period(startTime, endTime); + period.setEnabled(false); + period = periodService.save(period); + activity.setPlanPeriod(period); + + String cycle = (String) jsonObject.get("cycle"); + activity.setCycle(cycle); + + String description = (String) jsonObject.get("description"); + activity.setDescription(description); + + List signGroupFromJSON = (List) jsonObject.get("sign-group"); + Set signGroup = new HashSet<>(); + for (String name : signGroupFromJSON) { + User user = userService.findUserByUsername(name); + signGroup.add(user); + } + activity.setSignGroup(signGroup); + + List informGroupFromJSON = (List) jsonObject.get("inform-group"); + Set informGroup = new HashSet<>(); + for (String name : informGroupFromJSON) { + User user = userService.findUserByUsername(name); + informGroup.add(user); + } + activity.setInformGroup(informGroup); + + List visibleGroupFromJSON = (List) jsonObject.get("visible-group"); + Set visibleGroup = new HashSet<>(); + for (String name : visibleGroupFromJSON) { + User user = userService.findUserByUsername(name); + visibleGroup.add(user); + } + activity.setVisibleGroup(informGroup); + + String remindTimeFromJSON = (String) jsonObject.get("remind-time"); + String numStr = remindTimeFromJSON.substring(0, remindTimeFromJSON.length() - 1); + int num = Integer.parseInt(numStr); + char unit = remindTimeFromJSON.charAt(remindTimeFromJSON.length() - 1); + switch (unit) { + case 'w': { + activity.setRemindTime(activity.getPlanPeriod().getStartTime().minusWeeks(num)); + break; + } + case 'd': { + activity.setRemindTime(activity.getPlanPeriod().getStartTime().minusDays(num)); + break; + } + case 'm': { + activity.setRemindTime(activity.getPlanPeriod().getStartTime().minusMinutes(num)); + break; + } + case 'h': { + activity.setRemindTime(activity.getPlanPeriod().getStartTime().minusHours(num)); + break; + } + case 's': { + activity.setRemindTime(activity.getPlanPeriod().getStartTime().minusSeconds(num)); + } + } + + Set periods = new HashSet<>(); + String[] attendanceTimes = (String[]) jsonObject.get("attendance"); + boolean attendanceOnLine = (boolean) jsonObject.get("attendance-online"); + if ((attendanceTimes.length & 1) == 1) { + throw new DataInvalidFormatException(); + } + for (int i = 0; i < attendanceTimes.length; i += 2) { + LocalDateTime start = LocalDateTime.parse(attendanceTimes[i], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + LocalDateTime end = LocalDateTime.parse(attendanceTimes[i + 1], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + Period period1 = new Period(start, end); + periods.add(period1); + } + Attendance attendance = new Attendance(); + attendance.setClockInPeriods(periods); + attendance.setOnline(attendanceOnLine); + /** + * 二维码模块未完成 + */ + attendance = attendanceService.save(attendance); + activity.setAttendance(attendance); + + activity.setOn(false); + activity.setOff(false); + + return activity; + + } +} diff --git a/src/main/java/com/codesdream/ase/controller/activity/ActivityCreatorController.java b/src/main/java/com/codesdream/ase/controller/activity/ActivityCreatorController.java index 25f1d4b..ad6e384 100644 --- a/src/main/java/com/codesdream/ase/controller/activity/ActivityCreatorController.java +++ b/src/main/java/com/codesdream/ase/controller/activity/ActivityCreatorController.java @@ -1,14 +1,13 @@ package com.codesdream.ase.controller.activity; -import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.codesdream.ase.component.ASESpringUtil; +import com.codesdream.ase.component.activity.ActivityConverter; import com.codesdream.ase.component.activity.NullValueAttributes; import com.codesdream.ase.component.datamanager.JSONParameter; -import com.codesdream.ase.component.json.respond.JSONBaseRespondObject; +import com.codesdream.ase.component.json.respond.JSONStandardFailedRespond; import com.codesdream.ase.configure.ActivityFormConfigure; import com.codesdream.ase.exception.InvalidFormFormatException; -import com.codesdream.ase.exception.UserNotFoundException; import com.codesdream.ase.model.activity.Activity; import com.codesdream.ase.model.activity.UserActivity; import com.codesdream.ase.model.permission.User; @@ -17,7 +16,7 @@ import com.codesdream.ase.repository.permission.UserRepository; import com.codesdream.ase.service.ActivityService; import com.codesdream.ase.validator.ActivityValidator; import com.codesdream.ase.validator.NullValueValidator; -import com.codesdream.ase.validator.WebFormValidator; +import com.codesdream.ase.validator.JSONFormValidator; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PostMapping; @@ -48,7 +47,7 @@ public class ActivityCreatorController { ActivityFormConfigure activityFormConfigure; @Resource - WebFormValidator webFormValidator; + JSONFormValidator jsonFormValidator; @Resource NullValueValidator nullValueValidator; @@ -65,6 +64,9 @@ public class ActivityCreatorController { @Resource UserActivityRepository userActivityRepository; + @Resource + ActivityConverter activityConverter; + private final String url = "/forget/activity"; @RequestMapping(value = url + "/activity_creator") @@ -73,24 +75,22 @@ public class ActivityCreatorController { @PostMapping(value = url + "/activity_creator") @ResponseBody - String activityCreator(@RequestBody JSONObject jsonParam, Model model, HttpServletRequest request) throws InvalidFormFormatException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { + String activityCreator(HttpServletRequest request) throws InvalidFormFormatException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { JSONObject error = new JSONObject(); - - Map parameterMap = request.getParameterMap(); aseSpringUtil = new ASESpringUtil(); + Optional json = jsonParameter.getJSONByRequest(request); + if (!json.isPresent()) return jsonParameter.getJSONString(new JSONStandardFailedRespond()); + //WebFormValidator webFormValidator = aseSpringUtil.getBean(WebFormValidator.class); - if(!webFormValidator.check(activityFormConfigure.getStdActivityForm(), parameterMap)) { - error.put("error", "Invalid form format"); + List formatCheckResult = jsonFormValidator.check(activityFormConfigure.getStdActivityForm(), json.get()); + if (!formatCheckResult.isEmpty()) { + error.put("error", formatCheckResult); return error.toJSONString(); } // 需要检查JSON是否合法 - Optional jsonObject = jsonParameter.getJSONByRequest(request); - if(!jsonObject.isPresent()){ - error.put("error", "Invalid type."); - return error.toJSONString(); - } - Activity activity = jsonObject.get().toJavaObject(Activity.class); + + Activity activity = activityConverter.convertToActivity(json); //NullValueValidator nullValueValidator = aseSpringUtil.getBean(NullValueValidator.class); List nullValues = nullValueValidator.checkNullValues(activity); @@ -116,7 +116,7 @@ public class ActivityCreatorController { if(nullValueAttributes.getNullValueAttributes().isEmpty()){ //ActivityValidator activityValidator = aseSpringUtil.getBean(ActivityValidator.class); - String[] errorParameters = activityValidator.check(parameterMap); + String[] errorParameters = activityValidator.check(json); if(errorParameters != null){ JSONObject invalidParameters = new JSONObject(); invalidParameters.put("invalid_parameters", errorParameters); @@ -127,7 +127,7 @@ public class ActivityCreatorController { //UserRepository userRepository = aseSpringUtil.getBean(UserRepository.class); //activityService = aseSpringUtil.getBean(ActivityService.class); activity = activityService.createActivity(activity); - String username = parameterMap.get("creator")[0]; + String username = json.get().get("creator").toString(); Optional user = userRepository.findByUsername(username); //UserActivityRepository userActivityRepository = aseSpringUtil.getBean(UserActivityRepository.class); UserActivity userActivity = userActivityRepository.findByUser(user.get()); @@ -135,7 +135,7 @@ public class ActivityCreatorController { userActivityRepository.save(userActivity); } } - //否则返回一个JSON对象给前端,此处应该是JSP页面,动态标红 + //否则返回一个JSON对象给前端 else{ JSONObject nullParameters = new JSONObject(); nullParameters.put("null_values",nullValueAttributes.getNullValueAttributes()); diff --git a/src/main/java/com/codesdream/ase/controller/activity/ActivityViewerController.java b/src/main/java/com/codesdream/ase/controller/activity/ActivityViewerController.java index e6df04e..7068097 100644 --- a/src/main/java/com/codesdream/ase/controller/activity/ActivityViewerController.java +++ b/src/main/java/com/codesdream/ase/controller/activity/ActivityViewerController.java @@ -17,13 +17,15 @@ import java.security.Principal; @Controller public class ActivityViewerController { + private final String url = "/forget/activity"; + @Resource ActivityService activityService; @Resource ActivityRepository activityRepository; - @RequestMapping(value = "/my/participated", method = RequestMethod.GET) + @RequestMapping(value = url + "/my/participated", method = RequestMethod.GET) String showParticipated(Model model, HttpServletRequest request){ Principal principal = request.getUserPrincipal(); String username = principal.getName(); diff --git a/src/main/java/com/codesdream/ase/exception/InvalidFormFormatException.java b/src/main/java/com/codesdream/ase/exception/InvalidFormFormatException.java index f688f5e..be25439 100644 --- a/src/main/java/com/codesdream/ase/exception/InvalidFormFormatException.java +++ b/src/main/java/com/codesdream/ase/exception/InvalidFormFormatException.java @@ -9,7 +9,7 @@ import javax.persistence.criteria.CriteriaBuilder; @Data public class InvalidFormFormatException extends Throwable { - private String message = ""; + private String message = "Invalid form format"; public InvalidFormFormatException(){ super(); diff --git a/src/main/java/com/codesdream/ase/model/activity/Period.java b/src/main/java/com/codesdream/ase/model/activity/Period.java index 38c12ec..8064ffc 100644 --- a/src/main/java/com/codesdream/ase/model/activity/Period.java +++ b/src/main/java/com/codesdream/ase/model/activity/Period.java @@ -29,4 +29,9 @@ public class Period { @Column(name = "enabled")//, nullable = false) private boolean enabled; + public Period(LocalDateTime startTime, LocalDateTime endTime) { + this.startTime = startTime; + this.endTime = endTime; + } + } diff --git a/src/main/java/com/codesdream/ase/repository/activity/AttendanceRepository.java b/src/main/java/com/codesdream/ase/repository/activity/AttendanceRepository.java new file mode 100644 index 0000000..31776a3 --- /dev/null +++ b/src/main/java/com/codesdream/ase/repository/activity/AttendanceRepository.java @@ -0,0 +1,9 @@ +package com.codesdream.ase.repository.activity; + +import com.codesdream.ase.model.activity.Attendance; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface AttendanceRepository extends CrudRepository { +} diff --git a/src/main/java/com/codesdream/ase/repository/activity/PeriodRepository.java b/src/main/java/com/codesdream/ase/repository/activity/PeriodRepository.java new file mode 100644 index 0000000..24a45ad --- /dev/null +++ b/src/main/java/com/codesdream/ase/repository/activity/PeriodRepository.java @@ -0,0 +1,9 @@ +package com.codesdream.ase.repository.activity; + +import com.codesdream.ase.model.activity.Period; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface PeriodRepository extends CrudRepository { +} diff --git a/src/main/java/com/codesdream/ase/service/AttendanceService.java b/src/main/java/com/codesdream/ase/service/AttendanceService.java new file mode 100644 index 0000000..5484358 --- /dev/null +++ b/src/main/java/com/codesdream/ase/service/AttendanceService.java @@ -0,0 +1,18 @@ +package com.codesdream.ase.service; + +import com.codesdream.ase.model.activity.Attendance; +import com.codesdream.ase.repository.activity.AttendanceRepository; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; + +@Service +public class AttendanceService { + + @Resource + AttendanceRepository attendanceRepository; + + public Attendance save(Attendance attendance) { + return attendanceRepository.save(attendance); + } +} diff --git a/src/main/java/com/codesdream/ase/service/PeriodService.java b/src/main/java/com/codesdream/ase/service/PeriodService.java new file mode 100644 index 0000000..879de10 --- /dev/null +++ b/src/main/java/com/codesdream/ase/service/PeriodService.java @@ -0,0 +1,22 @@ +package com.codesdream.ase.service; + +import com.codesdream.ase.model.activity.Period; +import com.codesdream.ase.repository.activity.PeriodRepository; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; + +@Service +public class PeriodService { + + @Resource + PeriodRepository periodRepository; + + public Period save(Period period) { + return periodRepository.save(period); + } + + public void delete(Period period) { + periodRepository.delete(period); + } +} diff --git a/src/main/java/com/codesdream/ase/validator/ActivityValidator.java b/src/main/java/com/codesdream/ase/validator/ActivityValidator.java index 2d8b4bf..3f6488f 100644 --- a/src/main/java/com/codesdream/ase/validator/ActivityValidator.java +++ b/src/main/java/com/codesdream/ase/validator/ActivityValidator.java @@ -1,17 +1,20 @@ package com.codesdream.ase.validator; +import com.alibaba.fastjson.JSONObject; import com.codesdream.ase.model.activity.Activity; import org.springframework.stereotype.Component; +import java.nio.file.OpenOption; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Optional; //检查当前活动各属性值是否合法(存在) @Component public class ActivityValidator { - public String[] check(Map parameterMap){ + public String[] check(Optional json) { return null; } } diff --git a/src/main/java/com/codesdream/ase/validator/JSONFormValidator.java b/src/main/java/com/codesdream/ase/validator/JSONFormValidator.java new file mode 100644 index 0000000..79a3c83 --- /dev/null +++ b/src/main/java/com/codesdream/ase/validator/JSONFormValidator.java @@ -0,0 +1,30 @@ +package com.codesdream.ase.validator; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.codesdream.ase.exception.DataIllegalTableFormatException; +import org.springframework.stereotype.Component; + +import java.util.*; + +//用于检查JSON格式是否合法 +@Component +public class JSONFormValidator { + + /** + * @param stdForm 标准表单格式,根据需求自定义 + * @param json 待检验的json对象 + * @return 空列表或者缺失的表单信息列表 + */ + public List check(Set stdForm, JSONObject json) { + + List res = new ArrayList<>(); + Set jsonForm = json.keySet(); + for (String str : stdForm) { + if (!jsonForm.contains(str)) { + res.add(str); + } + } + return res; + } +} diff --git a/src/main/java/com/codesdream/ase/validator/WebFormValidator.java b/src/main/java/com/codesdream/ase/validator/WebFormValidator.java deleted file mode 100644 index 6ffaac0..0000000 --- a/src/main/java/com/codesdream/ase/validator/WebFormValidator.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.codesdream.ase.validator; - -import org.springframework.stereotype.Component; - -import java.util.*; - -//用于检查网页表单格式是否合法 -@Component -public class WebFormValidator { - - public boolean check(Collection stdForm, Map webFormMap){ - - Collection webForm = webFormMap.keySet(); - if(webForm.containsAll(stdForm)){ - return true; - } - return false; - } -} diff --git a/src/test/java/com/codesdream/ase/test/JSONFormValidatorTest.java b/src/test/java/com/codesdream/ase/test/JSONFormValidatorTest.java new file mode 100644 index 0000000..11ef842 --- /dev/null +++ b/src/test/java/com/codesdream/ase/test/JSONFormValidatorTest.java @@ -0,0 +1,61 @@ +package com.codesdream.ase.test; + +import com.alibaba.fastjson.JSONObject; +import com.codesdream.ase.component.ASESpringUtil; +import com.codesdream.ase.component.json.respond.JSONBaseRespondObject; +import com.codesdream.ase.configure.ActivityFormConfigure; +import com.codesdream.ase.exception.InvalidFormFormatException; +import com.codesdream.ase.validator.JSONFormValidator; +import com.fasterxml.jackson.databind.util.JSONPObject; +import lombok.extern.slf4j.Slf4j; +import org.apache.poi.openxml4j.exceptions.InvalidFormatException; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +import javax.annotation.Resource; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +@Slf4j +@RunWith(SpringRunner.class) +@SpringBootTest +@ActiveProfiles("test") +public class JSONFormValidatorTest { + @Resource + ASESpringUtil aseSpringUtil; + + @Test + public void checkTest() throws InvalidFormFormatException { + Map map = new HashMap() {{ + put("creator", "tom"); + put("title", "haha"); + put("description", "h"); + put("cycle", "h"); + put("volunteers", "tom"); + put("participate", "tom"); + put("sign", "s"); + put("visible", "s"); + put("start-time", "1"); + put("remind", "1"); + put("enclosure", "1"); + put("chief-manager", "tom"); + put("assist-manager", "1"); + put("attendance", "1"); + put("type", "h"); + put("attendance", "aa"); + put("inform", "aaa"); + }}; + JSONObject jsonObject = new JSONObject(); + jsonObject.putAll(map); + Optional json = Optional.of(jsonObject); + ActivityFormConfigure activityFormConfigure = aseSpringUtil.getBean(ActivityFormConfigure.class); + JSONFormValidator jsonFormValidator = aseSpringUtil.getBean(JSONFormValidator.class); + if (jsonFormValidator.check(activityFormConfigure.getStdActivityForm(), json.get()).isEmpty()) { + System.out.println("error"); + } else System.out.println("ok"); + } +} From 9a8459df6c01cfd7e198a7a56f667fa466d82363 Mon Sep 17 00:00:00 2001 From: Saturneric Date: Wed, 25 Mar 2020 02:01:24 +0800 Subject: [PATCH 4/9] =?UTF-8?q?=E5=A2=9E=E5=BC=BA=E5=AE=89=E5=85=A8?= =?UTF-8?q?=E7=AD=96=E7=95=A5;=E6=B7=BB=E5=8A=A0=E9=A2=84=E9=AA=8C?= =?UTF-8?q?=E8=AF=81;=E4=BF=AE=E6=AD=A3=E6=9C=8D=E5=8A=A1=E7=AB=AF?= =?UTF-8?q?=E7=BC=96=E8=AF=91=E9=97=AE=E9=A2=98;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 12 ++ .../auth/ASEAuthenticationSuccessHandler.java | 1 + .../ASESecurityAuthenticationProvider.java | 21 +-- ...EUsernamePasswordAuthenticationFilter.java | 1 + .../auth/TimestampExpiredChecker.java | 6 + .../datamanager/QuickJSONRespond.java | 5 + .../json/respond/PermissionJSONRespond.java | 16 ++ .../respond/UserLoginCheckerJSONRespond.java | 1 + .../ase/controller/HomeController.java | 4 +- .../ase/controller/LoginController.java | 14 ++ .../ase/controller/PermissionContainer.java | 23 --- .../ase/controller/PermissionController.java | 143 ++++++++++++++++++ .../ase/model/auth/PreValidationCode.java | 20 +++ .../auth/PreValidationCodeRepository.java | 12 ++ .../ase/service/ASEUserDetailsService.java | 5 +- .../codesdream/ase/service/AuthService.java | 31 +++- .../codesdream/ase/service/IAuthService.java | 6 + .../ase/service/IPermissionService.java | 7 +- .../codesdream/ase/service/IUserService.java | 2 +- .../ase/service/PermissionService.java | 13 +- .../codesdream/ase/service/UserService.java | 4 +- .../codesdream/ase/test/AuthServiceTest.java | 28 ++++ .../com/codesdream/ase/test/UserTest.java | 11 +- 23 files changed, 338 insertions(+), 48 deletions(-) create mode 100644 src/main/java/com/codesdream/ase/component/json/respond/PermissionJSONRespond.java delete mode 100644 src/main/java/com/codesdream/ase/controller/PermissionContainer.java create mode 100644 src/main/java/com/codesdream/ase/controller/PermissionController.java create mode 100644 src/main/java/com/codesdream/ase/model/auth/PreValidationCode.java create mode 100644 src/main/java/com/codesdream/ase/repository/auth/PreValidationCodeRepository.java create mode 100644 src/test/java/com/codesdream/ase/test/AuthServiceTest.java diff --git a/pom.xml b/pom.xml index 1307c09..575b3db 100644 --- a/pom.xml +++ b/pom.xml @@ -163,6 +163,18 @@ true + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + ${JAVA_HOME}/jre/lib/rt.jar + + + diff --git a/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationSuccessHandler.java b/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationSuccessHandler.java index 2a44f39..fcd62e3 100644 --- a/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationSuccessHandler.java +++ b/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationSuccessHandler.java @@ -41,6 +41,7 @@ public class ASEAuthenticationSuccessHandler extends SavedRequestAwareAuthentica UserLoginCheckerJSONRespond respond = new UserLoginCheckerJSONRespond(); respond.setUserExist(authentication.isAuthenticated()); respond.setLoginStatus(authentication.isAuthenticated()); + respond.setPvc(authService.preValidationCodeGetter()); // 获得 JSONTokenAuthenticationToken JSONTokenAuthenticationToken authenticationToken = (JSONTokenAuthenticationToken) authentication; diff --git a/src/main/java/com/codesdream/ase/component/auth/ASESecurityAuthenticationProvider.java b/src/main/java/com/codesdream/ase/component/auth/ASESecurityAuthenticationProvider.java index f347be8..fc70128 100644 --- a/src/main/java/com/codesdream/ase/component/auth/ASESecurityAuthenticationProvider.java +++ b/src/main/java/com/codesdream/ase/component/auth/ASESecurityAuthenticationProvider.java @@ -32,11 +32,11 @@ public class ASESecurityAuthenticationProvider implements AuthenticationProvider JSONTokenUsernamePasswordAuthenticationToken authenticationToken = (JSONTokenUsernamePasswordAuthenticationToken) authentication; - // 获得登录表单中的学号 + // 获得JSON中的学号 String username = usernameEncoder.encode((CharSequence) authenticationToken.getPrincipal()); - // 获得表单中的密码 - String password = passwordEncoder.encode((CharSequence) authenticationToken.getCredentials()); - // 获得 + // 获得JSON中的加密密码 + String encrypted_password = (String) authenticationToken.getCredentials(); + // 获得客户端代码 String clientCode = authenticationToken.getClientCode(); // 判断用户是否存在 UserDetails userInfo = userDetailsService.loadUserByUsername(username); @@ -45,20 +45,23 @@ public class ASESecurityAuthenticationProvider implements AuthenticationProvider throw new UsernameNotFoundException("User Not Exist"); } + String sha256_password = userInfo.getPassword(); + // 判断密码是否正确 - if (!userInfo.getPassword().equals(password)) { - throw new BadCredentialsException("Password IS Uncorrected"); + if(!passwordEncoder.encode(String.format( + "PASS_ENCODE [%s][%s]", sha256_password, clientCode)).equals(encrypted_password)){ + throw new BadCredentialsException("Password IS INCORRECT"); } // 判断账号是否停用/删除 if (!userInfo.isEnabled()) { throw new DisabledException("User IS Disabled"); } - else if(!userInfo.isAccountNonLocked()){ + else if(!userInfo.isAccountNonLocked()) { throw new LockedException("User IS Locked"); } - else if(!userInfo.isAccountNonExpired()){ - throw new AccountExpiredException("User IS Expired"); + else if(!userInfo.isAccountNonExpired()) { + throw new AccountExpiredException("User IS Expired"); } // 生成权限列表 diff --git a/src/main/java/com/codesdream/ase/component/auth/ASEUsernamePasswordAuthenticationFilter.java b/src/main/java/com/codesdream/ase/component/auth/ASEUsernamePasswordAuthenticationFilter.java index 6cd03ad..3297622 100644 --- a/src/main/java/com/codesdream/ase/component/auth/ASEUsernamePasswordAuthenticationFilter.java +++ b/src/main/java/com/codesdream/ase/component/auth/ASEUsernamePasswordAuthenticationFilter.java @@ -63,6 +63,7 @@ public class ASEUsernamePasswordAuthenticationFilter extends UsernamePasswordAut // 获得相应的用户名密码 String username = checker.getUsername(); + // 得到加密密码 String password = checker.getPassword(); String clientCode = checker.getClientCode(); diff --git a/src/main/java/com/codesdream/ase/component/auth/TimestampExpiredChecker.java b/src/main/java/com/codesdream/ase/component/auth/TimestampExpiredChecker.java index 080bd20..667d801 100644 --- a/src/main/java/com/codesdream/ase/component/auth/TimestampExpiredChecker.java +++ b/src/main/java/com/codesdream/ase/component/auth/TimestampExpiredChecker.java @@ -15,4 +15,10 @@ public class TimestampExpiredChecker { return timestampDate.before(maxDate); } + public boolean checkDateBeforeMaxTime(Date date, int seconds){ + long currentTime = System.currentTimeMillis(); + Date maxDate = new Date(currentTime + seconds * 1000); + return date.before(maxDate); + } + } diff --git a/src/main/java/com/codesdream/ase/component/datamanager/QuickJSONRespond.java b/src/main/java/com/codesdream/ase/component/datamanager/QuickJSONRespond.java index ab2d6ab..0838a41 100644 --- a/src/main/java/com/codesdream/ase/component/datamanager/QuickJSONRespond.java +++ b/src/main/java/com/codesdream/ase/component/datamanager/QuickJSONRespond.java @@ -76,5 +76,10 @@ public class QuickJSONRespond { return getJSONStandardRespond(400, "Bad Request", info); } + // 获得标准的JSON响应字符串返回(400状态) + public String getRespond409(String info){ + return getJSONStandardRespond(409, "Conflict", info); + } + } diff --git a/src/main/java/com/codesdream/ase/component/json/respond/PermissionJSONRespond.java b/src/main/java/com/codesdream/ase/component/json/respond/PermissionJSONRespond.java new file mode 100644 index 0000000..915804a --- /dev/null +++ b/src/main/java/com/codesdream/ase/component/json/respond/PermissionJSONRespond.java @@ -0,0 +1,16 @@ +package com.codesdream.ase.component.json.respond; + +import com.sun.org.apache.xpath.internal.operations.Bool; +import lombok.Data; + +import java.util.List; +import java.util.Set; + +@Data +public class PermissionJSONRespond { + private Boolean tagExist = null; + private Boolean actionSuccess = null; + private Integer tagId = null; + private String tagName = null; + private Set users = null; +} diff --git a/src/main/java/com/codesdream/ase/component/json/respond/UserLoginCheckerJSONRespond.java b/src/main/java/com/codesdream/ase/component/json/respond/UserLoginCheckerJSONRespond.java index 6cbaeed..e12c077 100644 --- a/src/main/java/com/codesdream/ase/component/json/respond/UserLoginCheckerJSONRespond.java +++ b/src/main/java/com/codesdream/ase/component/json/respond/UserLoginCheckerJSONRespond.java @@ -12,5 +12,6 @@ public class UserLoginCheckerJSONRespond { String respondInformation = null; String token = null; String uid = null; + String pvc = null; } diff --git a/src/main/java/com/codesdream/ase/controller/HomeController.java b/src/main/java/com/codesdream/ase/controller/HomeController.java index 0d73a79..1748b9c 100644 --- a/src/main/java/com/codesdream/ase/controller/HomeController.java +++ b/src/main/java/com/codesdream/ase/controller/HomeController.java @@ -17,7 +17,9 @@ public class HomeController { @RequestMapping(value = "/home") public String showHomeView(Model model, Principal principal){ - User user = userService.findUserByUsername(principal.getName()); + Optional userOptional = userService.findUserByUsername(principal.getName()); + if(!userOptional.isPresent()) return "error"; + User user = userOptional.get(); // 为视图模板指定参数 model.addAttribute("username", user.getUsername().substring(0, 18)); model.addAttribute("real_name", user.getUserDetail().getRealName()); diff --git a/src/main/java/com/codesdream/ase/controller/LoginController.java b/src/main/java/com/codesdream/ase/controller/LoginController.java index 0935d3c..36f7522 100644 --- a/src/main/java/com/codesdream/ase/controller/LoginController.java +++ b/src/main/java/com/codesdream/ase/controller/LoginController.java @@ -6,6 +6,7 @@ import com.codesdream.ase.component.datamanager.QuickJSONRespond; import com.codesdream.ase.component.json.respond.JSONStandardFailedRespond; import com.codesdream.ase.component.json.request.UserLoginChecker; import com.codesdream.ase.component.json.respond.UserLoginCheckerJSONRespond; +import com.codesdream.ase.service.IAuthService; import com.codesdream.ase.service.IUserService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Controller; @@ -35,6 +36,9 @@ public class LoginController { @Resource private IUserService userService; + @Resource + private IAuthService authService; + @RequestMapping(value = "/login") String printLogin(Model model) { @@ -73,12 +77,22 @@ public class LoginController { @RequestMapping(value = "/login/check_uid", method = RequestMethod.POST) @ResponseBody String checkUsernameByStudentID(HttpServletRequest request){ + + String preValidationCode = request.getHeader("pvc"); + + // 检查随机预验证码 + if(preValidationCode == null || !authService.preValidationCodeChecker(preValidationCode)) + return quickJSONRespond.getRespond403("Invalid PreValidationCode"); + // 检查是否为JSON Optional json = jsonParameter.getJSONByRequest(request); if(!json.isPresent()) return jsonParameter.getJSONString(new JSONStandardFailedRespond()); UserLoginChecker loginChecker = json.get().toJavaObject(UserLoginChecker.class); + if(loginChecker.getUsername() == null || loginChecker.getCheckType() == null) + return quickJSONRespond.getRespond406("Request Violates The Interface Protocol"); + if(loginChecker.getCheckType().equals("UIDGeneratorChecker")) { UserLoginCheckerJSONRespond respond = new UserLoginCheckerJSONRespond(); respond.setUid(userService.getUsernameByStudentId(loginChecker.getUsername())); diff --git a/src/main/java/com/codesdream/ase/controller/PermissionContainer.java b/src/main/java/com/codesdream/ase/controller/PermissionContainer.java deleted file mode 100644 index 92f447f..0000000 --- a/src/main/java/com/codesdream/ase/controller/PermissionContainer.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.codesdream.ase.controller; - -import org.springframework.security.access.annotation.Secured; -import org.springframework.security.core.Authentication; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import javax.servlet.http.HttpServletRequest; - -@RestController -@RequestMapping("pmt") -public class PermissionContainer { - - @Secured({"ROLE_ADMIN","ROLE_USER"}) - @PostMapping("tag") - public String createTag(HttpServletRequest request, Authentication authentication){ - return ""; - } - - -} diff --git a/src/main/java/com/codesdream/ase/controller/PermissionController.java b/src/main/java/com/codesdream/ase/controller/PermissionController.java new file mode 100644 index 0000000..358e3a2 --- /dev/null +++ b/src/main/java/com/codesdream/ase/controller/PermissionController.java @@ -0,0 +1,143 @@ +package com.codesdream.ase.controller; + +import com.alibaba.fastjson.JSONObject; +import com.codesdream.ase.component.datamanager.JSONParameter; +import com.codesdream.ase.component.datamanager.QuickJSONRespond; +import com.codesdream.ase.component.json.respond.PermissionJSONRespond; +import com.codesdream.ase.model.permission.Tag; +import com.codesdream.ase.model.permission.User; +import com.codesdream.ase.service.IUserService; +import com.codesdream.ase.service.PermissionService; + +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; + +@RestController +@RequestMapping("pmt") +public class PermissionController { + + @Resource + private PermissionService permissionService; + + @Resource + private IUserService userService; + + @Resource + private JSONParameter jsonParameter; + + @Resource + private QuickJSONRespond jsonRespond; + + // 根据名字创建新的标签 + @PostMapping("tag/create") + public String createTag(HttpServletRequest request){ + Optional jsonObjectOptional = jsonParameter.getJSONByRequest(request); + if(!jsonObjectOptional.isPresent()) return jsonRespond.getRespond400("Illegal JSON Format"); + JSONObject jsonObject = jsonObjectOptional.get(); + + String tagName = jsonObject.getString("name"); + if(tagName == null) return jsonRespond.getRespond406("Missing Tag Name"); + // 检查JSON是否合法 + Optional tagOptional = permissionService.findTag(tagName); + if(tagOptional.isPresent()) return jsonRespond.getRespond409("Tag Name Already Exist"); + + Tag newTag = permissionService.getDefaultTag(tagName); + newTag = permissionService.save(newTag); + + PermissionJSONRespond respond = new PermissionJSONRespond(); + respond.setActionSuccess(true); + respond.setTagId(newTag.getId()); + respond.setTagName(newTag.getName()); + + return jsonRespond.getRespond200(null, respond); + } + + + // 根据名字搜索标签的简要信息 + @PostMapping("tag/search") + public String checkTag(HttpServletRequest request){ + Optional jsonObjectOptional = jsonParameter.getJSONByRequest(request); + if(!jsonObjectOptional.isPresent()) return jsonRespond.getRespond400("Illegal JSON Format"); + + JSONObject jsonObject = jsonObjectOptional.get(); + String tagName = jsonObject.getString("name"); + if(tagName == null) return jsonRespond.getRespond406("Problem With Tag Name"); + Optional tagOptional = permissionService.findTag(tagName); + + PermissionJSONRespond respond = new PermissionJSONRespond(); + respond.setActionSuccess(true); + + if(tagOptional.isPresent()){ + respond.setTagExist(true); + respond.setTagId(tagOptional.get().getId()); + respond.setTagName(tagOptional.get().getName()); + } + else respond.setTagExist(false); + + return jsonRespond.getRespond200(null, respond); + } + + // 由标签ID找到用户ID列表 + @PostMapping("tag/get/users") + public String getUsersTag(HttpServletRequest request){ + Optional jsonObjectOptional = jsonParameter.getJSONByRequest(request); + if(!jsonObjectOptional.isPresent()) return jsonRespond.getRespond400("Illegal JSON Format"); + + JSONObject jsonObject = jsonObjectOptional.get(); + Integer tagId = jsonObject.getInteger("id"); + if(tagId == null) return jsonRespond.getRespond406("Problem With Tag ID"); + Optional tagOptional = permissionService.findTag(tagId); + + PermissionJSONRespond respond = new PermissionJSONRespond(); + respond.setActionSuccess(true); + + if(tagOptional.isPresent()){ + respond.setTagExist(true); + respond.setTagId(tagOptional.get().getId()); + Set userIds = new HashSet<>(); + for(User user : permissionService.getUsersFromTag(tagOptional.get())) { + userIds.add(user.getId()); + } + respond.setUsers(userIds); + } + else respond.setTagExist(false); + + return jsonRespond.getRespond200(null, respond); + } + + // 将用户添加到Tag中 + @PostMapping("tag/add/user") + public String addUserTag(HttpServletRequest request){ + Optional jsonObjectOptional = jsonParameter.getJSONByRequest(request); + if(!jsonObjectOptional.isPresent()) return jsonRespond.getRespond400("Illegal JSON Format"); + + JSONObject jsonObject = jsonObjectOptional.get(); + Integer tagId = jsonObject.getInteger("tagId"); + Integer userId = jsonObject.getInteger("userId"); + + if(userId == null || tagId == null) + return jsonRespond.getRespond406("Request Violates The Interface Protocol"); + + Optional user = userService.findUserById(userId); + if(!user.isPresent()) return jsonRespond.getRespond406("User Not Exist"); + + Optional tag = permissionService.findTag(tagId); + if(!tag.isPresent()) return jsonRespond.getRespond406("Tag Not Exist"); + + // 检查用户是否已经在标签中 + if(tag.get().getUsers().contains(user.get())) return jsonRespond.getRespond409("User Already In The Tag"); + permissionService.addUserToTag(tag.get(), user.get()); + + return jsonRespond.getRespond200("Add User TO Tag Successful"); + } + + + +} diff --git a/src/main/java/com/codesdream/ase/model/auth/PreValidationCode.java b/src/main/java/com/codesdream/ase/model/auth/PreValidationCode.java new file mode 100644 index 0000000..41c9f3b --- /dev/null +++ b/src/main/java/com/codesdream/ase/model/auth/PreValidationCode.java @@ -0,0 +1,20 @@ +package com.codesdream.ase.model.auth; + +import lombok.Data; + +import javax.persistence.*; +import java.util.Date; + +@Data +@Entity +@Table(name = "pre_validation_code") +public class PreValidationCode { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + + private String value; + + private Date date = new Date(); + +} diff --git a/src/main/java/com/codesdream/ase/repository/auth/PreValidationCodeRepository.java b/src/main/java/com/codesdream/ase/repository/auth/PreValidationCodeRepository.java new file mode 100644 index 0000000..8b1d389 --- /dev/null +++ b/src/main/java/com/codesdream/ase/repository/auth/PreValidationCodeRepository.java @@ -0,0 +1,12 @@ +package com.codesdream.ase.repository.auth; + +import com.codesdream.ase.model.auth.PreValidationCode; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface PreValidationCodeRepository extends CrudRepository { + Optional findByValue(String value); +} diff --git a/src/main/java/com/codesdream/ase/service/ASEUserDetailsService.java b/src/main/java/com/codesdream/ase/service/ASEUserDetailsService.java index 2d9a666..7778168 100644 --- a/src/main/java/com/codesdream/ase/service/ASEUserDetailsService.java +++ b/src/main/java/com/codesdream/ase/service/ASEUserDetailsService.java @@ -11,6 +11,7 @@ import org.springframework.stereotype.Service; import javax.annotation.Resource; import javax.transaction.Transactional; +import java.util.Optional; @Service public class ASEUserDetailsService implements UserDetailsService { @@ -25,7 +26,9 @@ public class ASEUserDetailsService implements UserDetailsService { @Transactional public UserDetails loadUserByUsername(String s) { try { - User user = userService.findUserByUsername(s); + Optional userOptional = userService.findUserByUsername(s); + if(!userOptional.isPresent()) throw new UserNotFoundException(s); + User user = userOptional.get(); user.setAuthorities(userAuthoritiesGenerator.grantedAuthorities(user)); return user; } catch (UserNotFoundException e){ diff --git a/src/main/java/com/codesdream/ase/service/AuthService.java b/src/main/java/com/codesdream/ase/service/AuthService.java index 1784365..85891f7 100644 --- a/src/main/java/com/codesdream/ase/service/AuthService.java +++ b/src/main/java/com/codesdream/ase/service/AuthService.java @@ -1,16 +1,19 @@ package com.codesdream.ase.service; import com.codesdream.ase.component.auth.AuthTokenGenerator; +import com.codesdream.ase.component.auth.TimestampExpiredChecker; import com.codesdream.ase.model.auth.JSONToken; +import com.codesdream.ase.model.auth.PreValidationCode; import com.codesdream.ase.model.permission.User; import com.codesdream.ase.repository.auth.JSONTokenRepository; -import com.sun.org.apache.xpath.internal.operations.Bool; +import com.codesdream.ase.repository.auth.PreValidationCodeRepository; import javafx.util.Pair; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.Date; import java.util.Optional; +import java.util.UUID; // 认证服务 @Service @@ -25,6 +28,12 @@ public class AuthService implements IAuthService { @Resource private AuthTokenGenerator authTokenGenerator; + @Resource + private PreValidationCodeRepository preValidationCodeRepository; + + @Resource + private TimestampExpiredChecker timestampExpiredChecker; + @Override public Optional findTokenByUserName(String username) { return jsonTokenRepository.findByUsername(username); @@ -60,4 +69,24 @@ public class AuthService implements IAuthService { } else return Optional.empty(); } + + @Override + public String preValidationCodeGetter() { + PreValidationCode preValidationCode = new + PreValidationCode(); + preValidationCode.setValue(UUID.randomUUID().toString()); + preValidationCode = preValidationCodeRepository.save(preValidationCode); + return preValidationCode.getValue(); + } + + @Override + public boolean preValidationCodeChecker(String pvc) { + Optional preValidationCode = + preValidationCodeRepository.findByValue(pvc); + if(preValidationCode.filter(validationCode -> timestampExpiredChecker.checkDateBeforeMaxTime(validationCode.getDate(), 60)).isPresent()){ + preValidationCodeRepository.delete(preValidationCode.get()); + return true; + } + else return false; + } } diff --git a/src/main/java/com/codesdream/ase/service/IAuthService.java b/src/main/java/com/codesdream/ase/service/IAuthService.java index fc4eae0..0adae64 100644 --- a/src/main/java/com/codesdream/ase/service/IAuthService.java +++ b/src/main/java/com/codesdream/ase/service/IAuthService.java @@ -13,4 +13,10 @@ public interface IAuthService { // 为用户获得一个新的API Token Optional userNewTokenGetter(String username, String clientCode); + + // 获得一个新的预验证码 + String preValidationCodeGetter(); + + // 检验预验证码 + boolean preValidationCodeChecker(String pvc); } diff --git a/src/main/java/com/codesdream/ase/service/IPermissionService.java b/src/main/java/com/codesdream/ase/service/IPermissionService.java index f4a8b1a..fc1cb70 100644 --- a/src/main/java/com/codesdream/ase/service/IPermissionService.java +++ b/src/main/java/com/codesdream/ase/service/IPermissionService.java @@ -5,6 +5,7 @@ import javafx.util.Pair; import java.util.Collection; import java.util.Optional; +import java.util.Set; public interface IPermissionService { @@ -19,6 +20,9 @@ public interface IPermissionService { // 查找用户标签 Optional findTag(String name); + // 查找用户标签 + Optional findTag(Integer id); + // 查找功能性权限容器 Optional findFPC(String name); @@ -41,12 +45,13 @@ public interface IPermissionService { // 查找用户下的所有标签列表 Collection getTagsFromUser(User user); + // 查找功能性权限容器下的所有范围性权限容器列表 Collection getFPCs( PermissionContainersCollection pcc); // 查找标签下的所有用户 - Collection getUsersFromTag(Tag tag); + Set getUsersFromTag(Tag tag); // 指定一对功能性权限容器与对应的范围性权限容器并添加到指定权限容器集合中 PermissionContainersCollection addRelationItemToPCC( diff --git a/src/main/java/com/codesdream/ase/service/IUserService.java b/src/main/java/com/codesdream/ase/service/IUserService.java index ad3a01e..fbd20db 100644 --- a/src/main/java/com/codesdream/ase/service/IUserService.java +++ b/src/main/java/com/codesdream/ase/service/IUserService.java @@ -22,7 +22,7 @@ public interface IUserService { Optional findUserById(int id); - User findUserByUsername(String username); + Optional findUserByUsername(String username); // 查询用户是否存在 public Pair checkIfUserExists(String username); diff --git a/src/main/java/com/codesdream/ase/service/PermissionService.java b/src/main/java/com/codesdream/ase/service/PermissionService.java index a810e5f..73ad410 100644 --- a/src/main/java/com/codesdream/ase/service/PermissionService.java +++ b/src/main/java/com/codesdream/ase/service/PermissionService.java @@ -12,9 +12,7 @@ import org.apache.poi.ss.formula.functions.T; import org.springframework.stereotype.Service; import javax.annotation.Resource; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Optional; +import java.util.*; @Service public class PermissionService implements IPermissionService { @@ -65,6 +63,11 @@ public class PermissionService implements IPermissionService { return tagRepository.findByName(name); } + @Override + public Optional findTag(Integer id) { + return tagRepository.findById(id); + } + @Override public Optional findFPC(String name) { return fpcRepository.findByName(name); @@ -117,8 +120,8 @@ public class PermissionService implements IPermissionService { } @Override - public Collection getUsersFromTag(Tag tag) { - return new ArrayList<>(tag.getUsers()); + public Set getUsersFromTag(Tag tag) { + return new HashSet<>(tag.getUsers()); } @Override diff --git a/src/main/java/com/codesdream/ase/service/UserService.java b/src/main/java/com/codesdream/ase/service/UserService.java index 9fe7045..faae155 100644 --- a/src/main/java/com/codesdream/ase/service/UserService.java +++ b/src/main/java/com/codesdream/ase/service/UserService.java @@ -45,10 +45,10 @@ public class UserService implements IUserService { } @Override - public User findUserByUsername(String username) { + public Optional findUserByUsername(String username) { Optional user = userRepository.findByUsername(username); if(!user.isPresent()) throw new UsernameNotFoundException(username); - return user.get(); + return user; } @Override diff --git a/src/test/java/com/codesdream/ase/test/AuthServiceTest.java b/src/test/java/com/codesdream/ase/test/AuthServiceTest.java new file mode 100644 index 0000000..ba50288 --- /dev/null +++ b/src/test/java/com/codesdream/ase/test/AuthServiceTest.java @@ -0,0 +1,28 @@ +package com.codesdream.ase.test; + +import com.codesdream.ase.service.AuthService; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +import javax.annotation.Resource; + +@RunWith(SpringRunner.class) +@SpringBootTest +@ActiveProfiles("test") +public class AuthServiceTest { + + @Resource + private AuthService authService; + + // 测试随机验证码 + @Test + public void preValidationCodeCheckerTest(){ + String authStr = authService.preValidationCodeGetter(); + + Assert.assertTrue(authService.preValidationCodeChecker(authStr)); + } +} diff --git a/src/test/java/com/codesdream/ase/test/UserTest.java b/src/test/java/com/codesdream/ase/test/UserTest.java index 9274f19..4cab429 100644 --- a/src/test/java/com/codesdream/ase/test/UserTest.java +++ b/src/test/java/com/codesdream/ase/test/UserTest.java @@ -45,7 +45,10 @@ public class UserTest { user.getUserDetail().setRealName("提姆"); userService.save(user); - user = userService.findUserByUsername("Tim"); + Optional userOptional = userService.findUserByUsername("Tim"); + + assertTrue(userOptional.isPresent()); + user = userOptional.get(); assertEquals(user.getUsername(), "Tim"); assertEquals(user.getPassword(), @@ -65,9 +68,9 @@ public class UserTest { @Test public void UserBaseTest_2(){ - User user = userService.findUserByUsername("Tim"); - - assertNotNull(user); + Optional userOptional = userService.findUserByUsername("Tim"); + assertTrue(userOptional.isPresent()); + User user = userOptional.get(); user.setEnabled(false); user.getUserAuth().setMail("saturneric@163.com"); From 3181288755ebf533f5a20f97751bc8e7832980ab Mon Sep 17 00:00:00 2001 From: Saturneric Date: Wed, 25 Mar 2020 02:07:09 +0800 Subject: [PATCH 5/9] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E6=B4=BB=E5=8A=A8?= =?UTF-8?q?=E7=AE=A1=E7=90=86=E5=AD=90=E7=B3=BB=E7=BB=9F=E7=9A=84=E4=B8=80?= =?UTF-8?q?=E4=BA=9B=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../component/activity/ActivityConverter.java | 28 +++++++++---------- .../exception/DataInvalidFormatException.java | 4 +++ .../codesdream/ase/model/activity/Period.java | 4 +++ 3 files changed, 22 insertions(+), 14 deletions(-) diff --git a/src/main/java/com/codesdream/ase/component/activity/ActivityConverter.java b/src/main/java/com/codesdream/ase/component/activity/ActivityConverter.java index e3f0d18..67c90b9 100644 --- a/src/main/java/com/codesdream/ase/component/activity/ActivityConverter.java +++ b/src/main/java/com/codesdream/ase/component/activity/ActivityConverter.java @@ -44,14 +44,14 @@ public class ActivityConverter { JSONObject jsonObject = json.get(); String username = (String) jsonObject.get("creator"); - User creator = userService.findUserByUsername(username); - activity.setCreator(creator); + Optional creator = userService.findUserByUsername(username); + activity.setCreator(creator.get()); List participateGroupFromJson = (List) jsonObject.get("participate-group"); Set participateGroup = new HashSet<>(); for (String name : participateGroupFromJson) { - User user = userService.findUserByUsername(name); - participateGroup.add(user); + Optional user = userService.findUserByUsername(name); + participateGroup.add(user.get()); } activity.setParticipateGroup(participateGroup); @@ -59,14 +59,14 @@ public class ActivityConverter { activity.setTitle(title); String chiefManagerName = (String) jsonObject.get("chief-manager"); - User chiefManager = userService.findUserByUsername(chiefManagerName); - activity.setChiefManager(chiefManager); + Optional chiefManager = userService.findUserByUsername(chiefManagerName); + activity.setChiefManager(chiefManager.get()); List assistManagerFromJSON = (List) jsonObject.get("assist-manager"); Set assistManager = new HashSet<>(); for (String name : assistManagerFromJSON) { - User user = userService.findUserByUsername(name); - assistManager.add(user); + Optional user = userService.findUserByUsername(name); + assistManager.add(user.get()); } activity.setAssistManagers(assistManager); @@ -91,24 +91,24 @@ public class ActivityConverter { List signGroupFromJSON = (List) jsonObject.get("sign-group"); Set signGroup = new HashSet<>(); for (String name : signGroupFromJSON) { - User user = userService.findUserByUsername(name); - signGroup.add(user); + Optional user = userService.findUserByUsername(name); + signGroup.add(user.get()); } activity.setSignGroup(signGroup); List informGroupFromJSON = (List) jsonObject.get("inform-group"); Set informGroup = new HashSet<>(); for (String name : informGroupFromJSON) { - User user = userService.findUserByUsername(name); - informGroup.add(user); + Optional user = userService.findUserByUsername(name); + informGroup.add(user.get()); } activity.setInformGroup(informGroup); List visibleGroupFromJSON = (List) jsonObject.get("visible-group"); Set visibleGroup = new HashSet<>(); for (String name : visibleGroupFromJSON) { - User user = userService.findUserByUsername(name); - visibleGroup.add(user); + Optional user = userService.findUserByUsername(name); + visibleGroup.add(user.get()); } activity.setVisibleGroup(informGroup); diff --git a/src/main/java/com/codesdream/ase/exception/DataInvalidFormatException.java b/src/main/java/com/codesdream/ase/exception/DataInvalidFormatException.java index e06394f..b5d4de5 100644 --- a/src/main/java/com/codesdream/ase/exception/DataInvalidFormatException.java +++ b/src/main/java/com/codesdream/ase/exception/DataInvalidFormatException.java @@ -12,4 +12,8 @@ public class DataInvalidFormatException extends RuntimeException { super(); information = e.getMessage(); } + + public DataInvalidFormatException(){ + super(); + } } diff --git a/src/main/java/com/codesdream/ase/model/activity/Period.java b/src/main/java/com/codesdream/ase/model/activity/Period.java index 8064ffc..ae359f7 100644 --- a/src/main/java/com/codesdream/ase/model/activity/Period.java +++ b/src/main/java/com/codesdream/ase/model/activity/Period.java @@ -34,4 +34,8 @@ public class Period { this.endTime = endTime; } + public Period(){ + + } + } From 4b7411f562a37b4fec8f905c6e35c9e2340de475 Mon Sep 17 00:00:00 2001 From: Saturneric Date: Wed, 25 Mar 2020 02:22:11 +0800 Subject: [PATCH 6/9] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E7=AB=AF=E8=BF=90=E8=A1=8C=E7=AB=AF=E5=8F=A3=EF=BC=8C=E9=81=BF?= =?UTF-8?q?=E5=85=8D=E4=B8=8E=E5=85=B6=E4=BB=96=E5=BA=94=E7=94=A8=E7=A8=8B?= =?UTF-8?q?=E5=BA=8F=E5=86=B2=E7=AA=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/codesdream/ase/model/activity/Period.java | 2 +- src/main/resources/application-test.properties | 2 +- src/main/resources/application.properties | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/codesdream/ase/model/activity/Period.java b/src/main/java/com/codesdream/ase/model/activity/Period.java index ae359f7..3e39829 100644 --- a/src/main/java/com/codesdream/ase/model/activity/Period.java +++ b/src/main/java/com/codesdream/ase/model/activity/Period.java @@ -35,7 +35,7 @@ public class Period { } public Period(){ - + } } diff --git a/src/main/resources/application-test.properties b/src/main/resources/application-test.properties index aa149bd..7ff0096 100644 --- a/src/main/resources/application-test.properties +++ b/src/main/resources/application-test.properties @@ -1,4 +1,4 @@ -server.port=8080 +server.port=80 spring.thymeleaf.prefix=classpath:templates/ spring.thymeleaf.suffix=.html diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 0a91e8b..102108f 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,4 +1,4 @@ -server.port=8080 +server.port=80 spring.thymeleaf.prefix=classpath:templates/ spring.thymeleaf.suffix=.html From e8d91a402261ef518a1b315f51496e827d706f4f Mon Sep 17 00:00:00 2001 From: Saturneric Date: Wed, 25 Mar 2020 02:40:38 +0800 Subject: [PATCH 7/9] =?UTF-8?q?=E7=94=B1=E4=BA=8E=E6=9D=83=E9=99=90?= =?UTF-8?q?=E9=97=AE=E9=A2=98=EF=BC=8C=E4=BF=AE=E6=94=B9=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E7=AB=AF=E8=BF=90=E8=A1=8C=E7=AB=AF=E5=8F=A3=E4=B8=BA8081?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/resources/application-test.properties | 2 +- src/main/resources/application.properties | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/resources/application-test.properties b/src/main/resources/application-test.properties index 7ff0096..c9dc072 100644 --- a/src/main/resources/application-test.properties +++ b/src/main/resources/application-test.properties @@ -1,4 +1,4 @@ -server.port=80 +server.port=8081 spring.thymeleaf.prefix=classpath:templates/ spring.thymeleaf.suffix=.html diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 102108f..258e642 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,4 +1,4 @@ -server.port=80 +server.port=8081 spring.thymeleaf.prefix=classpath:templates/ spring.thymeleaf.suffix=.html From f4d00f349f87b25b6d878cdd45bb593d1957c588 Mon Sep 17 00:00:00 2001 From: Saturneric Date: Wed, 25 Mar 2020 15:51:06 +0800 Subject: [PATCH 8/9] =?UTF-8?q?=E6=B7=BB=E5=8A=A0Swagger;=E5=BC=95?= =?UTF-8?q?=E5=85=A5Restful=20API=E6=A0=87=E5=87=86;Exception=E5=BD=92?= =?UTF-8?q?=E7=B1=BB;=E9=94=99=E8=AF=AF=E7=AE=A1=E7=90=86=E5=AD=90?= =?UTF-8?q?=E7=B3=BB=E7=BB=9F=E5=AE=8C=E5=96=84;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 22 ++++- .../QuickJSONRespond.java | 13 ++- .../auth/ASEAccessDeniedHandler.java | 4 +- .../auth/ASEAuthenticationEntryPoint.java | 6 +- .../auth/ASEAuthenticationFailureHandler.java | 5 +- .../auth/ASEAuthenticationSuccessHandler.java | 5 +- .../datamanager/DataExcelGenerator.java | 2 +- .../datamanager/DataExcelReader.java | 1 + .../ase/component/json/model/JsonableTag.java | 41 ++++++++ .../json/model/JsonableUidGetter.java | 6 ++ .../ase/configure/ASESwaggerConfigure.java | 57 +++++++++++ .../configure/CustomWebSecurityConfig.java | 8 +- .../ase/controller/ASEControllerAdvice.java | 32 ++++++- .../ase/controller/ASEErrorController.java | 12 +-- .../ase/controller/LoginController.java | 13 +-- .../ase/controller/PermissionController.java | 94 +++++-------------- .../ase/controller/RegisterController.java | 2 +- .../exception/DataFileNotFoundException.java | 15 --- .../notfound/DataFileNotFoundException.java | 15 +++ .../exception/notfound/NotFoundException.java | 12 +++ .../notfound/TagNotFoundException.java | 11 +++ .../{ => notfound}/UserNotFoundException.java | 10 +- .../ase/service/ASEUserDetailsService.java | 3 +- .../codesdream/ase/service/UserService.java | 2 +- src/main/resources/application-dev.properties | 23 +++++ 25 files changed, 275 insertions(+), 139 deletions(-) rename src/main/java/com/codesdream/ase/component/{datamanager => api}/QuickJSONRespond.java (85%) create mode 100644 src/main/java/com/codesdream/ase/component/json/model/JsonableTag.java create mode 100644 src/main/java/com/codesdream/ase/component/json/model/JsonableUidGetter.java create mode 100644 src/main/java/com/codesdream/ase/configure/ASESwaggerConfigure.java delete mode 100644 src/main/java/com/codesdream/ase/exception/DataFileNotFoundException.java create mode 100644 src/main/java/com/codesdream/ase/exception/notfound/DataFileNotFoundException.java create mode 100644 src/main/java/com/codesdream/ase/exception/notfound/NotFoundException.java create mode 100644 src/main/java/com/codesdream/ase/exception/notfound/TagNotFoundException.java rename src/main/java/com/codesdream/ase/exception/{ => notfound}/UserNotFoundException.java (56%) create mode 100644 src/main/resources/application-dev.properties diff --git a/pom.xml b/pom.xml index 53a9200..900747a 100644 --- a/pom.xml +++ b/pom.xml @@ -139,11 +139,12 @@ - org.mariadb.jdbc - mariadb-java-client - 2.5.4 - + org.mariadb.jdbc + mariadb-java-client + 2.5.4 + + com.h2database h2 @@ -163,6 +164,19 @@ 3.2.0 + + + io.springfox + springfox-swagger2 + 2.9.2 + + + + io.springfox + springfox-swagger-ui + 2.9.2 + + diff --git a/src/main/java/com/codesdream/ase/component/datamanager/QuickJSONRespond.java b/src/main/java/com/codesdream/ase/component/api/QuickJSONRespond.java similarity index 85% rename from src/main/java/com/codesdream/ase/component/datamanager/QuickJSONRespond.java rename to src/main/java/com/codesdream/ase/component/api/QuickJSONRespond.java index 0838a41..dfe654d 100644 --- a/src/main/java/com/codesdream/ase/component/datamanager/QuickJSONRespond.java +++ b/src/main/java/com/codesdream/ase/component/api/QuickJSONRespond.java @@ -1,5 +1,6 @@ -package com.codesdream.ase.component.datamanager; +package com.codesdream.ase.component.api; +import com.codesdream.ase.component.datamanager.JSONParameter; import com.codesdream.ase.component.json.respond.EmptyDataObjectRespond; import com.codesdream.ase.component.json.respond.JSONBaseRespondObject; import org.springframework.stereotype.Component; @@ -36,6 +37,11 @@ public class QuickJSONRespond { return getJSONStandardRespond(404, "Not Found", info); } + // 获得标准的JSON响应字符串返回(404状态) + public String getRespond404(String info, Object object){ + return getJSONStandardRespond(404, "Not Found", info, object); + } + // 获得标准的JSON响应字符串返回(500状态) public String getRespond500(String info){ return getJSONStandardRespond(500, "Internal Server Error", info); @@ -76,6 +82,11 @@ public class QuickJSONRespond { return getJSONStandardRespond(400, "Bad Request", info); } + // 获得标准的JSON响应字符串返回(404状态) + public String getRespond400(String info, Object object){ + return getJSONStandardRespond(400, "Bad Request", info, object); + } + // 获得标准的JSON响应字符串返回(400状态) public String getRespond409(String info){ return getJSONStandardRespond(409, "Conflict", info); diff --git a/src/main/java/com/codesdream/ase/component/auth/ASEAccessDeniedHandler.java b/src/main/java/com/codesdream/ase/component/auth/ASEAccessDeniedHandler.java index 3ab64a1..0c3350e 100644 --- a/src/main/java/com/codesdream/ase/component/auth/ASEAccessDeniedHandler.java +++ b/src/main/java/com/codesdream/ase/component/auth/ASEAccessDeniedHandler.java @@ -1,8 +1,6 @@ package com.codesdream.ase.component.auth; -import com.codesdream.ase.component.datamanager.JSONParameter; -import com.codesdream.ase.component.datamanager.QuickJSONRespond; -import com.codesdream.ase.component.json.respond.UserLoginCheckerJSONRespond; +import com.codesdream.ase.component.api.QuickJSONRespond; import lombok.extern.slf4j.Slf4j; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.access.AccessDeniedHandler; diff --git a/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationEntryPoint.java b/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationEntryPoint.java index a72840e..296cc2b 100644 --- a/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationEntryPoint.java +++ b/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationEntryPoint.java @@ -1,16 +1,12 @@ package com.codesdream.ase.component.auth; -import com.codesdream.ase.component.datamanager.JSONParameter; -import com.codesdream.ase.component.datamanager.QuickJSONRespond; -import com.codesdream.ase.component.json.respond.JSONBaseRespondObject; -import com.codesdream.ase.component.json.respond.UserLoginCheckerJSONRespond; +import com.codesdream.ase.component.api.QuickJSONRespond; import lombok.extern.slf4j.Slf4j; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; import javax.annotation.Resource; -import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; diff --git a/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationFailureHandler.java b/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationFailureHandler.java index b3a9dae..d90a784 100644 --- a/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationFailureHandler.java +++ b/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationFailureHandler.java @@ -1,16 +1,13 @@ package com.codesdream.ase.component.auth; -import com.codesdream.ase.component.datamanager.JSONParameter; -import com.codesdream.ase.component.datamanager.QuickJSONRespond; +import com.codesdream.ase.component.api.QuickJSONRespond; import com.codesdream.ase.component.json.respond.ErrorInfoJSONRespond; -import com.codesdream.ase.component.json.respond.UserLoginCheckerJSONRespond; import lombok.extern.slf4j.Slf4j; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; import org.springframework.stereotype.Component; import javax.annotation.Resource; -import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; diff --git a/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationSuccessHandler.java b/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationSuccessHandler.java index fcd62e3..f73d445 100644 --- a/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationSuccessHandler.java +++ b/src/main/java/com/codesdream/ase/component/auth/ASEAuthenticationSuccessHandler.java @@ -1,8 +1,6 @@ package com.codesdream.ase.component.auth; -import com.codesdream.ase.component.auth.JSONTokenAuthenticationToken; -import com.codesdream.ase.component.datamanager.JSONParameter; -import com.codesdream.ase.component.datamanager.QuickJSONRespond; +import com.codesdream.ase.component.api.QuickJSONRespond; import com.codesdream.ase.component.json.respond.UserLoginCheckerJSONRespond; import com.codesdream.ase.model.permission.User; @@ -19,7 +17,6 @@ import javax.annotation.Resource; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.Optional; diff --git a/src/main/java/com/codesdream/ase/component/datamanager/DataExcelGenerator.java b/src/main/java/com/codesdream/ase/component/datamanager/DataExcelGenerator.java index 1ca17b2..83c1948 100644 --- a/src/main/java/com/codesdream/ase/component/datamanager/DataExcelGenerator.java +++ b/src/main/java/com/codesdream/ase/component/datamanager/DataExcelGenerator.java @@ -1,6 +1,6 @@ package com.codesdream.ase.component.datamanager; -import com.codesdream.ase.exception.DataFileNotFoundException; +import com.codesdream.ase.exception.notfound.DataFileNotFoundException; import com.codesdream.ase.exception.DataIOException; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; diff --git a/src/main/java/com/codesdream/ase/component/datamanager/DataExcelReader.java b/src/main/java/com/codesdream/ase/component/datamanager/DataExcelReader.java index ae2e2e6..f5471f2 100644 --- a/src/main/java/com/codesdream/ase/component/datamanager/DataExcelReader.java +++ b/src/main/java/com/codesdream/ase/component/datamanager/DataExcelReader.java @@ -2,6 +2,7 @@ package com.codesdream.ase.component.datamanager; import com.codesdream.ase.exception.*; +import com.codesdream.ase.exception.notfound.DataFileNotFoundException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.*; diff --git a/src/main/java/com/codesdream/ase/component/json/model/JsonableTag.java b/src/main/java/com/codesdream/ase/component/json/model/JsonableTag.java new file mode 100644 index 0000000..b5397cd --- /dev/null +++ b/src/main/java/com/codesdream/ase/component/json/model/JsonableTag.java @@ -0,0 +1,41 @@ +package com.codesdream.ase.component.json.model; + +import com.codesdream.ase.model.permission.Tag; +import com.codesdream.ase.model.permission.User; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import net.bytebuddy.implementation.bind.annotation.DefaultMethod; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +@Data +@ApiModel("标签") +public class JsonableTag { + @ApiModelProperty(value = "标签id") + private Integer id = null; + @ApiModelProperty(value = "标签名", example = "系统管理员") + private String name; + @ApiModelProperty(value = "标签说明", example = "该系统的管理员") + private String description; + @ApiModelProperty(value = "用户列表", hidden = true) + private Set users = new HashSet<>(); + + public JsonableTag(){ + + } + + public JsonableTag(Tag tag){ + this.id = tag.getId(); + this.name = tag.getName(); + this.description = tag.getDescription(); + // 构建用户的ID列表 + for(User user : tag.getUsers()) { + users.add(user.getId()); + } + } + +} diff --git a/src/main/java/com/codesdream/ase/component/json/model/JsonableUidGetter.java b/src/main/java/com/codesdream/ase/component/json/model/JsonableUidGetter.java new file mode 100644 index 0000000..9eee677 --- /dev/null +++ b/src/main/java/com/codesdream/ase/component/json/model/JsonableUidGetter.java @@ -0,0 +1,6 @@ +package com.codesdream.ase.component.json.model; + +public class JsonableUidGetter { + private String checkType; + private String username; +} diff --git a/src/main/java/com/codesdream/ase/configure/ASESwaggerConfigure.java b/src/main/java/com/codesdream/ase/configure/ASESwaggerConfigure.java new file mode 100644 index 0000000..1e2061e --- /dev/null +++ b/src/main/java/com/codesdream/ase/configure/ASESwaggerConfigure.java @@ -0,0 +1,57 @@ +package com.codesdream.ase.configure; + +import com.google.common.collect.Sets; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.core.parameters.P; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.ParameterBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.schema.ModelRef; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Parameter; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +@Configuration +@EnableSwagger2 +public class ASESwaggerConfigure { + @Bean + public Docket createRestApi() { + + List pars = new ArrayList(); + + pars.add(new ParameterBuilder().name("username").description("真实用户名").hidden(true).order(1) + .modelRef(new ModelRef("string")).parameterType("header") + .required(false).defaultValue("u_id_88883b9e023c8824310760d8bb8b6542e5a3f16a0d67253214e01ee7ab0e96a1").build()); + pars.add(new ParameterBuilder().name("signed").description("客户端签名").hidden(true).order(2) + .modelRef(new ModelRef("string")).parameterType("header") + .required(false).defaultValue("6d4923fca4dcb51f67b85e54a23a8d763d9e02af").build()); + pars.add(new ParameterBuilder().name("timestamp").description("时间戳").hidden(true).order(3) + .modelRef(new ModelRef("string")).parameterType("header") + .required(false).defaultValue(Long.toString(new Date().getTime())).build()); + + return new Docket(DocumentationType.SWAGGER_2) + .protocols(Sets.newHashSet("http")) + .apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.basePackage("com.codesdream.ase.controller")) + .paths(PathSelectors.any()) + .build() + .globalOperationParameters(pars); + } + + private ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("全员育人管理系统后端接口定义") + .version("0.0.1") + .description("用于对后端接口进行说明") + .build(); + } +} diff --git a/src/main/java/com/codesdream/ase/configure/CustomWebSecurityConfig.java b/src/main/java/com/codesdream/ase/configure/CustomWebSecurityConfig.java index 96d414a..b2d3413 100644 --- a/src/main/java/com/codesdream/ase/configure/CustomWebSecurityConfig.java +++ b/src/main/java/com/codesdream/ase/configure/CustomWebSecurityConfig.java @@ -87,7 +87,13 @@ public class CustomWebSecurityConfig extends WebSecurityConfigurerAdapter { "/forget/**", "/not_found/**", "/error/**", - "/login/**"); + "/login/**", + "/swagger-ui.html", + "/webjars/**", + "/swagger-resources/**", + "/v2/api-docs", + "/configuration/ui", + "/configuration/security"); } //注册自定义的UsernamePasswordAuthenticationFilter diff --git a/src/main/java/com/codesdream/ase/controller/ASEControllerAdvice.java b/src/main/java/com/codesdream/ase/controller/ASEControllerAdvice.java index 332f5ba..755d930 100644 --- a/src/main/java/com/codesdream/ase/controller/ASEControllerAdvice.java +++ b/src/main/java/com/codesdream/ase/controller/ASEControllerAdvice.java @@ -1,7 +1,11 @@ package com.codesdream.ase.controller; +import com.codesdream.ase.component.api.QuickJSONRespond; import com.codesdream.ase.component.error.ErrorResponse; import com.codesdream.ase.component.json.respond.ErrorInfoJSONRespond; +import com.codesdream.ase.exception.notfound.NotFoundException; +import com.sun.xml.bind.v2.model.annotation.Quick; +import org.apache.poi.openxml4j.opc.internal.ContentType; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationServiceException; @@ -11,21 +15,39 @@ import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.context.request.WebRequest; +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.Date; import java.util.List; @RestControllerAdvice public class ASEControllerAdvice { - @ExceptionHandler(value = {RuntimeException.class}) - public final Object handleRuntimeException(RuntimeException e, WebRequest webRequest){ + + @Resource + private QuickJSONRespond quickJSONRespond; + + @ExceptionHandler(value = {NullPointerException.class}) + public ResponseEntity handleBadRequest(Exception ex) { + + String json = quickJSONRespond.getRespond400(null, getJSONRespondObject(ex)); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(json); + } + + @ExceptionHandler(value = {NotFoundException.class}) + public ResponseEntity handleNotFound(Exception ex) { + String json = quickJSONRespond.getRespond404(null, getJSONRespondObject(ex)); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(json); + } + + private Object getJSONRespondObject(Exception ex){ ErrorInfoJSONRespond errorInfoJSONRespond = new ErrorInfoJSONRespond(); + errorInfoJSONRespond.setException(ex.getClass().getName()); + errorInfoJSONRespond.setExceptionMessage(ex.getMessage()); errorInfoJSONRespond.setDate(new Date()); - errorInfoJSONRespond.setExceptionMessage(e.getMessage()); - errorInfoJSONRespond.setException(e.getClass().getName()); return errorInfoJSONRespond; } - } diff --git a/src/main/java/com/codesdream/ase/controller/ASEErrorController.java b/src/main/java/com/codesdream/ase/controller/ASEErrorController.java index ab33dc1..23d166d 100644 --- a/src/main/java/com/codesdream/ase/controller/ASEErrorController.java +++ b/src/main/java/com/codesdream/ase/controller/ASEErrorController.java @@ -1,24 +1,16 @@ package com.codesdream.ase.controller; -import com.codesdream.ase.component.datamanager.QuickJSONRespond; -import com.codesdream.ase.component.error.ErrorResponse; +import com.codesdream.ase.component.api.QuickJSONRespond; import com.codesdream.ase.component.json.respond.ErrorInfoJSONRespond; import org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.context.request.WebRequest; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; -import java.util.ArrayList; import java.util.Date; -import java.util.List; @Controller public class ASEErrorController implements ErrorController { @@ -80,7 +72,7 @@ public class ASEErrorController implements ErrorController { return quickJSONRespond.getJSONStandardRespond( statusCode, - "Error Controller Handle", + "Internal Server Error", null, errorInfoJSONRespond); } diff --git a/src/main/java/com/codesdream/ase/controller/LoginController.java b/src/main/java/com/codesdream/ase/controller/LoginController.java index 36f7522..fc3a5ce 100644 --- a/src/main/java/com/codesdream/ase/controller/LoginController.java +++ b/src/main/java/com/codesdream/ase/controller/LoginController.java @@ -2,15 +2,17 @@ package com.codesdream.ase.controller; import com.alibaba.fastjson.JSONObject; import com.codesdream.ase.component.datamanager.JSONParameter; -import com.codesdream.ase.component.datamanager.QuickJSONRespond; +import com.codesdream.ase.component.api.QuickJSONRespond; import com.codesdream.ase.component.json.respond.JSONStandardFailedRespond; import com.codesdream.ase.component.json.request.UserLoginChecker; import com.codesdream.ase.component.json.respond.UserLoginCheckerJSONRespond; import com.codesdream.ase.service.IAuthService; import com.codesdream.ase.service.IUserService; +import io.swagger.annotations.Api; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @@ -25,6 +27,7 @@ import java.util.Optional; */ @Slf4j @Controller +@Api(tags = "用户登录有关接口") public class LoginController { @Resource @@ -39,13 +42,7 @@ public class LoginController { @Resource private IAuthService authService; - - @RequestMapping(value = "/login") - String printLogin(Model model) { - return "login"; - } - - @RequestMapping(value = "/login/check_exists", method = RequestMethod.POST) + @PostMapping(value = "/login/check_exists") @ResponseBody String checkExists(HttpServletRequest request){ diff --git a/src/main/java/com/codesdream/ase/controller/PermissionController.java b/src/main/java/com/codesdream/ase/controller/PermissionController.java index 358e3a2..d702bee 100644 --- a/src/main/java/com/codesdream/ase/controller/PermissionController.java +++ b/src/main/java/com/codesdream/ase/controller/PermissionController.java @@ -2,16 +2,19 @@ package com.codesdream.ase.controller; import com.alibaba.fastjson.JSONObject; import com.codesdream.ase.component.datamanager.JSONParameter; -import com.codesdream.ase.component.datamanager.QuickJSONRespond; +import com.codesdream.ase.component.api.QuickJSONRespond; +import com.codesdream.ase.component.json.model.JsonableTag; import com.codesdream.ase.component.json.respond.PermissionJSONRespond; +import com.codesdream.ase.exception.notfound.TagNotFoundException; import com.codesdream.ase.model.permission.Tag; import com.codesdream.ase.model.permission.User; import com.codesdream.ase.service.IUserService; import com.codesdream.ase.service.PermissionService; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; @@ -21,6 +24,7 @@ import java.util.Set; @RestController @RequestMapping("pmt") +@Api(tags = "权限管理接口") public class PermissionController { @Resource @@ -36,80 +40,34 @@ public class PermissionController { private QuickJSONRespond jsonRespond; // 根据名字创建新的标签 - @PostMapping("tag/create") - public String createTag(HttpServletRequest request){ - Optional jsonObjectOptional = jsonParameter.getJSONByRequest(request); - if(!jsonObjectOptional.isPresent()) return jsonRespond.getRespond400("Illegal JSON Format"); - JSONObject jsonObject = jsonObjectOptional.get(); + @PostMapping("tag") + @ApiOperation(value = "创建新的标签", notes = "创建标签时其ID自动分配,指定ID无效") + public JsonableTag createTag(@RequestBody JsonableTag tag){ + + String tagName = tag.getName(); +/* if(tagName == null) return jsonRespond.getRespond406("Missing Tag Name");*/ - String tagName = jsonObject.getString("name"); - if(tagName == null) return jsonRespond.getRespond406("Missing Tag Name"); - // 检查JSON是否合法 Optional tagOptional = permissionService.findTag(tagName); - if(tagOptional.isPresent()) return jsonRespond.getRespond409("Tag Name Already Exist"); +/* if(tagOptional.isPresent()) return jsonRespond.getRespond409("Tag Name Already Exist");*/ Tag newTag = permissionService.getDefaultTag(tagName); - newTag = permissionService.save(newTag); - - PermissionJSONRespond respond = new PermissionJSONRespond(); - respond.setActionSuccess(true); - respond.setTagId(newTag.getId()); - respond.setTagName(newTag.getName()); - - return jsonRespond.getRespond200(null, respond); + if(tag.getDescription() != null) { + newTag.setDescription(tag.getDescription()); + } + return new JsonableTag(permissionService.save(newTag)); } // 根据名字搜索标签的简要信息 - @PostMapping("tag/search") - public String checkTag(HttpServletRequest request){ - Optional jsonObjectOptional = jsonParameter.getJSONByRequest(request); - if(!jsonObjectOptional.isPresent()) return jsonRespond.getRespond400("Illegal JSON Format"); - - JSONObject jsonObject = jsonObjectOptional.get(); - String tagName = jsonObject.getString("name"); - if(tagName == null) return jsonRespond.getRespond406("Problem With Tag Name"); - Optional tagOptional = permissionService.findTag(tagName); - - PermissionJSONRespond respond = new PermissionJSONRespond(); - respond.setActionSuccess(true); - + @GetMapping("tag") + @ApiOperation("搜索标签信息") + @ApiImplicitParam(name = "name", value = "标签名") + public JsonableTag checkTag(@RequestParam(value = "name") String name){ + Optional tagOptional = permissionService.findTag(name); if(tagOptional.isPresent()){ - respond.setTagExist(true); - respond.setTagId(tagOptional.get().getId()); - respond.setTagName(tagOptional.get().getName()); + return new JsonableTag(tagOptional.get()); } - else respond.setTagExist(false); - - return jsonRespond.getRespond200(null, respond); - } - - // 由标签ID找到用户ID列表 - @PostMapping("tag/get/users") - public String getUsersTag(HttpServletRequest request){ - Optional jsonObjectOptional = jsonParameter.getJSONByRequest(request); - if(!jsonObjectOptional.isPresent()) return jsonRespond.getRespond400("Illegal JSON Format"); - - JSONObject jsonObject = jsonObjectOptional.get(); - Integer tagId = jsonObject.getInteger("id"); - if(tagId == null) return jsonRespond.getRespond406("Problem With Tag ID"); - Optional tagOptional = permissionService.findTag(tagId); - - PermissionJSONRespond respond = new PermissionJSONRespond(); - respond.setActionSuccess(true); - - if(tagOptional.isPresent()){ - respond.setTagExist(true); - respond.setTagId(tagOptional.get().getId()); - Set userIds = new HashSet<>(); - for(User user : permissionService.getUsersFromTag(tagOptional.get())) { - userIds.add(user.getId()); - } - respond.setUsers(userIds); - } - else respond.setTagExist(false); - - return jsonRespond.getRespond200(null, respond); + else throw new TagNotFoundException(name); } // 将用户添加到Tag中 diff --git a/src/main/java/com/codesdream/ase/controller/RegisterController.java b/src/main/java/com/codesdream/ase/controller/RegisterController.java index 88b4827..0908a34 100644 --- a/src/main/java/com/codesdream/ase/controller/RegisterController.java +++ b/src/main/java/com/codesdream/ase/controller/RegisterController.java @@ -1,7 +1,7 @@ package com.codesdream.ase.controller; import com.codesdream.ase.component.datamanager.JSONParameter; -import com.codesdream.ase.component.datamanager.QuickJSONRespond; +import com.codesdream.ase.component.api.QuickJSONRespond; import com.codesdream.ase.component.json.request.UserRegisterChecker; import com.codesdream.ase.model.information.BaseStudentInfo; import com.codesdream.ase.model.permission.User; diff --git a/src/main/java/com/codesdream/ase/exception/DataFileNotFoundException.java b/src/main/java/com/codesdream/ase/exception/DataFileNotFoundException.java deleted file mode 100644 index c85958a..0000000 --- a/src/main/java/com/codesdream/ase/exception/DataFileNotFoundException.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.codesdream.ase.exception; - -import lombok.Data; -import lombok.EqualsAndHashCode; - -@EqualsAndHashCode(callSuper = true) -@Data -public class DataFileNotFoundException extends RuntimeException { - private String path; - - public DataFileNotFoundException(String filePath){ - super(); - this.path = filePath; - } -} diff --git a/src/main/java/com/codesdream/ase/exception/notfound/DataFileNotFoundException.java b/src/main/java/com/codesdream/ase/exception/notfound/DataFileNotFoundException.java new file mode 100644 index 0000000..6ff26be --- /dev/null +++ b/src/main/java/com/codesdream/ase/exception/notfound/DataFileNotFoundException.java @@ -0,0 +1,15 @@ +package com.codesdream.ase.exception.notfound; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +@EqualsAndHashCode(callSuper = true) +@Data +public class DataFileNotFoundException extends NotFoundException { + private String path; + + public DataFileNotFoundException(String msg){ + super(msg); + this.path = msg; + } +} diff --git a/src/main/java/com/codesdream/ase/exception/notfound/NotFoundException.java b/src/main/java/com/codesdream/ase/exception/notfound/NotFoundException.java new file mode 100644 index 0000000..a632648 --- /dev/null +++ b/src/main/java/com/codesdream/ase/exception/notfound/NotFoundException.java @@ -0,0 +1,12 @@ +package com.codesdream.ase.exception.notfound; + + +public class NotFoundException extends RuntimeException { + public NotFoundException(String msg){ + super(msg); + } + + public NotFoundException(){ + super(); + } +} diff --git a/src/main/java/com/codesdream/ase/exception/notfound/TagNotFoundException.java b/src/main/java/com/codesdream/ase/exception/notfound/TagNotFoundException.java new file mode 100644 index 0000000..a7509ac --- /dev/null +++ b/src/main/java/com/codesdream/ase/exception/notfound/TagNotFoundException.java @@ -0,0 +1,11 @@ +package com.codesdream.ase.exception.notfound; + + +public class TagNotFoundException extends NotFoundException { + String tagName; + + public TagNotFoundException(String tagName){ + super(tagName); + this.tagName = tagName; + } +} diff --git a/src/main/java/com/codesdream/ase/exception/UserNotFoundException.java b/src/main/java/com/codesdream/ase/exception/notfound/UserNotFoundException.java similarity index 56% rename from src/main/java/com/codesdream/ase/exception/UserNotFoundException.java rename to src/main/java/com/codesdream/ase/exception/notfound/UserNotFoundException.java index c721ae9..65a58c0 100644 --- a/src/main/java/com/codesdream/ase/exception/UserNotFoundException.java +++ b/src/main/java/com/codesdream/ase/exception/notfound/UserNotFoundException.java @@ -1,22 +1,20 @@ -package com.codesdream.ase.exception; +package com.codesdream.ase.exception.notfound; import lombok.Data; import lombok.EqualsAndHashCode; @EqualsAndHashCode(callSuper = true) @Data -public class UserNotFoundException extends RuntimeException { +public class UserNotFoundException extends NotFoundException { Integer id; String username; - String message; public UserNotFoundException(Integer id, String username){ super(); this.id = id; this.username = username; } - public UserNotFoundException(String message){ - super(); - this.message = message; + public UserNotFoundException(String msg){ + super(msg); } } diff --git a/src/main/java/com/codesdream/ase/service/ASEUserDetailsService.java b/src/main/java/com/codesdream/ase/service/ASEUserDetailsService.java index 7778168..6aae6c0 100644 --- a/src/main/java/com/codesdream/ase/service/ASEUserDetailsService.java +++ b/src/main/java/com/codesdream/ase/service/ASEUserDetailsService.java @@ -1,12 +1,11 @@ package com.codesdream.ase.service; import com.codesdream.ase.component.permission.UserAuthoritiesGenerator; -import com.codesdream.ase.exception.UserNotFoundException; +import com.codesdream.ase.exception.notfound.UserNotFoundException; import com.codesdream.ase.model.permission.User; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import javax.annotation.Resource; diff --git a/src/main/java/com/codesdream/ase/service/UserService.java b/src/main/java/com/codesdream/ase/service/UserService.java index faae155..3fd26b1 100644 --- a/src/main/java/com/codesdream/ase/service/UserService.java +++ b/src/main/java/com/codesdream/ase/service/UserService.java @@ -4,7 +4,7 @@ import com.codesdream.ase.component.auth.ASEPasswordEncoder; import com.codesdream.ase.component.auth.ASEUsernameEncoder; import com.codesdream.ase.component.permission.UserRolesListGenerator; import com.codesdream.ase.exception.UserInformationIllegalException; -import com.codesdream.ase.exception.UserNotFoundException; +import com.codesdream.ase.exception.notfound.UserNotFoundException; import com.codesdream.ase.exception.UsernameAlreadyExistException; import com.codesdream.ase.model.information.BaseStudentInfo; import com.codesdream.ase.model.permission.User; diff --git a/src/main/resources/application-dev.properties b/src/main/resources/application-dev.properties new file mode 100644 index 0000000..240adf1 --- /dev/null +++ b/src/main/resources/application-dev.properties @@ -0,0 +1,23 @@ +server.port=8081 + +spring.thymeleaf.prefix=classpath:templates/ +spring.thymeleaf.suffix=.html +spring.thymeleaf.mode=HTML +spring.thymeleaf.encoding=UTF-8 + +spring.jpa.generate-ddl=false +spring.jpa.show-sql=true +spring.jpa.hibernate.ddl-auto=update +spring.jooq.sql-dialect=org.hibernate.dialect.MariaDB102Dialect +spring.jpa.open-in-view=true +spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true + +spring.datasource.url=jdbc:mariadb://localhost:3306/ase?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC +spring.datasource.username=root +spring.datasource.password=#a9b9fa6422 +spring.datasource.driver-class-name=org.mariadb.jdbc.Driver + +server.error.whitelabel.enabled=false + +logging.level.root=info +logging.level.org.springframework.security=info \ No newline at end of file From e09f373fc0230c67d688d5911828662cc87ca090 Mon Sep 17 00:00:00 2001 From: Saturneric Date: Thu, 26 Mar 2020 01:28:22 +0800 Subject: [PATCH 9/9] =?UTF-8?q?=E7=BC=96=E5=86=99=E6=A0=87=E7=AD=BE?= =?UTF-8?q?=E7=9B=B8=E5=85=B3=E6=8E=A5=E5=8F=A3;=E5=AE=8C=E5=96=84?= =?UTF-8?q?=E7=94=A8=E6=88=B7=E7=AE=A1=E7=90=86=E6=9C=8D=E5=8A=A1=E5=B1=82?= =?UTF-8?q?;=E5=AE=8C=E5=96=84=E6=9D=83=E9=99=90=E7=AE=A1=E7=90=86?= =?UTF-8?q?=E6=9C=8D=E5=8A=A1=E5=B1=82;=E5=AE=8C=E5=96=84=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E7=AE=A1=E7=90=86=E5=AD=90=E7=B3=BB=E7=BB=9F;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ase/component/api/QuickJSONRespond.java | 50 +++++-- .../ase/component/json/model/JsonableTag.java | 11 +- .../json/model/JsonableTagUserList.java | 26 ++++ .../component/json/model/JsonableUser.java | 19 +++ .../ase/controller/ASEControllerAdvice.java | 45 +++--- .../ase/controller/PermissionController.java | 133 ++++++++++++++---- .../badrequest/AlreadyExistException.java | 14 ++ .../BaseInformationAlreadyExistException.java | 6 +- .../UsernameAlreadyExistException.java | 6 +- .../RelatedObjectsExistException.java | 13 ++ .../BaseInformationNotFoundException.java} | 8 +- .../ase/service/BaseInformationService.java | 22 +-- .../ase/service/IPermissionService.java | 8 ++ .../codesdream/ase/service/IUserService.java | 3 + .../ase/service/PermissionService.java | 22 +++ .../codesdream/ase/service/UserService.java | 18 ++- 16 files changed, 313 insertions(+), 91 deletions(-) create mode 100644 src/main/java/com/codesdream/ase/component/json/model/JsonableTagUserList.java create mode 100644 src/main/java/com/codesdream/ase/component/json/model/JsonableUser.java create mode 100644 src/main/java/com/codesdream/ase/exception/badrequest/AlreadyExistException.java rename src/main/java/com/codesdream/ase/exception/{ => badrequest}/BaseInformationAlreadyExistException.java (61%) rename src/main/java/com/codesdream/ase/exception/{ => badrequest}/UsernameAlreadyExistException.java (59%) create mode 100644 src/main/java/com/codesdream/ase/exception/conflict/RelatedObjectsExistException.java rename src/main/java/com/codesdream/ase/exception/{BaseInformationNotExistException.java => notfound/BaseInformationNotFoundException.java} (50%) diff --git a/src/main/java/com/codesdream/ase/component/api/QuickJSONRespond.java b/src/main/java/com/codesdream/ase/component/api/QuickJSONRespond.java index dfe654d..be125bf 100644 --- a/src/main/java/com/codesdream/ase/component/api/QuickJSONRespond.java +++ b/src/main/java/com/codesdream/ase/component/api/QuickJSONRespond.java @@ -3,6 +3,8 @@ package com.codesdream.ase.component.api; import com.codesdream.ase.component.datamanager.JSONParameter; import com.codesdream.ase.component.json.respond.EmptyDataObjectRespond; import com.codesdream.ase.component.json.respond.JSONBaseRespondObject; +import com.sun.deploy.net.HttpResponse; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import javax.annotation.Resource; @@ -23,6 +25,33 @@ public class QuickJSONRespond { return jsonParameter.getJSONString(respondObject); } + // 根据对象构造获得标准的JSON响应字符串返回 + public String getJSONStandardRespond(HttpStatus status, Object dataObject){ + JSONBaseRespondObject respondObject = new JSONBaseRespondObject(status.value(), status.getReasonPhrase()); + + respondObject.setData(dataObject); + return jsonParameter.getJSONString(respondObject); + } + + // 根据对象构造获得标准的JSON响应字符串返回 + public String getJSONStandardRespond(HttpStatus status, String info, Object dataObject){ + JSONBaseRespondObject respondObject = new JSONBaseRespondObject(status.value(), status.getReasonPhrase()); + if(info != null) respondObject.setInfo(info); + else respondObject.setInfo(null); + + respondObject.setData(dataObject); + return jsonParameter.getJSONString(respondObject); + } + + // 根据对象构造获得标准的JSON响应字符串返回 + public String getJSONStandardRespond(HttpStatus status, String info){ + JSONBaseRespondObject respondObject = new JSONBaseRespondObject(status.value(), status.getReasonPhrase()); + if(info != null) respondObject.setInfo(info); + else respondObject.setInfo(null); + + return jsonParameter.getJSONString(respondObject); + } + // 获得标准的JSON响应字符串返回特定状态码的和解释息 public String getJSONStandardRespond(Integer code, String msg, String info){ JSONBaseRespondObject respondObject = new JSONBaseRespondObject(code, msg); @@ -34,37 +63,42 @@ public class QuickJSONRespond { // 获得标准的JSON响应字符串返回(404状态) public String getRespond404(String info){ - return getJSONStandardRespond(404, "Not Found", info); + return getJSONStandardRespond(HttpStatus.NOT_FOUND, info); } // 获得标准的JSON响应字符串返回(404状态) public String getRespond404(String info, Object object){ - return getJSONStandardRespond(404, "Not Found", info, object); + return getJSONStandardRespond(HttpStatus.NOT_FOUND, info, object); } // 获得标准的JSON响应字符串返回(500状态) public String getRespond500(String info){ - return getJSONStandardRespond(500, "Internal Server Error", info); + return getJSONStandardRespond(HttpStatus.INTERNAL_SERVER_ERROR, info); } // 获得标准的JSON响应字符串返回(200状态) public String getRespond200(String info){ - return getJSONStandardRespond(200, "Ok", info); + return getJSONStandardRespond(HttpStatus.OK, info); } // 获得标准的JSON响应字符串返回(200状态) public String getRespond200(String info, Object object){ - return getJSONStandardRespond(200, "Ok", info, object); + return getJSONStandardRespond(HttpStatus.OK, info, object); } // 获得标准的JSON响应字符串返回(403状态) public String getRespond403(String info){ - return getJSONStandardRespond(403, "Forbidden", info); + return getJSONStandardRespond(HttpStatus.FORBIDDEN, info); } - // 获得标准的JSON响应字符串返回(403状态) + // 获得标准的JSON响应字符串返回(406状态) public String getRespond406(String info){ - return getJSONStandardRespond(406, "Not Acceptable", info); + return getJSONStandardRespond(HttpStatus.NOT_ACCEPTABLE, info); + } + + // 获得标准的JSON响应字符串返回(406状态) + public String getRespond406(String info, Object object){ + return getJSONStandardRespond(HttpStatus.NOT_ACCEPTABLE, info, object); } // 获得标准的JSON响应字符串返回(501态) diff --git a/src/main/java/com/codesdream/ase/component/json/model/JsonableTag.java b/src/main/java/com/codesdream/ase/component/json/model/JsonableTag.java index b5397cd..8db125b 100644 --- a/src/main/java/com/codesdream/ase/component/json/model/JsonableTag.java +++ b/src/main/java/com/codesdream/ase/component/json/model/JsonableTag.java @@ -5,6 +5,7 @@ import com.codesdream.ase.model.permission.User; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; +import lombok.NoArgsConstructor; import net.bytebuddy.implementation.bind.annotation.DefaultMethod; import java.util.ArrayList; @@ -13,6 +14,7 @@ import java.util.List; import java.util.Set; @Data +@NoArgsConstructor @ApiModel("标签") public class JsonableTag { @ApiModelProperty(value = "标签id") @@ -21,21 +23,12 @@ public class JsonableTag { private String name; @ApiModelProperty(value = "标签说明", example = "该系统的管理员") private String description; - @ApiModelProperty(value = "用户列表", hidden = true) - private Set users = new HashSet<>(); - public JsonableTag(){ - - } public JsonableTag(Tag tag){ this.id = tag.getId(); this.name = tag.getName(); this.description = tag.getDescription(); - // 构建用户的ID列表 - for(User user : tag.getUsers()) { - users.add(user.getId()); - } } } diff --git a/src/main/java/com/codesdream/ase/component/json/model/JsonableTagUserList.java b/src/main/java/com/codesdream/ase/component/json/model/JsonableTagUserList.java new file mode 100644 index 0000000..523c61e --- /dev/null +++ b/src/main/java/com/codesdream/ase/component/json/model/JsonableTagUserList.java @@ -0,0 +1,26 @@ +package com.codesdream.ase.component.json.model; + +import com.codesdream.ase.model.permission.Tag; +import com.codesdream.ase.model.permission.User; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +@Data +@NoArgsConstructor +@ApiModel("标签所属用户集合") +public class JsonableTagUserList { + + @ApiModelProperty(name = "用户列表") + private List users; + + + public JsonableTagUserList(Tag tag){ + for(User user : tag.getUsers()){ + users.add(user.getId()); + } + } +} diff --git a/src/main/java/com/codesdream/ase/component/json/model/JsonableUser.java b/src/main/java/com/codesdream/ase/component/json/model/JsonableUser.java new file mode 100644 index 0000000..74f6467 --- /dev/null +++ b/src/main/java/com/codesdream/ase/component/json/model/JsonableUser.java @@ -0,0 +1,19 @@ +package com.codesdream.ase.component.json.model; + +import com.codesdream.ase.model.permission.User; +import io.swagger.annotations.ApiModel; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@ApiModel("用户") +@NoArgsConstructor +public class JsonableUser { + private Integer id; + private String username; + + public JsonableUser(User user){ + this.id = user.getId(); + this.username = user.getUsername(); + } +} diff --git a/src/main/java/com/codesdream/ase/controller/ASEControllerAdvice.java b/src/main/java/com/codesdream/ase/controller/ASEControllerAdvice.java index 755d930..bdddf30 100644 --- a/src/main/java/com/codesdream/ase/controller/ASEControllerAdvice.java +++ b/src/main/java/com/codesdream/ase/controller/ASEControllerAdvice.java @@ -1,26 +1,17 @@ package com.codesdream.ase.controller; import com.codesdream.ase.component.api.QuickJSONRespond; -import com.codesdream.ase.component.error.ErrorResponse; import com.codesdream.ase.component.json.respond.ErrorInfoJSONRespond; +import com.codesdream.ase.exception.badrequest.AlreadyExistException; +import com.codesdream.ase.exception.conflict.RelatedObjectsExistException; import com.codesdream.ase.exception.notfound.NotFoundException; -import com.sun.xml.bind.v2.model.annotation.Quick; -import org.apache.poi.openxml4j.opc.internal.ContentType; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.authentication.AuthenticationServiceException; -import org.springframework.security.core.AuthenticationException; -import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; -import org.springframework.web.context.request.WebRequest; import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.ArrayList; import java.util.Date; -import java.util.List; @RestControllerAdvice public class ASEControllerAdvice { @@ -28,17 +19,37 @@ public class ASEControllerAdvice { @Resource private QuickJSONRespond quickJSONRespond; - @ExceptionHandler(value = {NullPointerException.class}) + @ExceptionHandler(value = { + NullPointerException.class, + AlreadyExistException.class + }) public ResponseEntity handleBadRequest(Exception ex) { - - String json = quickJSONRespond.getRespond400(null, getJSONRespondObject(ex)); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(json); + return getResponse(HttpStatus.BAD_REQUEST, ex); } @ExceptionHandler(value = {NotFoundException.class}) public ResponseEntity handleNotFound(Exception ex) { - String json = quickJSONRespond.getRespond404(null, getJSONRespondObject(ex)); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(json); + + return getResponse(HttpStatus.NOT_FOUND, ex); + } + + @ExceptionHandler(value = {}) + public ResponseEntity handleNotAcceptable(Exception ex) { + return getResponse(HttpStatus.NOT_ACCEPTABLE, ex); + } + + @ExceptionHandler(value = {RelatedObjectsExistException.class}) + public ResponseEntity handleConflict(Exception ex) { + return getResponse(HttpStatus.CONFLICT, ex); + } + + private ResponseEntity getResponse(HttpStatus status, Exception ex){ + return ResponseEntity.status(status).body(getJSON(status, ex)); + + } + + private String getJSON(HttpStatus status, Exception ex){ + return quickJSONRespond.getJSONStandardRespond(status, getJSONRespondObject(ex)); } private Object getJSONRespondObject(Exception ex){ diff --git a/src/main/java/com/codesdream/ase/controller/PermissionController.java b/src/main/java/com/codesdream/ase/controller/PermissionController.java index d702bee..766d619 100644 --- a/src/main/java/com/codesdream/ase/controller/PermissionController.java +++ b/src/main/java/com/codesdream/ase/controller/PermissionController.java @@ -4,7 +4,12 @@ import com.alibaba.fastjson.JSONObject; import com.codesdream.ase.component.datamanager.JSONParameter; import com.codesdream.ase.component.api.QuickJSONRespond; import com.codesdream.ase.component.json.model.JsonableTag; +import com.codesdream.ase.component.json.model.JsonableTagUserList; +import com.codesdream.ase.component.json.model.JsonableUser; import com.codesdream.ase.component.json.respond.PermissionJSONRespond; +import com.codesdream.ase.exception.badrequest.AlreadyExistException; +import com.codesdream.ase.exception.conflict.RelatedObjectsExistException; +import com.codesdream.ase.exception.notfound.NotFoundException; import com.codesdream.ase.exception.notfound.TagNotFoundException; import com.codesdream.ase.model.permission.Tag; import com.codesdream.ase.model.permission.User; @@ -14,11 +19,14 @@ import com.codesdream.ase.service.PermissionService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; +import org.apache.poi.ss.formula.functions.T; +import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.HashSet; +import java.util.List; import java.util.Optional; import java.util.Set; @@ -33,23 +41,14 @@ public class PermissionController { @Resource private IUserService userService; - @Resource - private JSONParameter jsonParameter; - - @Resource - private QuickJSONRespond jsonRespond; - // 根据名字创建新的标签 @PostMapping("tag") + @ResponseStatus(HttpStatus.CREATED) @ApiOperation(value = "创建新的标签", notes = "创建标签时其ID自动分配,指定ID无效") public JsonableTag createTag(@RequestBody JsonableTag tag){ - String tagName = tag.getName(); -/* if(tagName == null) return jsonRespond.getRespond406("Missing Tag Name");*/ - Optional tagOptional = permissionService.findTag(tagName); -/* if(tagOptional.isPresent()) return jsonRespond.getRespond409("Tag Name Already Exist");*/ - + if(tagOptional.isPresent()) throw new AlreadyExistException(tagName); Tag newTag = permissionService.getDefaultTag(tagName); if(tag.getDescription() != null) { newTag.setDescription(tag.getDescription()); @@ -57,9 +56,9 @@ public class PermissionController { return new JsonableTag(permissionService.save(newTag)); } - // 根据名字搜索标签的简要信息 @GetMapping("tag") + @ResponseStatus(HttpStatus.OK) @ApiOperation("搜索标签信息") @ApiImplicitParam(name = "name", value = "标签名") public JsonableTag checkTag(@RequestParam(value = "name") String name){ @@ -67,33 +66,105 @@ public class PermissionController { if(tagOptional.isPresent()){ return new JsonableTag(tagOptional.get()); } - else throw new TagNotFoundException(name); + else throw new NotFoundException(name); } - // 将用户添加到Tag中 - @PostMapping("tag/add/user") - public String addUserTag(HttpServletRequest request){ - Optional jsonObjectOptional = jsonParameter.getJSONByRequest(request); - if(!jsonObjectOptional.isPresent()) return jsonRespond.getRespond400("Illegal JSON Format"); + // 根据名字搜索标签的简要信息 + @GetMapping("tags") + @ResponseStatus(HttpStatus.OK) + @ApiOperation("列出所有的标签信息") + @ApiImplicitParam(name = "name", value = "标签名") + public Set listTag(){ + Iterable tagIterable = permissionService.findAllTag(); + Set jsonableTagSet = new HashSet<>(); + for(Tag tag : tagIterable){ + jsonableTagSet.add(new JsonableTag(tag)); + } + return jsonableTagSet; + } - JSONObject jsonObject = jsonObjectOptional.get(); - Integer tagId = jsonObject.getInteger("tagId"); - Integer userId = jsonObject.getInteger("userId"); + // 根据名字搜索标签的简要信息 + @DeleteMapping("tag") + @ResponseStatus(HttpStatus.NO_CONTENT) + @ApiOperation("删除标签") + @ApiImplicitParam(name = "name", value = "标签名") + public void deleteTag(@RequestParam(value = "name") String name){ + Optional tag = permissionService.findTag(name); + if(!tag.isPresent()) throw new NotFoundException(name); - if(userId == null || tagId == null) - return jsonRespond.getRespond406("Request Violates The Interface Protocol"); + // 检查外键关联 + if(tag.get().getUsers().size() > 0) throw new RelatedObjectsExistException(); + if(tag.get().getPermissionContainersCollections().size() > 0) throw new RelatedObjectsExistException(); - Optional user = userService.findUserById(userId); - if(!user.isPresent()) return jsonRespond.getRespond406("User Not Exist"); + permissionService.delete(tag.get()); + } - Optional tag = permissionService.findTag(tagId); - if(!tag.isPresent()) return jsonRespond.getRespond406("Tag Not Exist"); - // 检查用户是否已经在标签中 - if(tag.get().getUsers().contains(user.get())) return jsonRespond.getRespond409("User Already In The Tag"); - permissionService.addUserToTag(tag.get(), user.get()); + @GetMapping("tag/users") + @ResponseStatus(HttpStatus.OK) + @ApiOperation("搜索单个标签所属用户集合信息") + public JsonableTagUserList getUserTag(@RequestParam(value = "name") String name){ + Optional tag = permissionService.findTag(name); + if(!tag.isPresent()) throw new NotFoundException(name); + return new JsonableTagUserList(tag.get()); + } - return jsonRespond.getRespond200("Add User TO Tag Successful"); + @PutMapping("tag/users") + @ApiOperation("更新索单个标签所属用户集合信息") + public JsonableTagUserList setUserTag(@RequestParam String name, @RequestBody JsonableTagUserList userList){ + Optional tag = permissionService.findTag(name); + if(!tag.isPresent()) throw new NotFoundException(name); + + Set userSet = new HashSet<>(userList.getUsers()); + tag.get().setUsers(userService.findUsersById(userSet)); + + return new JsonableTagUserList(permissionService.save(tag.get())); + } + + @PostMapping("tag/users") + @ApiOperation("更新单个标签所属用户集合中添加一个或多个用户") + public JsonableTagUserList addUserTag(@RequestParam String name, @RequestBody JsonableTagUserList userList){ + Optional tag = permissionService.findTag(name); + if(!tag.isPresent()) throw new NotFoundException(name); + Set newUserSet = userService.findUsersById(new HashSet<>(userList.getUsers())); + + Set userSet = tag.get().getUsers(); + + userSet.addAll(newUserSet); + tag.get().setUsers(userSet); + + return new JsonableTagUserList(permissionService.save(tag.get())); + } + + @DeleteMapping("tag/users") + @ApiOperation("从单个标签所属用户集合中删除一个或多个用户") + @ApiImplicitParam(name = "name", value = "标签名") + public JsonableTagUserList deleteUserTag(@RequestParam String name, @RequestBody JsonableTagUserList userList){ + Optional tag = permissionService.findTag(name); + if(!tag.isPresent()) throw new NotFoundException(name); + Set userSet = tag.get().getUsers(); + Set deleteUserSet = userService.findUsersById(new HashSet<>(userList.getUsers())); + + userSet.removeAll(deleteUserSet); + tag.get().setUsers(userSet); + + return new JsonableTagUserList(permissionService.save(tag.get())); + } + + @GetMapping("tags/users") + @ResponseStatus(HttpStatus.OK) + @ApiOperation("搜索多个标签所属用户集合信息") + public Set getUserTags(@RequestParam(value = "name") List names){ + Set tagSet = permissionService.findTags(names); + Set userSet = new HashSet<>(); + Set jsonableUsers = new HashSet<>(); + for(Tag tag : tagSet){ + userSet.addAll(tag.getUsers()); + } + for(User user : userSet){ + jsonableUsers.add(new JsonableUser(user)); + } + return jsonableUsers; } diff --git a/src/main/java/com/codesdream/ase/exception/badrequest/AlreadyExistException.java b/src/main/java/com/codesdream/ase/exception/badrequest/AlreadyExistException.java new file mode 100644 index 0000000..81fa88b --- /dev/null +++ b/src/main/java/com/codesdream/ase/exception/badrequest/AlreadyExistException.java @@ -0,0 +1,14 @@ +package com.codesdream.ase.exception.badrequest; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; + +@EqualsAndHashCode(callSuper = true) +@Data +@NoArgsConstructor +public class AlreadyExistException extends RuntimeException { + public AlreadyExistException(String msg){ + super(msg); + } +} diff --git a/src/main/java/com/codesdream/ase/exception/BaseInformationAlreadyExistException.java b/src/main/java/com/codesdream/ase/exception/badrequest/BaseInformationAlreadyExistException.java similarity index 61% rename from src/main/java/com/codesdream/ase/exception/BaseInformationAlreadyExistException.java rename to src/main/java/com/codesdream/ase/exception/badrequest/BaseInformationAlreadyExistException.java index 54a564b..47fda13 100644 --- a/src/main/java/com/codesdream/ase/exception/BaseInformationAlreadyExistException.java +++ b/src/main/java/com/codesdream/ase/exception/badrequest/BaseInformationAlreadyExistException.java @@ -1,16 +1,16 @@ -package com.codesdream.ase.exception; +package com.codesdream.ase.exception.badrequest; import lombok.Data; import lombok.EqualsAndHashCode; @EqualsAndHashCode(callSuper = true) @Data -public class BaseInformationAlreadyExistException extends RuntimeException { +public class BaseInformationAlreadyExistException extends AlreadyExistException { private String className; private String value; public BaseInformationAlreadyExistException(Class aClass, String value){ - super(); + super(String.format("%s: %s", aClass.getName(), value)); this.className = aClass.getName(); this.value = value; } diff --git a/src/main/java/com/codesdream/ase/exception/UsernameAlreadyExistException.java b/src/main/java/com/codesdream/ase/exception/badrequest/UsernameAlreadyExistException.java similarity index 59% rename from src/main/java/com/codesdream/ase/exception/UsernameAlreadyExistException.java rename to src/main/java/com/codesdream/ase/exception/badrequest/UsernameAlreadyExistException.java index 634d2e8..c08d0e0 100644 --- a/src/main/java/com/codesdream/ase/exception/UsernameAlreadyExistException.java +++ b/src/main/java/com/codesdream/ase/exception/badrequest/UsernameAlreadyExistException.java @@ -1,16 +1,16 @@ -package com.codesdream.ase.exception; +package com.codesdream.ase.exception.badrequest; import lombok.Data; import lombok.EqualsAndHashCode; @EqualsAndHashCode(callSuper = true) @Data -public class UsernameAlreadyExistException extends RuntimeException { +public class UsernameAlreadyExistException extends AlreadyExistException { String username; public UsernameAlreadyExistException(String username){ - super(); + super(username); this.username = username; } } diff --git a/src/main/java/com/codesdream/ase/exception/conflict/RelatedObjectsExistException.java b/src/main/java/com/codesdream/ase/exception/conflict/RelatedObjectsExistException.java new file mode 100644 index 0000000..48fb482 --- /dev/null +++ b/src/main/java/com/codesdream/ase/exception/conflict/RelatedObjectsExistException.java @@ -0,0 +1,13 @@ +package com.codesdream.ase.exception.conflict; + +import lombok.NoArgsConstructor; + +/** + * 存在与之相关联的对象 + */ +@NoArgsConstructor +public class RelatedObjectsExistException extends RuntimeException { + public RelatedObjectsExistException(String msg){ + super(msg); + } +} diff --git a/src/main/java/com/codesdream/ase/exception/BaseInformationNotExistException.java b/src/main/java/com/codesdream/ase/exception/notfound/BaseInformationNotFoundException.java similarity index 50% rename from src/main/java/com/codesdream/ase/exception/BaseInformationNotExistException.java rename to src/main/java/com/codesdream/ase/exception/notfound/BaseInformationNotFoundException.java index 65da967..961d435 100644 --- a/src/main/java/com/codesdream/ase/exception/BaseInformationNotExistException.java +++ b/src/main/java/com/codesdream/ase/exception/notfound/BaseInformationNotFoundException.java @@ -1,16 +1,16 @@ -package com.codesdream.ase.exception; +package com.codesdream.ase.exception.notfound; import lombok.Data; import lombok.EqualsAndHashCode; @EqualsAndHashCode(callSuper = true) @Data -public class BaseInformationNotExistException extends RuntimeException { +public class BaseInformationNotFoundException extends NotFoundException { private String className; private String value; - public BaseInformationNotExistException(Class baseInformationClass, String value){ - super(); + public BaseInformationNotFoundException(Class baseInformationClass, String value){ + super(String.format("%s: %s", baseInformationClass.getName(), value)); this.className = baseInformationClass.getName(); this.value = value; } diff --git a/src/main/java/com/codesdream/ase/service/BaseInformationService.java b/src/main/java/com/codesdream/ase/service/BaseInformationService.java index 072ec94..ec287a5 100644 --- a/src/main/java/com/codesdream/ase/service/BaseInformationService.java +++ b/src/main/java/com/codesdream/ase/service/BaseInformationService.java @@ -1,9 +1,9 @@ package com.codesdream.ase.service; import com.codesdream.ase.component.datamanager.DataTable; -import com.codesdream.ase.exception.BaseInformationAlreadyExistException; +import com.codesdream.ase.exception.badrequest.BaseInformationAlreadyExistException; import com.codesdream.ase.exception.BaseInformationIllegalException; -import com.codesdream.ase.exception.BaseInformationNotExistException; +import com.codesdream.ase.exception.notfound.BaseInformationNotFoundException; import com.codesdream.ase.model.information.*; import com.codesdream.ase.repository.information.*; import lombok.extern.slf4j.Slf4j; @@ -103,7 +103,7 @@ public class BaseInformationService implements IBaseInformationService { if(administrativeDivision.isPresent()) { return administrativeDivision.get(); } - else throw new BaseInformationNotExistException(BaseAdministrativeDivision.class, name); + else throw new BaseInformationNotFoundException(BaseAdministrativeDivision.class, name); } return administrativeDivision.get(); @@ -114,7 +114,7 @@ public class BaseInformationService implements IBaseInformationService { Optional college = collegeRepository.findByName(name); // 检查 - if(!college.isPresent()) throw new BaseInformationNotExistException(BaseCollege.class, name); + if(!college.isPresent()) throw new BaseInformationNotFoundException(BaseCollege.class, name); return college.get(); } @@ -122,7 +122,7 @@ public class BaseInformationService implements IBaseInformationService { public BaseEthnic findEthnicByName(String name) { Optional ethnic = ethnicRepository.findByName(name); - if(!ethnic.isPresent()) throw new BaseInformationNotExistException(BaseEthnic.class, name); + if(!ethnic.isPresent()) throw new BaseInformationNotFoundException(BaseEthnic.class, name); return ethnic.get(); } @@ -130,7 +130,7 @@ public class BaseInformationService implements IBaseInformationService { public BaseMajor findMajorByName(String name) { Optional major = majorRepository.findByName(name); - if(!major.isPresent()) throw new BaseInformationNotExistException(BaseMajor.class, name); + if(!major.isPresent()) throw new BaseInformationNotFoundException(BaseMajor.class, name); return major.get(); } @@ -139,7 +139,7 @@ public class BaseInformationService implements IBaseInformationService { Optional politicalStatus = politicalStatusRepository.findByName(name); if(!politicalStatus.isPresent()) - throw new BaseInformationNotExistException(BasePoliticalStatus.class, name); + throw new BaseInformationNotFoundException(BasePoliticalStatus.class, name); return politicalStatus.get(); } @@ -148,7 +148,7 @@ public class BaseInformationService implements IBaseInformationService { Optional candidateCategory = candidateCategoryRepository.findByName(name); if(!candidateCategory.isPresent()) - throw new BaseInformationNotExistException(BaseCandidateCategory.class, name); + throw new BaseInformationNotFoundException(BaseCandidateCategory.class, name); return candidateCategory.get(); } @@ -157,7 +157,7 @@ public class BaseInformationService implements IBaseInformationService { Optional studentInfo = studentInfoRepository.findByStudentId(studentId); if(!studentInfo.isPresent()) - throw new BaseInformationNotExistException(BaseStudentInfo.class, studentId); + throw new BaseInformationNotFoundException(BaseStudentInfo.class, studentId); return studentInfo.get(); } @@ -202,7 +202,7 @@ public class BaseInformationService implements IBaseInformationService { row.elementAt(infoIndex.elementAt(7)), row.elementAt(infoIndex.elementAt(8))); save(studentInfo); - } catch (BaseInformationNotExistException e){ + } catch (BaseInformationNotFoundException e){ String log_info = String.format("一项学生信息的某项基本信息未在数据库找到, 该项数据无效." + " %s: %s",e.getClassName(), e.getValue()); log.warn(log_info); @@ -281,7 +281,7 @@ public class BaseInformationService implements IBaseInformationService { public BaseStudentInfo update(BaseStudentInfo baseStudentInfo) { // 更新前检查 if(!checkStudentInfo(baseStudentInfo.getStudentId())) - throw new BaseInformationNotExistException(BaseStudentInfo.class, baseStudentInfo.getStudentId()); + throw new BaseInformationNotFoundException(BaseStudentInfo.class, baseStudentInfo.getStudentId()); return studentInfoRepository.save(baseStudentInfo); } } diff --git a/src/main/java/com/codesdream/ase/service/IPermissionService.java b/src/main/java/com/codesdream/ase/service/IPermissionService.java index fc1cb70..ca8ec6e 100644 --- a/src/main/java/com/codesdream/ase/service/IPermissionService.java +++ b/src/main/java/com/codesdream/ase/service/IPermissionService.java @@ -4,6 +4,7 @@ import com.codesdream.ase.model.permission.*; import javafx.util.Pair; import java.util.Collection; +import java.util.List; import java.util.Optional; import java.util.Set; @@ -23,6 +24,11 @@ public interface IPermissionService { // 查找用户标签 Optional findTag(Integer id); + // 列出所有的标签 + Iterable findAllTag(); + + Set findTags(List names); + // 查找功能性权限容器 Optional findFPC(String name); @@ -95,6 +101,8 @@ public interface IPermissionService { Tag save(Tag tag); + void delete(Tag tag); + FunctionalPermissionContainer save(FunctionalPermissionContainer fpc); ScopePermissionContainer save(ScopePermissionContainer spc); diff --git a/src/main/java/com/codesdream/ase/service/IUserService.java b/src/main/java/com/codesdream/ase/service/IUserService.java index fbd20db..8426fd2 100644 --- a/src/main/java/com/codesdream/ase/service/IUserService.java +++ b/src/main/java/com/codesdream/ase/service/IUserService.java @@ -8,6 +8,7 @@ import org.springframework.security.core.GrantedAuthority; import java.util.Collection; import java.util.List; import java.util.Optional; +import java.util.Set; public interface IUserService { @@ -42,6 +43,8 @@ public interface IUserService { // 更具学号获得对应的用户名 String getUsernameByStudentId(String studentId); + Set findUsersById(Set usersId); + // 随机生成一个用户名 void generateRandomUsername(User user); diff --git a/src/main/java/com/codesdream/ase/service/PermissionService.java b/src/main/java/com/codesdream/ase/service/PermissionService.java index 73ad410..918c7f2 100644 --- a/src/main/java/com/codesdream/ase/service/PermissionService.java +++ b/src/main/java/com/codesdream/ase/service/PermissionService.java @@ -2,6 +2,7 @@ package com.codesdream.ase.service; import com.codesdream.ase.component.permission.UserFPCListGenerator; import com.codesdream.ase.component.permission.UserFSRGenerator; +import com.codesdream.ase.exception.notfound.NotFoundException; import com.codesdream.ase.model.permission.*; import com.codesdream.ase.repository.permission.FunctionalPermissionContainerRepository; import com.codesdream.ase.repository.permission.PermissionContainersCollectionRepository; @@ -68,6 +69,22 @@ public class PermissionService implements IPermissionService { return tagRepository.findById(id); } + @Override + public Iterable findAllTag() { + return tagRepository.findAll(); + } + + @Override + public Set findTags(List names) { + Set tagSet = new HashSet<>(); + for(String name : names){ + Optional tag = findTag(name); + if(!tag.isPresent()) throw new NotFoundException(name); + tagSet.add(tag.get()); + } + return tagSet; + } + @Override public Optional findFPC(String name) { return fpcRepository.findByName(name); @@ -223,6 +240,11 @@ public class PermissionService implements IPermissionService { return tagRepository.save(tag); } + @Override + public void delete(Tag tag) { + tagRepository.delete(tag); + } + @Override public FunctionalPermissionContainer save(FunctionalPermissionContainer fpc) { if(fpcRepository.findByName(fpc.getName()).isPresent()) diff --git a/src/main/java/com/codesdream/ase/service/UserService.java b/src/main/java/com/codesdream/ase/service/UserService.java index 3fd26b1..f4710e4 100644 --- a/src/main/java/com/codesdream/ase/service/UserService.java +++ b/src/main/java/com/codesdream/ase/service/UserService.java @@ -5,7 +5,7 @@ import com.codesdream.ase.component.auth.ASEUsernameEncoder; import com.codesdream.ase.component.permission.UserRolesListGenerator; import com.codesdream.ase.exception.UserInformationIllegalException; import com.codesdream.ase.exception.notfound.UserNotFoundException; -import com.codesdream.ase.exception.UsernameAlreadyExistException; +import com.codesdream.ase.exception.badrequest.UsernameAlreadyExistException; import com.codesdream.ase.model.information.BaseStudentInfo; import com.codesdream.ase.model.permission.User; import com.codesdream.ase.repository.permission.UserRepository; @@ -15,10 +15,7 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import javax.annotation.Resource; -import java.util.Collection; -import java.util.List; -import java.util.Optional; -import java.util.UUID; +import java.util.*; @Service public class UserService implements IUserService { @@ -86,6 +83,17 @@ public class UserService implements IUserService { return usernameEncoder.encode(studentId); } + @Override + public Set findUsersById(Set usersId) { + Set userSet = new HashSet<>(); + for(Integer id : usersId){ + Optional user = findUserById(id); + if(!user.isPresent()) throw new UserNotFoundException(String.format("ID: %d", id)); + userSet.add(user.get()); + } + return userSet; + } + @Override public void generateRandomUsername(User user) { user.setUsername(usernameEncoder.encode(UUID.randomUUID().toString()));