张延森 преди 3 години
родител
ревизия
7cc6654a7e
променени са 27 файла, в които са добавени 381 реда и са изтрити 680 реда
  1. 1
    1
      deploy/bootstrap
  2. 1
    1
      deploy/s.yml
  3. 9
    12
      pom.xml
  4. 19
    12
      src/main/java/com/njyunzhi/ubpa/common/BaseController.java
  5. 44
    0
      src/main/java/com/njyunzhi/ubpa/config/SaTokenConfigure.java
  6. 8
    10
      src/main/java/com/njyunzhi/ubpa/controller/LoginController.java
  7. 131
    0
      src/main/java/com/njyunzhi/ubpa/controller/OrgLoginController.java
  8. 6
    1
      src/main/java/com/njyunzhi/ubpa/controller/TaResumeWorkFormController.java
  9. 121
    61
      src/main/java/com/njyunzhi/ubpa/controller/TaUserController.java
  10. 2
    0
      src/main/java/com/njyunzhi/ubpa/entity/TaUser.java
  11. 1
    0
      src/main/java/com/njyunzhi/ubpa/service/ITaUserService.java
  12. 8
    21
      src/main/java/com/njyunzhi/ubpa/service/impl/ManagerServiceImpl.java
  13. 9
    0
      src/main/java/com/njyunzhi/ubpa/service/impl/TaUserServiceImpl.java
  14. 0
    17
      src/main/java/com/njyunzhi/ubpa/shiro/FirstExceptionStrategy.java
  15. 0
    103
      src/main/java/com/njyunzhi/ubpa/shiro/ShiroConfig.java
  16. 0
    94
      src/main/java/com/njyunzhi/ubpa/shiro/filters/JWTFilter.java
  17. 0
    28
      src/main/java/com/njyunzhi/ubpa/shiro/filters/ManagerFilter.java
  18. 0
    24
      src/main/java/com/njyunzhi/ubpa/shiro/filters/MiniappFilter.java
  19. 0
    16
      src/main/java/com/njyunzhi/ubpa/shiro/matcher/JWTCredentialsMatcher.java
  20. 0
    31
      src/main/java/com/njyunzhi/ubpa/shiro/realms/manager/IManagerService.java
  21. 0
    77
      src/main/java/com/njyunzhi/ubpa/shiro/realms/manager/ManagerRealm.java
  22. 0
    44
      src/main/java/com/njyunzhi/ubpa/shiro/realms/miniapp/MiniappRealm.java
  23. 0
    23
      src/main/java/com/njyunzhi/ubpa/shiro/utils/JWTToken.java
  24. 0
    66
      src/main/java/com/njyunzhi/ubpa/shiro/utils/JWTUtil.java
  25. 0
    23
      src/main/java/com/njyunzhi/ubpa/shiro/utils/MiniappToken.java
  26. 3
    0
      src/main/resources/application-prod.yml
  27. 18
    15
      src/main/resources/application.yml

+ 1
- 1
deploy/bootstrap Целия файл

@@ -2,4 +2,4 @@
2 2
 #
3 3
 #
4 4
 
5
-java -jar ./ubpa-0.0.5.jar
5
+java -jar ./ubpa-0.0.6.jar

+ 1
- 1
deploy/s.yml Целия файл

@@ -15,7 +15,7 @@ services:
15 15
         name: ubpa-func
16 16
         description: 'ubpa-func'
17 17
         ossBucket: yz-serverless
18
-        ossKey: ubpa/ubpa-0.0.5.zip
18
+        ossKey: ubpa/ubpa-0.0.6.zip
19 19
         handler: 'com.njyunzhi.ubpa.UbpaApplication::main'
20 20
         memorySize: 1024
21 21
         timeout: 30

+ 9
- 12
pom.xml Целия файл

@@ -10,7 +10,7 @@
10 10
 	</parent>
11 11
 	<groupId>com.njyunzhi</groupId>
12 12
 	<artifactId>ubpa</artifactId>
13
-	<version>0.0.5</version>
13
+	<version>0.0.6</version>
14 14
 	<name>ubpa</name>
15 15
 	<description>Demo project for Spring Boot</description>
16 16
 
@@ -100,22 +100,19 @@
100 100
 		</dependency>
101 101
 		<!--swagger end-->
102 102
 
103
-
104
-		<!-- shiro start-->
103
+		<!-- Sa-Token 权限认证, 在线文档:http://sa-token.dev33.cn/ -->
105 104
 		<dependency>
106
-			<groupId>org.apache.shiro</groupId>
107
-			<artifactId>shiro-spring-boot-web-starter</artifactId>
108
-			<version>1.8.0</version>
105
+			<groupId>cn.dev33</groupId>
106
+			<artifactId>sa-token-spring-boot-starter</artifactId>
107
+			<version>1.29.0</version>
109 108
 		</dependency>
110
-		<!-- shiro end-->
111 109
 
112
-		<!-- jwt start -->
110
+		<!-- Sa-Token 整合 jwt -->
113 111
 		<dependency>
114
-			<groupId>com.auth0</groupId>
115
-			<artifactId>java-jwt</artifactId>
116
-			<version>3.18.3</version>
112
+			<groupId>cn.dev33</groupId>
113
+			<artifactId>sa-token-jwt</artifactId>
114
+			<version>1.29.0</version>
117 115
 		</dependency>
118
-		<!-- end start -->
119 116
 
120 117
 	</dependencies>
121 118
 

+ 19
- 12
src/main/java/com/njyunzhi/ubpa/common/BaseController.java Целия файл

@@ -1,10 +1,10 @@
1 1
 package com.njyunzhi.ubpa.common;
2 2
 
3
+import cn.dev33.satoken.stp.StpUtil;
3 4
 import com.njyunzhi.ubpa.entity.SysUser;
5
+import com.njyunzhi.ubpa.entity.TaUser;
4 6
 import com.njyunzhi.ubpa.service.ISysUserService;
5
-import com.njyunzhi.ubpa.shiro.utils.JWTUtil;
6
-import org.apache.shiro.SecurityUtils;
7
-import org.apache.shiro.subject.Subject;
7
+import com.njyunzhi.ubpa.service.ITaUserService;
8 8
 import org.springframework.beans.factory.annotation.Autowired;
9 9
 import org.springframework.stereotype.Component;
10 10
 
@@ -14,23 +14,30 @@ public class BaseController {
14 14
     @Autowired
15 15
     ISysUserService iSysUserService;
16 16
 
17
-    public String getLoginId() {
18
-        Subject subject = SecurityUtils.getSubject();
19
-        String token = subject.getPrincipal().toString();
17
+    @Autowired
18
+    ITaUserService iTaUserService;
20 19
 
21
-//        List<Object> list = Arrays.asList(subject.getPrincipals().fromRealm("managerRealm").toArray());
22
-//        String token = list.get(0).toString();
20
+    public SysUser currentAdmin() throws Exception {
21
+        String loginId = StpUtil.getLoginIdAsString();
22
+        if (StringUtils.isEmpty(loginId)) {
23
+            throw new Exception("请先登录");
24
+        }
23 25
 
24
-        return JWTUtil.getLoginId(token);
26
+        SysUser user = iSysUserService.getById(loginId);
27
+        if (user == null || user.getStatus() == Constants.STATUS_DELETE) {
28
+            throw new Exception("人员不存在");
29
+        }
30
+
31
+        return user;
25 32
     }
26 33
 
27
-    public SysUser currentUser() throws Exception {
28
-        String loginId = getLoginId();
34
+    public TaUser currentUser() throws Exception {
35
+        String loginId = StpUtil.getLoginIdAsString();
29 36
         if (StringUtils.isEmpty(loginId)) {
30 37
             throw new Exception("请先登录");
31 38
         }
32 39
 
33
-        SysUser user = iSysUserService.getById(loginId);
40
+        TaUser user = iTaUserService.getById(loginId);
34 41
         if (user == null || user.getStatus() == Constants.STATUS_DELETE) {
35 42
             throw new Exception("人员不存在");
36 43
         }

+ 44
- 0
src/main/java/com/njyunzhi/ubpa/config/SaTokenConfigure.java Целия файл

@@ -0,0 +1,44 @@
1
+package com.njyunzhi.ubpa.config;
2
+
3
+import cn.dev33.satoken.interceptor.SaRouteInterceptor;
4
+import cn.dev33.satoken.jwt.StpLogicJwtForStateless;
5
+import cn.dev33.satoken.stp.StpLogic;
6
+import org.springframework.context.annotation.Bean;
7
+import org.springframework.context.annotation.Configuration;
8
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
9
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
10
+
11
+import java.util.ArrayList;
12
+import java.util.List;
13
+
14
+@Configuration
15
+public class SaTokenConfigure implements WebMvcConfigurer {
16
+    // 注册拦截器
17
+    @Override
18
+    public void addInterceptors(InterceptorRegistry registry) {
19
+
20
+        List<String> anonList = new ArrayList<>();
21
+        anonList.add("/swagger-ui/**");
22
+        anonList.add("/swagger-resources/**");
23
+        anonList.add("/v2/**");
24
+//        anonList.add("/wxpay/notify/**");
25
+        anonList.add("/**/sms-captcha");
26
+        anonList.add("/**/**/sms-captcha");
27
+        anonList.add("/**/preload");
28
+        anonList.add("/**/login");
29
+        anonList.add("/**/**/login");
30
+
31
+        // 注册Sa-Token的路由拦截器
32
+        registry.addInterceptor(new SaRouteInterceptor())
33
+                .addPathPatterns("/**")
34
+                .excludePathPatterns(anonList.toArray(new String[0]));
35
+    }
36
+
37
+
38
+
39
+    // Sa-Token 整合 jwt (Style模式)
40
+    @Bean
41
+    public StpLogic getStpLogicJwt() {
42
+        return new StpLogicJwtForStateless();
43
+    }
44
+}

+ 8
- 10
src/main/java/com/njyunzhi/ubpa/controller/LoginController.java Целия файл

@@ -1,18 +1,16 @@
1 1
 package com.njyunzhi.ubpa.controller;
2 2
 
3
+import cn.dev33.satoken.stp.StpUtil;
3 4
 import com.njyunzhi.ubpa.common.*;
4 5
 import com.njyunzhi.ubpa.entity.SysSetting;
5 6
 import com.njyunzhi.ubpa.entity.SysUser;
6 7
 import com.njyunzhi.ubpa.service.ISysSettingService;
7 8
 import com.njyunzhi.ubpa.service.ISysUserService;
8
-import com.njyunzhi.ubpa.shiro.utils.JWTUtil;
9 9
 import com.njyunzhi.ubpa.vo.ChangePassword;
10 10
 import com.njyunzhi.ubpa.vo.LoginParam;
11 11
 import io.swagger.annotations.Api;
12 12
 import io.swagger.annotations.ApiOperation;
13 13
 import io.swagger.annotations.ApiParam;
14
-import org.apache.shiro.SecurityUtils;
15
-import org.apache.shiro.subject.Subject;
16 14
 import org.springframework.beans.factory.annotation.Autowired;
17 15
 import org.springframework.web.bind.annotation.*;
18 16
 
@@ -61,10 +59,11 @@ public class LoginController extends BaseController {
61 59
 
62 60
         Map<String, Object> res = new HashMap<>();
63 61
         res.put("user", sysUser);
62
+        res.put("roleAlias", "admin");
64 63
 
65 64
         // 生成 token
66
-        String token = JWTUtil.sign(sysUser.getUserId(), sysUser.getUserId());
67
-        res.put("token", token);
65
+        StpUtil.login(sysUser.getUserId(), "admin");
66
+        res.put("token", StpUtil.getTokenValue());
68 67
 
69 68
         // 获取填报客户端地址
70 69
         SysSetting sysSetting = iSysSettingService.getById(Constants.SETTING_REPORT_URL);
@@ -76,7 +75,7 @@ public class LoginController extends BaseController {
76 75
     @GetMapping("/admin/currentUser")
77 76
     @ApiOperation(value="当前用户", notes = "当前用户", httpMethod = "GET", response = ResponseBean.class)
78 77
     public ResponseBean getCurrentUser() throws Exception {
79
-        SysUser sysUser = currentUser();
78
+        SysUser sysUser = currentAdmin();
80 79
 
81 80
         if (sysUser.getStatus() != Constants.STATUS_NORMAL) {
82 81
             return ResponseBean.error("账户异常", ResponseBean.ERROR_ILLEGAL_PARAMS);
@@ -87,6 +86,7 @@ public class LoginController extends BaseController {
87 86
         sysUser.setPassword(null);
88 87
         Map<String, Object> res = new HashMap<>();
89 88
         res.put("user", sysUser);
89
+        res.put("roleAlias", "admin");
90 90
         res.put(Constants.SETTING_REPORT_URL, sysSetting.getContent());
91 91
 
92 92
         return ResponseBean.success(res);
@@ -95,8 +95,7 @@ public class LoginController extends BaseController {
95 95
     @PostMapping("/admin/logout")
96 96
     @ApiOperation(value="登出", notes = "登出", httpMethod = "POST", response = ResponseBean.class)
97 97
     public ResponseBean logout() throws Exception {
98
-        Subject subject = SecurityUtils.getSubject();
99
-        subject.logout();
98
+        StpUtil.logout();
100 99
         return ResponseBean.success("success");
101 100
     }
102 101
 
@@ -113,7 +112,7 @@ public class LoginController extends BaseController {
113 112
             return ResponseBean.error("原始密码或新密码不能为空", ResponseBean.ERROR_ILLEGAL_PARAMS);
114 113
         }
115 114
 
116
-        SysUser currentUser = currentUser();
115
+        SysUser currentUser = currentAdmin();
117 116
 
118 117
         if (!checkPassword(param.getOriginPassword(), currentUser.getPassword(), currentUser.getUserId())) {
119 118
             return ResponseBean.error("原始密码不正确", ResponseBean.ERROR_ILLEGAL_PARAMS);
@@ -125,7 +124,6 @@ public class LoginController extends BaseController {
125 124
         return ResponseBean.success("密码修改成功");
126 125
     }
127 126
 
128
-
129 127
     private boolean checkPassword(String src, String targ, String salt) {
130 128
         return EncryptUtils.md5(src, salt).equals(targ);
131 129
     }

+ 131
- 0
src/main/java/com/njyunzhi/ubpa/controller/OrgLoginController.java Целия файл

@@ -0,0 +1,131 @@
1
+package com.njyunzhi.ubpa.controller;
2
+
3
+import cn.dev33.satoken.stp.StpUtil;
4
+import com.njyunzhi.ubpa.common.*;
5
+import com.njyunzhi.ubpa.entity.SysSetting;
6
+import com.njyunzhi.ubpa.entity.TaUser;
7
+import com.njyunzhi.ubpa.service.ISysSettingService;
8
+import com.njyunzhi.ubpa.service.ITaUserService;
9
+import com.njyunzhi.ubpa.vo.ChangePassword;
10
+import com.njyunzhi.ubpa.vo.LoginParam;
11
+import io.swagger.annotations.Api;
12
+import io.swagger.annotations.ApiOperation;
13
+import io.swagger.annotations.ApiParam;
14
+import org.springframework.beans.factory.annotation.Autowired;
15
+import org.springframework.web.bind.annotation.*;
16
+
17
+import java.util.HashMap;
18
+import java.util.Map;
19
+
20
+
21
+@Api(tags = "企业登入/登出")
22
+@RestController
23
+@RequestMapping("/admin/org")
24
+public class OrgLoginController extends BaseController {
25
+
26
+    @Autowired
27
+    ITaUserService iTaUserService;
28
+
29
+    @Autowired
30
+    ISysSettingService iSysSettingService;
31
+
32
+    @PostMapping("/login")
33
+    @ApiOperation(value="登录", notes = "登录", httpMethod = "POST", response = ResponseBean.class)
34
+    public ResponseBean login(@ApiParam("登录参数") @RequestBody LoginParam loginParam) throws Exception {
35
+        if (null == loginParam) {
36
+            return ResponseBean.error("账户或密码不能为空", ResponseBean.ERROR_ILLEGAL_PARAMS);
37
+        }
38
+
39
+        String userName = loginParam.getUserName();
40
+        String password = loginParam.getPassword();
41
+
42
+        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
43
+            return ResponseBean.error("账户或密码不能为空", ResponseBean.ERROR_ILLEGAL_PARAMS);
44
+        }
45
+
46
+        TaUser taUser = iTaUserService.getExistBy("login_name", userName, false, true);
47
+        if (null == taUser) {
48
+            return ResponseBean.error("账户或密码不正确", ResponseBean.ERROR_ILLEGAL_PARAMS);
49
+        }
50
+
51
+        if (taUser.getStatus() != Constants.STATUS_NORMAL) {
52
+            return ResponseBean.error("账户异常", ResponseBean.ERROR_ILLEGAL_PARAMS);
53
+        }
54
+
55
+        if (!checkPassword(password, taUser.getPassword(), taUser.getUserId())) {
56
+            return ResponseBean.error("账户或密码不正确", ResponseBean.ERROR_ILLEGAL_PARAMS);
57
+        }
58
+
59
+        taUser.setPassword(null);
60
+
61
+        Map<String, Object> res = new HashMap<>();
62
+        res.put("user", taUser);
63
+        res.put("roleAlias", "org");
64
+
65
+        // 生成 token
66
+        StpUtil.login(taUser.getUserId(), "org");
67
+        res.put("token", StpUtil.getTokenValue());
68
+
69
+        // 获取填报客户端地址
70
+        SysSetting sysSetting = iSysSettingService.getById(Constants.SETTING_REPORT_URL);
71
+        res.put(Constants.SETTING_REPORT_URL, sysSetting.getContent());
72
+
73
+        return ResponseBean.success(res);
74
+    }
75
+
76
+    @GetMapping("/currentUser")
77
+    @ApiOperation(value="当前用户", notes = "当前用户", httpMethod = "GET", response = ResponseBean.class)
78
+    public ResponseBean getCurrentUser() throws Exception {
79
+        TaUser taUser = currentUser();
80
+
81
+        if (taUser.getStatus() != Constants.STATUS_NORMAL) {
82
+            return ResponseBean.error("账户异常", ResponseBean.ERROR_ILLEGAL_PARAMS);
83
+        }
84
+        // 获取填报客户端地址
85
+        SysSetting sysSetting = iSysSettingService.getById(Constants.SETTING_REPORT_URL);
86
+
87
+        taUser.setPassword(null);
88
+        Map<String, Object> res = new HashMap<>();
89
+        res.put("user", taUser);
90
+        res.put("roleAlias", "org");
91
+        res.put(Constants.SETTING_REPORT_URL, sysSetting.getContent());
92
+
93
+        return ResponseBean.success(res);
94
+    }
95
+
96
+    @PostMapping("/logout")
97
+    @ApiOperation(value="登出", notes = "登出", httpMethod = "POST", response = ResponseBean.class)
98
+    public ResponseBean logout() throws Exception {
99
+        StpUtil.logout();
100
+        return ResponseBean.success("success");
101
+    }
102
+
103
+    @GetMapping("/401")
104
+    @ApiOperation(value="401无权限", notes = "401无权限", httpMethod = "GET", response = ResponseBean.class)
105
+    public ResponseBean unAuth(@RequestParam(value = "msg", defaultValue = "未登录或暂无权限") String msg) throws Exception {
106
+        return ResponseBean.error(msg, ResponseBean.ERROR_AUTH_FAIL);
107
+    }
108
+
109
+    @PutMapping("/change-password")
110
+    @ApiOperation(value="修改密码", notes = "修改密码", httpMethod = "PUT", response = ResponseBean.class)
111
+    public ResponseBean changePassword(@ApiParam("修改密码参数") @RequestBody ChangePassword param) throws Exception {
112
+        if (StringUtils.isEmpty(param.getOriginPassword()) || StringUtils.isEmpty(param.getNewPassword())) {
113
+            return ResponseBean.error("原始密码或新密码不能为空", ResponseBean.ERROR_ILLEGAL_PARAMS);
114
+        }
115
+
116
+        TaUser taUser = currentUser();
117
+
118
+        if (!checkPassword(param.getOriginPassword(), taUser.getPassword(), taUser.getUserId())) {
119
+            return ResponseBean.error("原始密码不正确", ResponseBean.ERROR_ILLEGAL_PARAMS);
120
+        }
121
+
122
+        taUser.setPassword(EncryptUtils.md5(param.getNewPassword(), taUser.getUserId()));
123
+        iTaUserService.updateById(taUser);
124
+
125
+        return ResponseBean.success("密码修改成功");
126
+    }
127
+
128
+    private boolean checkPassword(String src, String targ, String salt) {
129
+        return EncryptUtils.md5(src, salt).equals(targ);
130
+    }
131
+}

+ 6
- 1
src/main/java/com/njyunzhi/ubpa/controller/TaResumeWorkFormController.java Целия файл

@@ -87,11 +87,14 @@ public class TaResumeWorkFormController extends BaseController {
87 87
      */
88 88
     @RequestMapping(value="/admin/resume-work-form/export",method= RequestMethod.GET)
89 89
     @ApiOperation(value="申请导出", notes = "申请导出", httpMethod = "GET", response = ResponseBean.class)
90
-    public void formExport(@ApiParam("企业ID") @RequestParam(value ="orgId") String orgId,
90
+    public ResponseBean formExport(@ApiParam("企业ID") @RequestParam(value ="orgId", required = false) String orgId,
91 91
                            @ApiParam("申请人") @RequestParam(value ="userName", required = false) String userName,
92 92
                            @ApiParam(value = "起始时间", example = "2022-03-01") @RequestParam(value ="start", required = false) String start,
93 93
                            @ApiParam(value = "结束时间", example = "2022-03-31") @RequestParam(value ="end", required = false) String end,
94 94
                            HttpServletResponse response) throws Exception{
95
+        if (StringUtils.isEmpty(orgId)) {
96
+            return ResponseBean.error("请选择企业");
97
+        }
95 98
 
96 99
         LocalDateTime startDate = DateUtils.getDayStart(start);
97 100
         LocalDateTime endDate = DateUtils.getDayEnd(end);
@@ -133,6 +136,8 @@ public class TaResumeWorkFormController extends BaseController {
133 136
         }
134 137
 
135 138
         ExcelUtils.flush(response, FormExport.class, list, String.join("_", fileNameParts), null);
139
+
140
+        return null;
136 141
     }
137 142
 
138 143
     /**

+ 121
- 61
src/main/java/com/njyunzhi/ubpa/controller/TaUserController.java Целия файл

@@ -4,7 +4,9 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
4 4
 import com.baomidou.mybatisplus.core.metadata.IPage;
5 5
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
6 6
 import com.njyunzhi.ubpa.common.BaseController;
7
+import com.njyunzhi.ubpa.common.EncryptUtils;
7 8
 import com.njyunzhi.ubpa.common.ResponseBean;
9
+import com.njyunzhi.ubpa.common.StringUtils;
8 10
 import io.swagger.annotations.Api;
9 11
 import io.swagger.annotations.ApiOperation;
10 12
 import io.swagger.annotations.ApiParam;
@@ -40,80 +42,138 @@ public class TaUserController extends BaseController {
40 42
     public ITaUserService iTaUserService;
41 43
 
42 44
 
43
-    /**
44
-     * 分页查询列表
45
-     * @param pageNum
46
-     * @param pageSize
47
-     * @return
48
-     */
49
-    @RequestMapping(value="/taUser",method= RequestMethod.GET)
50
-    @ApiOperation(value="列表", notes = "列表", httpMethod = "GET", response = ResponseBean.class)
51
-    public ResponseBean taUserList(@ApiParam("页码") @RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
52
-									 @ApiParam("单页数据量") @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize) throws Exception{
53
-
54
-		    IPage<TaUser> pg = new Page<>(pageNum, pageSize);
55
-            QueryWrapper<TaUser> queryWrapper = new QueryWrapper<>();
56
-            queryWrapper.orderByDesc("create_date");
45
+//    /**
46
+//     * 分页查询列表
47
+//     * @param pageNum
48
+//     * @param pageSize
49
+//     * @return
50
+//     */
51
+//    @RequestMapping(value="/taUser",method= RequestMethod.GET)
52
+//    @ApiOperation(value="列表", notes = "列表", httpMethod = "GET", response = ResponseBean.class)
53
+//    public ResponseBean taUserList(@ApiParam("页码") @RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
54
+//									 @ApiParam("单页数据量") @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize) throws Exception{
55
+//
56
+//		    IPage<TaUser> pg = new Page<>(pageNum, pageSize);
57
+//            QueryWrapper<TaUser> queryWrapper = new QueryWrapper<>();
58
+//            queryWrapper.orderByDesc("create_date");
59
+//
60
+//            IPage<TaUser> result = iTaUserService.page(pg, queryWrapper);
61
+//            return ResponseBean.success(result);
62
+//    }
63
+//
64
+//    /**
65
+//     * 保存对象
66
+//     * @param taUser 实体对象
67
+//     * @return
68
+//     */
69
+//    @RequestMapping(value="/taUser",method= RequestMethod.POST)
70
+//    @ApiOperation(value="保存", notes = "保存", httpMethod = "POST", response = ResponseBean.class)
71
+//    public ResponseBean taUserAdd(@ApiParam("保存内容") @RequestBody TaUser taUser) throws Exception{
72
+//
73
+//        if (iTaUserService.save(taUser)){
74
+//            return ResponseBean.success(taUser);
75
+//        }else {
76
+//            return ResponseBean.error("保存失败, 请重试", ResponseBean.ERROR_UNAVAILABLE);
77
+//        }
78
+//    }
57 79
 
58
-            IPage<TaUser> result = iTaUserService.page(pg, queryWrapper);
59
-            return ResponseBean.success(result);
60
-    }
61 80
 
62 81
     /**
63 82
      * 保存对象
64 83
      * @param taUser 实体对象
65 84
      * @return
66 85
      */
67
-    @RequestMapping(value="/taUser",method= RequestMethod.POST)
68
-    @ApiOperation(value="保存", notes = "保存", httpMethod = "POST", response = ResponseBean.class)
69
-    public ResponseBean taUserAdd(@ApiParam("保存内容") @RequestBody TaUser taUser) throws Exception{
86
+    @RequestMapping(value="/admin/org/{orgId}/user",method= RequestMethod.POST)
87
+    @ApiOperation(value="保存或修改对象", notes = "保存或修改对象", httpMethod = "POST", response = ResponseBean.class)
88
+    public ResponseBean taUserAdd(@ApiParam("企业ID") @PathVariable String orgId,
89
+                                  @ApiParam("保存内容") @RequestBody TaUser taUser) throws Exception{
90
+        boolean isAdd = StringUtils.isEmpty(taUser.getUserId());
91
+        taUser.setOrgId(orgId);
70 92
 
71
-        if (iTaUserService.save(taUser)){
72
-            return ResponseBean.success(taUser);
73
-        }else {
74
-            return ResponseBean.error("保存失败, 请重试", ResponseBean.ERROR_UNAVAILABLE);
93
+        if (isAdd) {
94
+            TaUser orgin = iTaUserService.getOrgAdmin(orgId);
95
+            if (null != orgin) {
96
+                return ResponseBean.error("参数错误, 企业已存在管理员");
97
+            }
75 98
         }
76
-    }
77 99
 
78
-    /**
79
-     * 根据id删除对象
80
-     * @param id  实体ID
81
-     */
82
-    @RequestMapping(value="/taUser/{id}", method= RequestMethod.DELETE)
83
-    @ApiOperation(value="删除", notes = "删除", httpMethod = "DELETE", response = ResponseBean.class)
84
-    public ResponseBean taUserDelete(@ApiParam("对象ID") @PathVariable Integer id) throws Exception{
85
-        if(iTaUserService.removeById(id)){
86
-            return ResponseBean.success("success");
87
-        }else {
88
-            return ResponseBean.error("删除失败, 请重试", ResponseBean.ERROR_UNAVAILABLE);
100
+        if (StringUtils.isEmpty(taUser.getUserName())) {
101
+            return ResponseBean.error("用户姓名不能为空");
89 102
         }
90
-    }
91 103
 
92
-    /**
93
-     * 修改对象
94
-     * @param id  实体ID
95
-     * @param taUser 实体对象
96
-     * @return
97
-     */
98
-    @RequestMapping(value="/taUser/{id}",method= RequestMethod.PUT)
99
-    @ApiOperation(value="更新", notes = "更新", httpMethod = "PUT", response = ResponseBean.class)
100
-    public ResponseBean taUserUpdate(@ApiParam("对象ID") @PathVariable Integer id,
101
-                                        @ApiParam("更新内容") @RequestBody TaUser taUser) throws Exception{
102
-
103
-        if (iTaUserService.updateById(taUser)){
104
-            return ResponseBean.success(iTaUserService.getById(id));
105
-        }else {
106
-            return ResponseBean.error("修改失败, 请重试", ResponseBean.ERROR_UNAVAILABLE);
104
+        if (StringUtils.isEmpty(taUser.getPhone())) {
105
+            return ResponseBean.error("用户手机不能为空");
107 106
         }
108
-    }
109 107
 
110
-    /**
111
-     * 根据id查询对象
112
-     * @param id  实体ID
113
-     */
114
-    @RequestMapping(value="/taUser/{id}",method= RequestMethod.GET)
115
-    @ApiOperation(value="详情", notes = "详情", httpMethod = "GET", response = ResponseBean.class)
116
-    public ResponseBean taUserGet(@ApiParam("对象ID") @PathVariable Integer id) throws Exception{
117
-        return ResponseBean.success(iTaUserService.getById(id));
108
+        TaUser origin = iTaUserService.getExistBy("phone", taUser.getPhone(), false, true);
109
+        if (null != origin && (isAdd || !taUser.getUserId().equals(origin.getUserId()))) {
110
+            return ResponseBean.error("用户手机已存在");
111
+        }
112
+
113
+        if (!StringUtils.isEmpty(taUser.getLoginName())) {
114
+            origin = iTaUserService.getExistBy("login_name", taUser.getLoginName(), false, true);
115
+            if (null != origin && (isAdd || !taUser.getUserId().equals(origin.getUserId()))) {
116
+                return ResponseBean.error("用户登录账号已存在");
117
+            }
118
+        }
119
+
120
+        if (isAdd) {
121
+            taUser.setUserId(StringUtils.uuid());
122
+        }
123
+
124
+        if (!StringUtils.isEmpty(taUser.getPassword())) {
125
+            String newPass = EncryptUtils.md5(taUser.getPassword(), taUser.getUserId());
126
+            taUser.setPassword(newPass);
127
+        }
128
+
129
+        boolean isOk = isAdd ? iTaUserService.save(taUser) : iTaUserService.updateById(taUser);
130
+
131
+        if (isOk){
132
+            return ResponseBean.success(taUser);
133
+        } else {
134
+            return ResponseBean.error("保存失败, 请重试", ResponseBean.ERROR_UNAVAILABLE);
135
+        }
118 136
     }
137
+//
138
+//    /**
139
+//     * 根据id删除对象
140
+//     * @param id  实体ID
141
+//     */
142
+//    @RequestMapping(value="/taUser/{id}", method= RequestMethod.DELETE)
143
+//    @ApiOperation(value="删除", notes = "删除", httpMethod = "DELETE", response = ResponseBean.class)
144
+//    public ResponseBean taUserDelete(@ApiParam("对象ID") @PathVariable Integer id) throws Exception{
145
+//        if(iTaUserService.removeById(id)){
146
+//            return ResponseBean.success("success");
147
+//        }else {
148
+//            return ResponseBean.error("删除失败, 请重试", ResponseBean.ERROR_UNAVAILABLE);
149
+//        }
150
+//    }
151
+//
152
+//    /**
153
+//     * 修改对象
154
+//     * @param id  实体ID
155
+//     * @param taUser 实体对象
156
+//     * @return
157
+//     */
158
+//    @RequestMapping(value="/taUser/{id}",method= RequestMethod.PUT)
159
+//    @ApiOperation(value="更新", notes = "更新", httpMethod = "PUT", response = ResponseBean.class)
160
+//    public ResponseBean taUserUpdate(@ApiParam("对象ID") @PathVariable Integer id,
161
+//                                        @ApiParam("更新内容") @RequestBody TaUser taUser) throws Exception{
162
+//
163
+//        if (iTaUserService.updateById(taUser)){
164
+//            return ResponseBean.success(iTaUserService.getById(id));
165
+//        }else {
166
+//            return ResponseBean.error("修改失败, 请重试", ResponseBean.ERROR_UNAVAILABLE);
167
+//        }
168
+//    }
169
+//
170
+//    /**
171
+//     * 根据id查询对象
172
+//     * @param id  实体ID
173
+//     */
174
+//    @RequestMapping(value="/taUser/{id}",method= RequestMethod.GET)
175
+//    @ApiOperation(value="详情", notes = "详情", httpMethod = "GET", response = ResponseBean.class)
176
+//    public ResponseBean taUserGet(@ApiParam("对象ID") @PathVariable Integer id) throws Exception{
177
+//        return ResponseBean.success(iTaUserService.getById(id));
178
+//    }
119 179
 }

+ 2
- 0
src/main/java/com/njyunzhi/ubpa/entity/TaUser.java Целия файл

@@ -55,4 +55,6 @@ public class TaUser implements Serializable {
55 55
     private LocalDateTime createDate;
56 56
 
57 57
 
58
+    @ApiModelProperty(value = "是否管理员")
59
+    private Boolean isAdmin;
58 60
 }

+ 1
- 0
src/main/java/com/njyunzhi/ubpa/service/ITaUserService.java Целия файл

@@ -12,4 +12,5 @@ import com.njyunzhi.ubpa.entity.TaUser;
12 12
  */
13 13
 public interface ITaUserService extends IBaseService<TaUser> {
14 14
 
15
+    TaUser getOrgAdmin(String orgId);
15 16
 }

+ 8
- 21
src/main/java/com/njyunzhi/ubpa/service/impl/ManagerServiceImpl.java Целия файл

@@ -1,41 +1,28 @@
1 1
 package com.njyunzhi.ubpa.service.impl;
2 2
 
3
-import com.njyunzhi.ubpa.common.Constants;
4
-import com.njyunzhi.ubpa.entity.SysUser;
3
+import cn.dev33.satoken.stp.StpInterface;
5 4
 import com.njyunzhi.ubpa.mapper.SysUserMapper;
6
-import com.njyunzhi.ubpa.shiro.realms.manager.IManagerService;
7 5
 import org.springframework.beans.factory.annotation.Autowired;
8 6
 import org.springframework.stereotype.Service;
9 7
 
10
-import java.util.HashSet;
11
-import java.util.Set;
8
+import java.util.ArrayList;
9
+import java.util.List;
12 10
 
13 11
 @Service
14
-public class ManagerServiceImpl implements IManagerService {
12
+public class ManagerServiceImpl implements StpInterface {
15 13
 
16 14
     @Autowired
17 15
     SysUserMapper sysUserMapper;
18 16
 
19
-    @Override
20
-    public Boolean verify(String id) {
21
-        SysUser sysUser = sysUserMapper.selectById(id);
22
-        if (null == sysUser || sysUser.getStatus() != Constants.STATUS_NORMAL) {
23
-            return false;
24
-        }
25
-
26
-        return true;
27
-    }
28 17
 
29 18
     @Override
30
-    public Set<String> getRolesByLoginId(String id) {
31
-//        SysUser sysUser = sysUserMapper.selectById(id);
32
-        return new HashSet();
19
+    public List<String> getRoleList(Object loginId, String loginType) {
20
+        return new ArrayList<>();
33 21
     }
34 22
 
35 23
     @Override
36
-    public Set<String> getPermissionsLoginId(String id) {
37
-//        SysUser sysUser = sysUserMapper.selectById(id);
38
-        return new HashSet();
24
+    public List<String> getPermissionList(Object loginId, String loginType) {
25
+        return new ArrayList<>();
39 26
     }
40 27
 
41 28
 }

+ 9
- 0
src/main/java/com/njyunzhi/ubpa/service/impl/TaUserServiceImpl.java Целия файл

@@ -1,5 +1,6 @@
1 1
 package com.njyunzhi.ubpa.service.impl;
2 2
 
3
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
3 4
 import com.njyunzhi.ubpa.entity.TaUser;
4 5
 import com.njyunzhi.ubpa.mapper.TaUserMapper;
5 6
 import com.njyunzhi.ubpa.service.ITaUserService;
@@ -16,4 +17,12 @@ import org.springframework.stereotype.Service;
16 17
 @Service
17 18
 public class TaUserServiceImpl extends BaseServiceImpl<TaUserMapper, TaUser> implements ITaUserService {
18 19
 
20
+    @Override
21
+    public TaUser getOrgAdmin(String orgId) {
22
+        QueryWrapper<TaUser> queryWrapper = new QueryWrapper<>();
23
+        queryWrapper.eq("org_id", orgId);
24
+        queryWrapper.eq("is_admin", 1);
25
+
26
+        return getOne(queryWrapper);
27
+    }
19 28
 }

+ 0
- 17
src/main/java/com/njyunzhi/ubpa/shiro/FirstExceptionStrategy.java Целия файл

@@ -1,17 +0,0 @@
1
-package com.njyunzhi.ubpa.shiro;
2
-
3
-import org.apache.shiro.authc.AuthenticationException;
4
-import org.apache.shiro.authc.AuthenticationInfo;
5
-import org.apache.shiro.authc.AuthenticationToken;
6
-import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy;
7
-import org.apache.shiro.realm.Realm;
8
-
9
-public class FirstExceptionStrategy extends AtLeastOneSuccessfulStrategy {
10
-
11
-    @Override
12
-    public AuthenticationInfo afterAttempt(Realm realm, AuthenticationToken token, AuthenticationInfo singleRealmInfo, AuthenticationInfo aggregateInfo, Throwable t) throws AuthenticationException {
13
-        if ((t instanceof AuthenticationException)) throw (AuthenticationException) t;
14
-        return super.afterAttempt(realm, token, singleRealmInfo, aggregateInfo, t);
15
-    }
16
-
17
-}

+ 0
- 103
src/main/java/com/njyunzhi/ubpa/shiro/ShiroConfig.java Целия файл

@@ -1,103 +0,0 @@
1
-package com.njyunzhi.ubpa.shiro;
2
-
3
-import com.njyunzhi.ubpa.shiro.filters.ManagerFilter;
4
-import com.njyunzhi.ubpa.shiro.filters.MiniappFilter;
5
-import com.njyunzhi.ubpa.shiro.matcher.JWTCredentialsMatcher;
6
-import com.njyunzhi.ubpa.shiro.realms.manager.IManagerService;
7
-import com.njyunzhi.ubpa.shiro.realms.manager.ManagerRealm;
8
-import com.njyunzhi.ubpa.shiro.realms.miniapp.MiniappRealm;
9
-import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy;
10
-import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
11
-import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
12
-import org.apache.shiro.mgt.DefaultSubjectDAO;
13
-import org.apache.shiro.realm.Realm;
14
-import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
15
-import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
16
-import org.springframework.beans.factory.annotation.Autowired;
17
-import org.springframework.beans.factory.annotation.Value;
18
-import org.springframework.context.annotation.Bean;
19
-import org.springframework.context.annotation.Configuration;
20
-
21
-import javax.servlet.Filter;
22
-import java.util.ArrayList;
23
-import java.util.HashMap;
24
-import java.util.List;
25
-import java.util.Map;
26
-
27
-@Configuration
28
-public class ShiroConfig {
29
-
30
-    @Autowired
31
-    IManagerService iManagerService;
32
-
33
-    @Value("${shiro.unauthorizedUrl}")
34
-    private String unauthorizedUrl;
35
-
36
-    @Value("#{${shiro.filterRuleMap}}")
37
-    private Map<String, String> filterRuleMap;
38
-
39
-    @Bean
40
-    public ManagerRealm managerRealm() {
41
-        ManagerRealm realm = new ManagerRealm();
42
-        realm.setManagerService(iManagerService);
43
-        realm.setCredentialsMatcher(new JWTCredentialsMatcher());
44
-        return realm;
45
-    }
46
-
47
-    @Bean
48
-    public MiniappRealm miniappRealm() {
49
-        MiniappRealm realm = new MiniappRealm();
50
-        realm.setCredentialsMatcher(new JWTCredentialsMatcher());
51
-        return realm;
52
-    }
53
-
54
-    @Bean("shiroFilterFactoryBean")
55
-    public ShiroFilterFactoryBean factory(DefaultWebSecurityManager securityManager) {
56
-        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
57
-
58
-        // 手动加入 Filter
59
-        ManagerFilter managerFilter = new ManagerFilter();
60
-        managerFilter.setUnauthorizedUrl(unauthorizedUrl);
61
-        MiniappFilter miniappFilter = new MiniappFilter();
62
-        miniappFilter.setUnauthorizedUrl(unauthorizedUrl);
63
-
64
-        Map<String, Filter> filterMap = new HashMap<>();
65
-        filterMap.put("manager", managerFilter);
66
-        filterMap.put("miniapp", miniappFilter);
67
-        factoryBean.setFilters(filterMap);
68
-
69
-        factoryBean.setSecurityManager(securityManager);
70
-        factoryBean.setUnauthorizedUrl(unauthorizedUrl);
71
-
72
-        factoryBean.setFilterChainDefinitionMap(filterRuleMap);
73
-        return factoryBean;
74
-    }
75
-
76
-    @Bean("securityManager")
77
-    public DefaultWebSecurityManager securityManager() {
78
-        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
79
-        // 修改多 Realm 的处理逻辑
80
-        ModularRealmAuthenticator realmAuthenticator = (ModularRealmAuthenticator) manager.getAuthenticator();
81
-        // 主要有一个 Realm 成功, 就立即返回
82
-        realmAuthenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
83
-//        realmAuthenticator.setAuthenticationStrategy(new FirstExceptionStrategy());
84
-
85
-        //  Use your own realm
86
-        List<Realm> realmList = new ArrayList<Realm>() {{
87
-            add(managerRealm());
88
-            add(miniappRealm());
89
-        }};
90
-        manager.setRealms(realmList);
91
-
92
-        /*
93
-         * 禁用 session
94
-         */
95
-        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
96
-        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
97
-        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
98
-        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
99
-        manager.setSubjectDAO(subjectDAO);
100
-
101
-        return manager;
102
-    }
103
-}

+ 0
- 94
src/main/java/com/njyunzhi/ubpa/shiro/filters/JWTFilter.java Целия файл

@@ -1,94 +0,0 @@
1
-package com.njyunzhi.ubpa.shiro.filters;
2
-
3
-import com.njyunzhi.ubpa.shiro.utils.JWTUtil;
4
-import org.apache.shiro.authc.AuthenticationException;
5
-import org.apache.shiro.authc.AuthenticationToken;
6
-import org.apache.shiro.subject.Subject;
7
-import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
8
-import org.apache.shiro.web.util.WebUtils;
9
-import org.slf4j.Logger;
10
-import org.slf4j.LoggerFactory;
11
-
12
-import javax.servlet.ServletRequest;
13
-import javax.servlet.ServletResponse;
14
-import javax.servlet.http.HttpServletResponse;
15
-import java.io.IOException;
16
-import java.io.UnsupportedEncodingException;
17
-import java.net.URLEncoder;
18
-
19
-public abstract class JWTFilter extends AuthenticatingFilter {
20
-
21
-    private Logger LOGGER = LoggerFactory.getLogger(this.getClass());
22
-
23
-    public final static String JWT_HEADER = "Authorization";
24
-
25
-    // token 刷新频率
26
-    private final static long REFRESH_MILLS = 99 * 24 * 60 * 1000;
27
-
28
-    private String unauthorizedUrl;
29
-    public void setUnauthorizedUrl(String unauthorizedUrl) {
30
-        this.unauthorizedUrl = unauthorizedUrl;
31
-    }
32
-
33
-    @Override
34
-    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
35
-        try {
36
-            return executeLogin(request, response);
37
-        } catch (Exception e) {
38
-            response401(request, response, e);
39
-        }
40
-
41
-        return false;
42
-    }
43
-
44
-    @Override
45
-    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
46
-        return false;
47
-    }
48
-
49
-    @Override
50
-    protected abstract AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception;
51
-
52
-    // 主要用来刷新 token
53
-    @Override
54
-    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
55
-        String originToken = token.getPrincipal().toString();
56
-
57
-        long diff = System.currentTimeMillis() - JWTUtil.getExpDate(originToken).getTime();
58
-        if (diff >= REFRESH_MILLS) {
59
-            HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
60
-            httpServletResponse.setHeader(JWT_HEADER, JWTUtil.refresh(originToken));
61
-        }
62
-
63
-        return true;
64
-    }
65
-
66
-    @Override
67
-    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
68
-        if (e != null) {
69
-            response401(request, response, e);
70
-        }
71
-
72
-        return false;
73
-    }
74
-
75
-    /**
76
-     *Jump illegal request to / 401
77
-     */
78
-    protected void response401(ServletRequest request, ServletResponse response, Exception e) {
79
-        String message = "";
80
-        if (e != null) {
81
-            try {
82
-                message = URLEncoder.encode(e.getMessage(), "UTF-8");
83
-            } catch (UnsupportedEncodingException ex) {
84
-                //
85
-            }
86
-        }
87
-
88
-        try {
89
-            WebUtils.toHttp(response).sendRedirect(unauthorizedUrl + "?msg=" + message);
90
-        } catch (IOException e1) {
91
-            LOGGER.error(e1.getMessage());
92
-        }
93
-    }
94
-}

+ 0
- 28
src/main/java/com/njyunzhi/ubpa/shiro/filters/ManagerFilter.java Целия файл

@@ -1,28 +0,0 @@
1
-package com.njyunzhi.ubpa.shiro.filters;
2
-
3
-import com.njyunzhi.ubpa.shiro.utils.JWTToken;
4
-import org.apache.shiro.authc.AuthenticationToken;
5
-import org.apache.shiro.web.util.WebUtils;
6
-
7
-import javax.servlet.ServletRequest;
8
-import javax.servlet.ServletResponse;
9
-import javax.servlet.http.HttpServletRequest;
10
-
11
-/**
12
- * ManagerFilter 与 MiniappFilter 实际上是一样的,只是返回的 token 类型不一致
13
- */
14
-public class ManagerFilter extends JWTFilter {
15
-
16
-    @Override
17
-    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
18
-        HttpServletRequest request = WebUtils.toHttp(servletRequest);
19
-        String authorization = request.getHeader(JWT_HEADER);
20
-        if (authorization == null || "".equals(authorization)) {
21
-            throw new Exception("请先登录系统");
22
-        }
23
-
24
-        return new JWTToken(authorization);
25
-    }
26
-
27
-
28
-}

+ 0
- 24
src/main/java/com/njyunzhi/ubpa/shiro/filters/MiniappFilter.java Целия файл

@@ -1,24 +0,0 @@
1
-package com.njyunzhi.ubpa.shiro.filters;
2
-
3
-import com.njyunzhi.ubpa.shiro.utils.MiniappToken;
4
-import org.apache.shiro.authc.AuthenticationToken;
5
-import org.apache.shiro.web.util.WebUtils;
6
-
7
-import javax.servlet.ServletRequest;
8
-import javax.servlet.ServletResponse;
9
-import javax.servlet.http.HttpServletRequest;
10
-
11
-public class MiniappFilter  extends JWTFilter {
12
-
13
-    @Override
14
-    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
15
-        HttpServletRequest request = WebUtils.toHttp(servletRequest);
16
-        String authorization = request.getHeader(JWT_HEADER);
17
-        if (authorization == null || "".equals(authorization)) {
18
-            throw new Exception("请先登录系统");
19
-        }
20
-
21
-        return new MiniappToken(authorization);
22
-    }
23
-
24
-}

+ 0
- 16
src/main/java/com/njyunzhi/ubpa/shiro/matcher/JWTCredentialsMatcher.java Целия файл

@@ -1,16 +0,0 @@
1
-package com.njyunzhi.ubpa.shiro.matcher;
2
-
3
-import org.apache.shiro.authc.AuthenticationInfo;
4
-import org.apache.shiro.authc.AuthenticationToken;
5
-import org.apache.shiro.authc.credential.CredentialsMatcher;
6
-
7
-public class JWTCredentialsMatcher implements CredentialsMatcher {
8
-    @Override
9
-    public boolean doCredentialsMatch(AuthenticationToken authenticationToken, AuthenticationInfo authenticationInfo) {
10
-//        String token = authenticationToken.getCredentials().toString();
11
-//        return JWTUtil.verify(token);
12
-
13
-        // 校验在 realm 做过了
14
-        return true;
15
-    }
16
-}

+ 0
- 31
src/main/java/com/njyunzhi/ubpa/shiro/realms/manager/IManagerService.java Целия файл

@@ -1,31 +0,0 @@
1
-package com.njyunzhi.ubpa.shiro.realms.manager;
2
-
3
-import java.util.Set;
4
-
5
-/**
6
- *
7
- */
8
-public interface IManagerService {
9
-
10
-    /**
11
-     * 校验用户状态
12
-     * @param id
13
-     * @return
14
-     */
15
-    Boolean verify(String id);
16
-
17
-    /**
18
-     * 获取用户角色
19
-     * @param id
20
-     * @return
21
-     */
22
-    Set<String> getRolesByLoginId(String id);
23
-
24
-    /**
25
-     * 获取用户权限
26
-     * @param id
27
-     * @return
28
-     */
29
-    Set<String> getPermissionsLoginId(String id);
30
-
31
-}

+ 0
- 77
src/main/java/com/njyunzhi/ubpa/shiro/realms/manager/ManagerRealm.java Целия файл

@@ -1,77 +0,0 @@
1
-package com.njyunzhi.ubpa.shiro.realms.manager;
2
-
3
-import com.auth0.jwt.exceptions.JWTDecodeException;
4
-import com.auth0.jwt.exceptions.TokenExpiredException;
5
-import com.njyunzhi.ubpa.shiro.utils.JWTToken;
6
-import com.njyunzhi.ubpa.shiro.utils.JWTUtil;
7
-import lombok.extern.slf4j.Slf4j;
8
-import org.apache.shiro.authc.*;
9
-import org.apache.shiro.authz.AuthorizationInfo;
10
-import org.apache.shiro.authz.SimpleAuthorizationInfo;
11
-import org.apache.shiro.realm.AuthorizingRealm;
12
-import org.apache.shiro.subject.PrincipalCollection;
13
-
14
-import java.util.Set;
15
-
16
-@Slf4j
17
-public class ManagerRealm extends AuthorizingRealm {
18
-
19
-    IManagerService iManagerService;
20
-
21
-    @Override
22
-    public String getName() {
23
-        return "managerRealm";
24
-    }
25
-
26
-    public void setManagerService(IManagerService iManagerService) {
27
-        this.iManagerService = iManagerService;
28
-    }
29
-
30
-    @Override
31
-    public boolean supports(AuthenticationToken token) {
32
-        return token instanceof JWTToken;
33
-    }
34
-
35
-    @Override
36
-    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
37
-        // 获取用户角色,权限
38
-        String token = (String) principalCollection.getPrimaryPrincipal();
39
-        String loginId = JWTUtil.getLoginId(token);
40
-        Set<String> roles = iManagerService.getRolesByLoginId(loginId);
41
-        Set<String> permissions = iManagerService.getPermissionsLoginId(loginId);
42
-
43
-        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
44
-        simpleAuthorizationInfo.setStringPermissions(permissions);
45
-        simpleAuthorizationInfo.setRoles(roles);
46
-        return simpleAuthorizationInfo;
47
-    }
48
-
49
-    @Override
50
-    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
51
-        log.info("===========ManagerRealm===========");
52
-
53
-        String token = (String) authenticationToken.getPrincipal();
54
-
55
-        // 这里进行 token 验证, CredentialsMatcher 就不做了
56
-        try {
57
-            JWTUtil.verify(token);
58
-        } catch (JWTDecodeException e1) {
59
-            throw new AuthenticationException("非法的权限凭证");
60
-        } catch (TokenExpiredException e2) {
61
-            throw new ExpiredCredentialsException("授权过期, 请重新登录");
62
-        } catch (Exception e) {
63
-            e.printStackTrace();
64
-            throw new AuthenticationException("凭证校验失败, 请重新登录");
65
-        }
66
-
67
-
68
-        String loginId = JWTUtil.getLoginId(token);
69
-
70
-        if (!iManagerService.verify(loginId)) {
71
-            throw new LockedAccountException("用户不存在或者状态异常");
72
-        }
73
-
74
-        // 交给 AuthenticatingRealm 使用 CredentialsMatcher 行校验
75
-        return new SimpleAuthenticationInfo(token, token, getName());
76
-    }
77
-}

+ 0
- 44
src/main/java/com/njyunzhi/ubpa/shiro/realms/miniapp/MiniappRealm.java Целия файл

@@ -1,44 +0,0 @@
1
-package com.njyunzhi.ubpa.shiro.realms.miniapp;
2
-
3
-import com.auth0.jwt.exceptions.JWTDecodeException;
4
-import com.auth0.jwt.exceptions.TokenExpiredException;
5
-import com.njyunzhi.ubpa.shiro.utils.JWTUtil;
6
-import com.njyunzhi.ubpa.shiro.utils.MiniappToken;
7
-import lombok.extern.slf4j.Slf4j;
8
-import org.apache.shiro.authc.*;
9
-import org.apache.shiro.realm.AuthenticatingRealm;
10
-
11
-@Slf4j
12
-public class MiniappRealm extends AuthenticatingRealm {
13
-
14
-    @Override
15
-    public String getName() {
16
-        return "miniappRealm";
17
-    }
18
-
19
-    @Override
20
-    public boolean supports(AuthenticationToken token) {
21
-        return token instanceof MiniappToken;
22
-    }
23
-
24
-    @Override
25
-    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
26
-        log.info("===========MiniappRealm===========");
27
-
28
-        String token = (String) authenticationToken.getPrincipal();
29
-
30
-        // 这里进行 token 验证, CredentialsMatcher 就不做了
31
-        try {
32
-            JWTUtil.verify(token);
33
-        } catch (JWTDecodeException e1) {
34
-            throw new AuthenticationException("非法的权限凭证");
35
-        } catch (TokenExpiredException e2) {
36
-            throw new ExpiredCredentialsException("授权过期, 请重新登录");
37
-        } catch (Exception e) {
38
-            e.printStackTrace();
39
-            throw new AuthenticationException("凭证校验失败, 请重新登录");
40
-        }
41
-        // 交给 AuthenticatingRealm 使用 CredentialsMatcher 行校验
42
-        return new SimpleAuthenticationInfo(token, token, getName());
43
-    }
44
-}

+ 0
- 23
src/main/java/com/njyunzhi/ubpa/shiro/utils/JWTToken.java Целия файл

@@ -1,23 +0,0 @@
1
-package com.njyunzhi.ubpa.shiro.utils;
2
-
3
-import org.apache.shiro.authc.AuthenticationToken;
4
-
5
-public class JWTToken implements AuthenticationToken {
6
-
7
-    //Key
8
-    private String token;
9
-
10
-    public JWTToken(String token) {
11
-        this.token = token;
12
-    }
13
-
14
-    @Override
15
-    public Object getPrincipal() {
16
-        return token;
17
-    }
18
-
19
-    @Override
20
-    public Object getCredentials() {
21
-        return token;
22
-    }
23
-}

+ 0
- 66
src/main/java/com/njyunzhi/ubpa/shiro/utils/JWTUtil.java Целия файл

@@ -1,66 +0,0 @@
1
-package com.njyunzhi.ubpa.shiro.utils;
2
-
3
-import com.auth0.jwt.JWT;
4
-import com.auth0.jwt.algorithms.Algorithm;
5
-import com.auth0.jwt.exceptions.JWTDecodeException;
6
-import com.auth0.jwt.exceptions.JWTVerificationException;
7
-import com.auth0.jwt.interfaces.DecodedJWT;
8
-import com.auth0.jwt.interfaces.JWTVerifier;
9
-
10
-import java.util.Date;
11
-
12
-/**
13
- * 一个通用版本的 JWT
14
- */
15
-public class JWTUtil {
16
-
17
-    // token 生存周期
18
-    private static final long EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000;
19
-
20
-    public static String getLoginId(String token) {
21
-        try {
22
-            DecodedJWT jwt = JWT.decode(token);
23
-            return jwt.getSubject();
24
-        } catch (JWTDecodeException e) {
25
-            return null;
26
-        }
27
-    }
28
-
29
-    public static Date getExpDate(String token) {
30
-        try {
31
-            DecodedJWT jwt = JWT.decode(token);
32
-            return jwt.getExpiresAt();
33
-        } catch (JWTDecodeException e) {
34
-            return null;
35
-        }
36
-    }
37
-
38
-    public static String sign(String loginId, String secret) {
39
-        Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME);
40
-        Algorithm algorithm = Algorithm.HMAC256(secret);
41
-
42
-        return JWT.create()
43
-                .withSubject(loginId)
44
-                .withExpiresAt(date)
45
-                .withClaim("secret", secret)
46
-                .sign(algorithm);
47
-    }
48
-
49
-    public static String refresh(String token) throws Exception {
50
-        DecodedJWT jwt = JWT.decode(token);
51
-        String loginId = jwt.getSubject();
52
-        String secret = jwt.getClaim("secret").asString();
53
-
54
-        return sign(loginId, secret);
55
-    }
56
-
57
-    public static void verify(String token) throws JWTVerificationException {
58
-        DecodedJWT jwt = JWT.decode(token);
59
-        String loginId = jwt.getSubject();
60
-        String secret = jwt.getClaim("secret").asString();
61
-        Algorithm algorithm = Algorithm.HMAC256(secret);
62
-        JWTVerifier verifier = JWT.require(algorithm).withSubject(loginId).build();
63
-        verifier.verify(jwt);
64
-    }
65
-
66
-}

+ 0
- 23
src/main/java/com/njyunzhi/ubpa/shiro/utils/MiniappToken.java Целия файл

@@ -1,23 +0,0 @@
1
-package com.njyunzhi.ubpa.shiro.utils;
2
-
3
-import org.apache.shiro.authc.AuthenticationToken;
4
-
5
-public class MiniappToken implements AuthenticationToken {
6
-
7
-    //Key
8
-    private String token;
9
-
10
-    public MiniappToken(String token) {
11
-        this.token = token;
12
-    }
13
-
14
-    @Override
15
-    public Object getPrincipal() {
16
-        return token;
17
-    }
18
-
19
-    @Override
20
-    public Object getCredentials() {
21
-        return token;
22
-    }
23
-}

+ 3
- 0
src/main/resources/application-prod.yml Целия файл

@@ -1,3 +1,6 @@
1
+server:
2
+  port: 9000
3
+
1 4
 ###
2 5
 spring:
3 6
   servlet:

+ 18
- 15
src/main/resources/application.yml Целия файл

@@ -4,21 +4,24 @@ server:
4 4
   servlet:
5 5
     context-path: /api
6 6
 
7
-###
8
-shiro:
9
-  enabled: true
10
-  unauthorizedUrl: /api/401
11
-  filterRuleMap: '{
12
-    "/wxpay/notify/**": "anon",
13
-    "/**/sms-captcha": "anon",
14
-    "/**/oss-sts": "anon",
15
-    "/**/preload": "anon",
16
-    "/**/login": "anon",
17
-    "/**/**/login": "anon",
18
-    "/admin/**": "manager",
19
-    "/wx/**": "miniapp",
20
-    "/**": "anon"
21
-  }'
7
+# Sa-Token配置
8
+sa-token:
9
+  # jwt秘钥
10
+  jwt-secret-key: Q920tdPkkDxnSv4dd6cqE6jNDT2OKT7L
11
+  # token名称 (同时也是cookie名称)
12
+  token-name: Authorization
13
+  # token有效期,单位s 默认30天, -1代表永不过期
14
+  timeout: 2592000
15
+  # token临时有效期 (指定时间内无操作就视为token过期) 单位: 秒
16
+  activity-timeout: -1
17
+  # 是否允许同一账号并发登录 (为true时允许一起登录, 为false时新登录挤掉旧登录)
18
+  is-concurrent: true
19
+  # 在多人登录同一账号时,是否共用一个token (为true时所有登录共用一个token, 为false时每次登录新建一个token)
20
+  is-share: false
21
+  # token风格
22
+  token-style: uuid
23
+  # 是否输出操作日志
24
+  is-log: false
22 25
 
23 26
 ###
24 27
 mybatis-plus: