|
@@ -1,8 +1,9 @@
|
|
|
package com.nokia.config.web;
|
|
|
|
|
|
import com.alibaba.fastjson2.JSON;
|
|
|
+import com.nokia.common.R;
|
|
|
+import lombok.NoArgsConstructor;
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
-import org.springframework.http.HttpStatus;
|
|
|
import org.springframework.web.servlet.HandlerInterceptor;
|
|
|
|
|
|
import javax.servlet.http.HttpServletRequest;
|
|
@@ -13,25 +14,38 @@ import javax.servlet.http.HttpSession;
|
|
|
* web登录拦截
|
|
|
*/
|
|
|
@Slf4j
|
|
|
+@NoArgsConstructor
|
|
|
public class WebLoginInterceptor implements HandlerInterceptor {
|
|
|
+ private Integer timeoutSeconds;
|
|
|
+
|
|
|
+ public WebLoginInterceptor(Integer timeoutSeconds) {
|
|
|
+ this.timeoutSeconds = timeoutSeconds;
|
|
|
+ }
|
|
|
+
|
|
|
@Override
|
|
|
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
|
|
HttpSession session = request.getSession();
|
|
|
// 未登录或登录失效返回401
|
|
|
if (session == null || session.getAttribute("userinfo") == null) {
|
|
|
- response.setStatus(HttpStatus.UNAUTHORIZED.value());
|
|
|
+ response.setCharacterEncoding("UTF-8");
|
|
|
+ response.setContentType("application/json; charset=utf-8");
|
|
|
+ response.getWriter().write(JSON.toJSONString(R.error().code(401).message("登录失效")));
|
|
|
+ log.warn("登录失效");
|
|
|
return false;
|
|
|
}
|
|
|
// 没有权限返回403
|
|
|
if (session.getAttribute("role") == null) {
|
|
|
- response.setStatus(HttpStatus.FORBIDDEN.value());
|
|
|
+ response.setCharacterEncoding("UTF-8");
|
|
|
+ response.setContentType("application/json; charset=utf-8");
|
|
|
+ response.getWriter().write(JSON.toJSONString(R.error().code(403).message("权限不足")));
|
|
|
+ log.warn("权限不足");
|
|
|
return false;
|
|
|
}
|
|
|
log.debug("sessionId: {}, userinfo: {}, role: {}", session.getId(),
|
|
|
JSON.toJSONString(session.getAttribute("userinfo")),
|
|
|
JSON.toJSONString(session.getAttribute("role")));
|
|
|
// 延长session过期时间
|
|
|
- session.setMaxInactiveInterval(600);
|
|
|
+ session.setMaxInactiveInterval(timeoutSeconds);
|
|
|
return true;
|
|
|
}
|
|
|
}
|