dongyukun
2024-12-31 0a2b23ad3f30dfb01c5d590fb98f39e93bfe1932
提交 | 用户 | 时间
e7c126 1 package com.xxl.job.admin.controller.interceptor;
H 2
3 import com.xxl.job.admin.controller.annotation.PermissionLimit;
4 import com.xxl.job.admin.core.model.XxlJobUser;
5 import com.xxl.job.admin.core.util.I18nUtil;
6 import com.xxl.job.admin.service.LoginService;
7 import org.springframework.stereotype.Component;
8 import org.springframework.web.method.HandlerMethod;
9 import org.springframework.web.servlet.AsyncHandlerInterceptor;
10
11 import javax.annotation.Resource;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14
15 /**
16  * 权限拦截
17  *
18  * @author xuxueli 2015-12-12 18:09:04
19  */
20 @Component
21 public class PermissionInterceptor implements AsyncHandlerInterceptor {
22
23     @Resource
24     private LoginService loginService;
25
26     @Override
27     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
28         
29         if (!(handler instanceof HandlerMethod)) {
30             return true;    // proceed with the next interceptor
31         }
32
33         // if need login
34         boolean needLogin = true;
35         boolean needAdminuser = false;
36         HandlerMethod method = (HandlerMethod)handler;
37         PermissionLimit permission = method.getMethodAnnotation(PermissionLimit.class);
38         if (permission!=null) {
39             needLogin = permission.limit();
40             needAdminuser = permission.adminuser();
41         }
42
43         if (needLogin) {
44             XxlJobUser loginUser = loginService.ifLogin(request, response);
45             if (loginUser == null) {
46                 response.setStatus(302);
47                 response.setHeader("location", request.getContextPath()+"/toLogin");
48                 return false;
49             }
50             if (needAdminuser && loginUser.getRole()!=1) {
51                 throw new RuntimeException(I18nUtil.getString("system_permission_limit"));
52             }
53             request.setAttribute(LoginService.LOGIN_IDENTITY_KEY, loginUser);
54         }
55
56         return true;    // proceed with the next interceptor
57     }
58     
59 }