xiatian 13 ore fa
parent
commit
74a54cd580

+ 47 - 51
stmms-web/src/main/java/cn/com/qmth/stmms/api/controller/BaseApiController.java

@@ -18,13 +18,6 @@ import org.apache.commons.lang.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
-import org.springframework.web.bind.annotation.ExceptionHandler;
-import org.springframework.web.bind.annotation.ResponseBody;
-
-import com.qmth.boot.core.exception.StatusException;
 
 import cn.com.qmth.stmms.admin.utils.SessionExamUtils;
 import cn.com.qmth.stmms.api.exception.ApiException;
@@ -33,7 +26,6 @@ import cn.com.qmth.stmms.biz.exam.model.ExamSubject;
 import cn.com.qmth.stmms.biz.exam.service.ExamSubjectService;
 import cn.com.qmth.stmms.biz.school.model.School;
 import cn.com.qmth.stmms.biz.school.service.SchoolService;
-import cn.com.qmth.stmms.common.StatusResponse;
 import cn.com.qmth.stmms.common.controller.BaseController;
 import cn.com.qmth.stmms.common.domain.ApiUser;
 import cn.com.qmth.stmms.common.utils.RequestUtils;
@@ -43,7 +35,7 @@ public class BaseApiController extends BaseController {
 
     protected static final Logger log = LoggerFactory.getLogger(BaseApiController.class);
 
-    private static final String ERROR_MESSAGE_HEADER_KEY = "error-info";
+    // private static final String ERROR_MESSAGE_HEADER_KEY = "error-info";
 
     @Autowired
     private SchoolService schoolService;
@@ -51,48 +43,52 @@ public class BaseApiController extends BaseController {
     @Autowired
     private ExamSubjectService subjectService;
 
-    @ResponseBody
-    @ExceptionHandler(Exception.class)
-    public ResponseEntity<StatusResponse> handleException(Exception e, HttpServletRequest request) {
-        StatusResponse body = new StatusResponse(500, "系统异常");
-        return asResult(e, body, request);
-    }
-
-    @ResponseBody
-    @ExceptionHandler(RuntimeException.class)
-    public ResponseEntity<StatusResponse> handleException(RuntimeException e, HttpServletRequest request,
-            HttpServletResponse response) {
-        StatusResponse body = null;
-
-        if (e instanceof StatusException) {
-            StatusException se = (StatusException) e;
-            body = new StatusResponse(se.getCode(), se.getMessage());
-        } else if (e instanceof ApiException) {
-            response.addHeader(ERROR_MESSAGE_HEADER_KEY, StringUtils.trimToEmpty(e.getMessage()));
-            ApiException teme = (ApiException) e;
-            try {
-                response.sendError(teme.getCode());
-                body = new StatusResponse(teme.getCode(), teme.getMessage());
-            } catch (IOException e1) {
-                log.error("api response senderror", e);
-            }
-        } else {
-            body = new StatusResponse(500, "系统异常");
-        }
-
-        return asResult(e, body, request);
-    }
-
-    private ResponseEntity<StatusResponse> asResult(Throwable err, StatusResponse body, HttpServletRequest request) {
-
-        HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
-
-        log.error(err.getMessage(), err);
-
-        HttpHeaders headers = new HttpHeaders();
-        headers.add("Content-Type", "application/json;charset=utf-8");
-        return new ResponseEntity<>(body, headers, httpStatus);
-    }
+    // @ResponseBody
+    // @ExceptionHandler(Exception.class)
+    // public ResponseEntity<StatusResponse> handleException(Exception e,
+    // HttpServletRequest request) {
+    // StatusResponse body = new StatusResponse(500, "系统异常");
+    // return asResult(e, body, request);
+    // }
+    //
+    // @ResponseBody
+    // @ExceptionHandler(RuntimeException.class)
+    // public ResponseEntity<StatusResponse> handleException(RuntimeException e,
+    // HttpServletRequest request,
+    // HttpServletResponse response) {
+    // StatusResponse body = null;
+    //
+    // if (e instanceof StatusException) {
+    // StatusException se = (StatusException) e;
+    // body = new StatusResponse(se.getCode(), se.getMessage());
+    // } else if (e instanceof ApiException) {
+    // response.addHeader(ERROR_MESSAGE_HEADER_KEY,
+    // StringUtils.trimToEmpty(e.getMessage()));
+    // ApiException teme = (ApiException) e;
+    // try {
+    // response.sendError(teme.getCode());
+    // body = new StatusResponse(teme.getCode(), teme.getMessage());
+    // } catch (IOException e1) {
+    // log.error("api response senderror", e);
+    // }
+    // } else {
+    // body = new StatusResponse(500, "系统异常");
+    // }
+    //
+    // return asResult(e, body, request);
+    // }
+    //
+    // private ResponseEntity<StatusResponse> asResult(Throwable err,
+    // StatusResponse body, HttpServletRequest request) {
+    //
+    // HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
+    //
+    // log.error(err.getMessage(), err);
+    //
+    // HttpHeaders headers = new HttpHeaders();
+    // headers.add("Content-Type", "application/json;charset=utf-8");
+    // return new ResponseEntity<>(body, headers, httpStatus);
+    // }
 
     protected void exportFile(String fileName, File file, HttpServletResponse response) {
         OutputStream out = null;

+ 60 - 70
stmms-web/src/main/java/cn/com/qmth/stmms/api/interceptor/ApiInterceptor.java

@@ -1,5 +1,16 @@
 package cn.com.qmth.stmms.api.interceptor;
 
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.method.HandlerMethod;
+import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
 import cn.com.qmth.stmms.api.exception.ApiException;
 import cn.com.qmth.stmms.biz.basic.service.PrivilegeService;
 import cn.com.qmth.stmms.biz.basic.service.RolePrivilegeService;
@@ -12,24 +23,12 @@ import cn.com.qmth.stmms.common.annotation.RoleRequire;
 import cn.com.qmth.stmms.common.authorization.AuthorizationService;
 import cn.com.qmth.stmms.common.domain.ApiUser;
 import cn.com.qmth.stmms.common.domain.AuthInfo;
-import cn.com.qmth.stmms.common.domain.WebUser;
 import cn.com.qmth.stmms.common.enums.Role;
 import cn.com.qmth.stmms.common.session.service.SessionService;
 import cn.com.qmth.stmms.common.signature.SignatureInfo;
 import cn.com.qmth.stmms.common.signature.SignatureType;
 import cn.com.qmth.stmms.common.utils.EncryptUtils;
 import cn.com.qmth.stmms.common.utils.RequestUtils;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import org.apache.commons.lang.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.method.HandlerMethod;
-import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.util.Date;
 
 /**
  * API接口访问拦截器
@@ -65,79 +64,70 @@ public class ApiInterceptor extends HandlerInterceptorAdapter {
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
             throws Exception {
         HandlerMethod method = (HandlerMethod) handler;
-        try {
-            return validate(request, response, method.getMethodAnnotation(RoleRequire.class));
-        } catch (ApiException e) {
-            response.sendError(e.getCode(), StringUtils.trimToEmpty(e.getMessage()));
-            return false;
-        } catch (Exception ee) {
-            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, StringUtils.trimToEmpty(ee.getMessage()));
-            return false;
-        }
+        return validate(request, response, method.getMethodAnnotation(RoleRequire.class));
     }
 
     private boolean validate(HttpServletRequest request, HttpServletResponse response, RoleRequire authConfig) {
-//        if (authConfig != null && authConfig.value().length > 0) {
-            AuthInfo simple;
-            // 优先按签名模式解析
-            SignatureInfo info = authorizationService.buildSignature(request);
-            if (info != null) {
-                if (info.getType() == SignatureType.SECRET) {
-                    School school = schoolService.findByAccessKey(info.getInvoker());
-                    if (school == null || !info.validate(school.getAccessSecret())) {
-                        throw ApiException.SIGNATURE_INVALID;
-                    }
-                    if (!school.isEnable()) {
-                        throw ApiException.USER_DISABLED;
-                    }
-                    if (authConfig != null && authConfig.value().length > 0&& !matchRole(authConfig, Role.SCHOOL_DEV)) {
-                        throw ApiException.USER_ROLE_INVALID;
-                    }
-                    return buildApiUser(request, response, school);
-                } else if (info.getType() == SignatureType.TOKEN) {
-                    User user = userService.findByLoginName(info.getInvoker());
-                    if (user == null ||!info.validate(user.getAccessToken())) {
-                        try {
-                            ObjectMapper mapper = new ObjectMapper();
-                            log.warn("api token signature invalud, signature={}, user={}",
-                                    mapper.writeValueAsString(info),
-                                    user != null ? mapper.writeValueAsString(user) : "{}");
-                        } catch (Exception ignored) {
-                        }
-                        throw ApiException.SIGNATURE_INVALID;
-                    }
-                    if (!user.isEnable()) {
-                        throw ApiException.USER_DISABLED;
-                    }
-                    if (authConfig != null && authConfig.value().length > 0 && !matchRole(authConfig, user.getRole())) {
-                        throw ApiException.USER_ROLE_INVALID;
-                    }
-                    return buildApiUser(request, response, user);
-                } else {
+        // if (authConfig != null && authConfig.value().length > 0) {
+        AuthInfo simple;
+        // 优先按签名模式解析
+        SignatureInfo info = authorizationService.buildSignature(request);
+        if (info != null) {
+            if (info.getType() == SignatureType.SECRET) {
+                School school = schoolService.findByAccessKey(info.getInvoker());
+                if (school == null || !info.validate(school.getAccessSecret())) {
                     throw ApiException.SIGNATURE_INVALID;
                 }
-            }
-            // 再尝试按简单模式解析
-            else if ((simple = authorizationService.buildAuthInfo(request)) != null) {
-                User user = userService.findByLoginName(simple.getLoginname());
-                if (user == null) {
-                    throw ApiException.SIGNATURE_INVALID;
+                if (!school.isEnable()) {
+                    throw ApiException.USER_DISABLED;
+                }
+                if (authConfig != null && authConfig.value().length > 0 && !matchRole(authConfig, Role.SCHOOL_DEV)) {
+                    throw ApiException.USER_ROLE_INVALID;
                 }
-                if( !EncryptUtils.md5(simple.getPassword()).equals(user.getPassword())){
-                    throw ApiException.PASSWORD_ERROR;
+                return buildApiUser(request, response, school);
+            } else if (info.getType() == SignatureType.TOKEN) {
+                User user = userService.findByLoginName(info.getInvoker());
+                if (user == null || !info.validate(user.getAccessToken())) {
+                    try {
+                        ObjectMapper mapper = new ObjectMapper();
+                        log.warn("api token signature invalud, signature={}, user={}", mapper.writeValueAsString(info),
+                                user != null ? mapper.writeValueAsString(user) : "{}");
+                    } catch (Exception ignored) {
+                    }
+                    throw ApiException.SIGNATURE_INVALID;
                 }
                 if (!user.isEnable()) {
                     throw ApiException.USER_DISABLED;
                 }
-                if (authConfig != null && authConfig.value().length > 0&& !matchRole(authConfig, user.getRole())) {
+                if (authConfig != null && authConfig.value().length > 0 && !matchRole(authConfig, user.getRole())) {
                     throw ApiException.USER_ROLE_INVALID;
                 }
                 return buildApiUser(request, response, user);
             } else {
-                throw ApiException.AUTHORIZATION_UNEXIST;
+                throw ApiException.SIGNATURE_INVALID;
+            }
+        }
+        // 再尝试按简单模式解析
+        else if ((simple = authorizationService.buildAuthInfo(request)) != null) {
+            User user = userService.findByLoginName(simple.getLoginname());
+            if (user == null) {
+                throw ApiException.SIGNATURE_INVALID;
             }
-//        }
-//        return true;
+            if (!EncryptUtils.md5(simple.getPassword()).equals(user.getPassword())) {
+                throw ApiException.PASSWORD_ERROR;
+            }
+            if (!user.isEnable()) {
+                throw ApiException.USER_DISABLED;
+            }
+            if (authConfig != null && authConfig.value().length > 0 && !matchRole(authConfig, user.getRole())) {
+                throw ApiException.USER_ROLE_INVALID;
+            }
+            return buildApiUser(request, response, user);
+        } else {
+            throw ApiException.AUTHORIZATION_UNEXIST;
+        }
+        // }
+        // return true;
     }
 
     private boolean matchRole(RoleRequire authConfig, Role role) {

+ 76 - 0
stmms-web/src/main/java/cn/com/qmth/stmms/common/support/CustomExceptionHandler.java

@@ -0,0 +1,76 @@
+package cn.com.qmth.stmms.common.support;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.lang.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+
+import com.qmth.boot.core.exception.StatusException;
+
+import cn.com.qmth.stmms.api.controller.BaseApiController;
+import cn.com.qmth.stmms.api.exception.ApiException;
+
+@ControllerAdvice
+public class CustomExceptionHandler {
+
+    protected static final Logger log = LoggerFactory.getLogger(BaseApiController.class);
+
+    private static final String ERROR_MESSAGE_HEADER_KEY = "error-info";
+
+    @ExceptionHandler(Exception.class)
+    public ResponseEntity<StatusResponse> handleException(Exception e, HttpServletRequest request) {
+        StatusResponse body = new StatusResponse(500, "系统异常");
+        return asResult(e, body, request);
+    }
+
+    @ExceptionHandler(RuntimeException.class)
+    public ResponseEntity<StatusResponse> handleException(RuntimeException e, HttpServletRequest request,
+            HttpServletResponse response) {
+        StatusResponse body = null;
+
+        if (e instanceof StatusException) {
+            StatusException se = (StatusException) e;
+            body = new StatusResponse(se.getCode(), se.getMessage());
+        } else if (e instanceof ApiException) {
+            response.addHeader(ERROR_MESSAGE_HEADER_KEY, StringUtils.trimToEmpty(e.getMessage()));
+            ApiException teme = (ApiException) e;
+            body = new StatusResponse(teme.getCode(), teme.getMessage());
+            return asResultApiEx(e, body, request);
+        } else {
+            body = new StatusResponse(500, "系统异常");
+        }
+
+        return asResult(e, body, request);
+    }
+
+    private ResponseEntity<StatusResponse> asResultApiEx(Throwable err, StatusResponse body,
+            HttpServletRequest request) {
+        ApiException teme = (ApiException) err;
+        HttpStatus httpStatus = HttpStatus.valueOf(teme.getCode());
+
+        log.error(err.getMessage(), err);
+
+        HttpHeaders headers = new HttpHeaders();
+        headers.add("Content-Type", "application/json;charset=utf-8");
+        return new ResponseEntity<>(body, headers, httpStatus);
+    }
+
+    private ResponseEntity<StatusResponse> asResult(Throwable err, StatusResponse body, HttpServletRequest request) {
+
+        HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
+
+        log.error(err.getMessage(), err);
+
+        HttpHeaders headers = new HttpHeaders();
+        headers.add("Content-Type", "application/json;charset=utf-8");
+        return new ResponseEntity<>(body, headers, httpStatus);
+    }
+
+}

+ 1 - 1
stmms-web/src/main/java/cn/com/qmth/stmms/common/JsonSerializable.java → stmms-web/src/main/java/cn/com/qmth/stmms/common/support/JsonSerializable.java

@@ -1,4 +1,4 @@
-package cn.com.qmth.stmms.common;
+package cn.com.qmth.stmms.common.support;
 
 import java.io.Serializable;
 

+ 8 - 8
stmms-web/src/main/java/cn/com/qmth/stmms/common/StatusResponse.java → stmms-web/src/main/java/cn/com/qmth/stmms/common/support/StatusResponse.java

@@ -1,4 +1,4 @@
-package cn.com.qmth.stmms.common;
+package cn.com.qmth.stmms.common.support;
 
 import io.swagger.annotations.ApiModelProperty;
 
@@ -10,7 +10,7 @@ public class StatusResponse implements JsonSerializable {
     private int code;
 
     @ApiModelProperty(value = "响应描述", example = "具体描述信息", required = true)
-    private String desc;
+    private String message;
 
     /**
      * 构造函数
@@ -25,10 +25,10 @@ public class StatusResponse implements JsonSerializable {
      * @param code
      * @param desc
      */
-    public StatusResponse(int code, String desc) {
+    public StatusResponse(int code, String message) {
         super();
         this.code = code;
-        this.desc = desc;
+        this.message = message;
     }
 
     public int getCode() {
@@ -39,12 +39,12 @@ public class StatusResponse implements JsonSerializable {
         this.code = code;
     }
 
-    public String getDesc() {
-        return desc;
+    public String getMessage() {
+        return message;
     }
 
-    public void setDesc(String desc) {
-        this.desc = desc;
+    public void setMessage(String message) {
+        this.message = message;
     }
 
 }

+ 2 - 1
stmms-web/src/main/webapp/WEB-INF/spring-mvc.xml

@@ -27,7 +27,8 @@
 					  cn.com.qmth.stmms.monitor,
 					  cn.com.qmth.stmms.report,
 					  cn.com.qmth.stmms.open,
-					  cn.com.qmth.stmms.student">
+					  cn.com.qmth.stmms.student,
+					  cn.com.qmth.stmms.common.support">
         <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
         <context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/>
     </context:component-scan>