Skip to content

Commit e6bbc1a

Browse files
committed
feat: update code
1 parent ab09451 commit e6bbc1a

File tree

18 files changed

+147
-109
lines changed

18 files changed

+147
-109
lines changed

dc3-api/dc3-api-auth/src/main/java/io/github/pnoker/api/center/auth/feign/BlackIpClient.java

+4-4
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ public interface BlackIpClient {
4444
/**
4545
* 新增 BlackIp
4646
*
47-
* @param blackIp BlackIp
47+
* @param blackIp BlackIp
4848
* @return BlackIp
4949
*/
5050
@PostMapping("/add")
@@ -65,7 +65,7 @@ public interface BlackIpClient {
6565
* 支 持: Enable
6666
* 不支持: Ip
6767
*
68-
* @param blackIp BlackIp
68+
* @param blackIp BlackIp
6969
* @return BlackIp
7070
*/
7171
@PostMapping("/update")
@@ -83,7 +83,7 @@ public interface BlackIpClient {
8383
/**
8484
* 根据 Ip 查询 BlackIp
8585
*
86-
* @param ip Black Ip
86+
* @param ip Black Ip
8787
* @return BlackIp
8888
*/
8989
@GetMapping("/ip/{ip}")
@@ -101,7 +101,7 @@ public interface BlackIpClient {
101101
/**
102102
* 检测 Ip 是否在 Ip 黑名单列表
103103
*
104-
* @param ip Black Ip
104+
* @param ip Black Ip
105105
* @return Boolean
106106
*/
107107
@GetMapping("/check/{ip}")

dc3-center/dc3-center-auth/src/main/java/io/github/pnoker/center/auth/api/TokenApi.java

+4-4
Original file line numberDiff line numberDiff line change
@@ -45,19 +45,19 @@ public class TokenApi implements TokenClient {
4545

4646
@Override
4747
public R<String> generateSalt(Login login) {
48-
String salt = tokenService.generateSalt(login.getName());
48+
String salt = tokenService.generateSalt(login.getName(), login.getTenant());
4949
return null != salt ? R.ok(salt, "The salt will expire in 5 minutes") : R.fail();
5050
}
5151

5252
@Override
5353
public R<String> generateToken(Login login) {
54-
String token = tokenService.generateToken(login.getTenant(), login.getName(), login.getSalt(), login.getPassword());
54+
String token = tokenService.generateToken(login.getName(), login.getSalt(), login.getPassword(), login.getTenant());
5555
return null != token ? R.ok(token, "The token will expire in 12 hours.") : R.fail();
5656
}
5757

5858
@Override
5959
public R<String> checkTokenValid(Login login) {
60-
TokenValid tokenValid = tokenService.checkTokenValid(login.getName(), login.getSalt(), login.getToken());
60+
TokenValid tokenValid = tokenService.checkTokenValid(login.getName(), login.getSalt(), login.getToken(), login.getTenant());
6161
if (tokenValid.isValid()) {
6262
String expireTime = Dc3Util.formatCompleteData(tokenValid.getExpireTime());
6363
return R.ok(expireTime, "The token will expire in " + expireTime);
@@ -67,6 +67,6 @@ public R<String> checkTokenValid(Login login) {
6767

6868
@Override
6969
public R<Boolean> cancelToken(Login login) {
70-
return tokenService.cancelToken(login.getName()) ? R.ok() : R.fail();
70+
return tokenService.cancelToken(login.getName(), login.getTenant()) ? R.ok() : R.fail();
7171
}
7272
}

dc3-center/dc3-center-auth/src/main/java/io/github/pnoker/center/auth/service/TokenService.java

+15-12
Original file line numberDiff line numberDiff line change
@@ -27,35 +27,38 @@ public interface TokenService {
2727
/**
2828
* 生成用户的随机 salt
2929
*
30-
* @param username Username
30+
* @param username Username
31+
* @param tenantName Tenant Name
3132
* @return String
3233
*/
33-
String generateSalt(String username);
34+
String generateSalt(String username, String tenantName);
3435

3536
/**
3637
* 生成用户的Token令牌
3738
*
38-
* @param tenant Tenant
39-
* @param name User Name
40-
* @param salt User Salt
41-
* @param password User Password
39+
* @param username User Name
40+
* @param salt User Salt
41+
* @param password User Password
42+
* @param tenantName Tenant Name
4243
* @return String
4344
*/
44-
String generateToken(String tenant, String name, String salt, String password);
45+
String generateToken(String username, String salt, String password, String tenantName);
4546

4647
/**
4748
* 校验用户的Token令牌是否有效
4849
*
49-
* @param username Username
50-
* @param token Token
50+
* @param username Username
51+
* @param token Token
52+
* @param tenantName Tenant Name
5153
* @return TokenValid
5254
*/
53-
TokenValid checkTokenValid(String username, String salt, String token);
55+
TokenValid checkTokenValid(String username, String salt, String token, String tenantName);
5456

5557
/**
5658
* 注销用户的Token令牌
5759
*
58-
* @param username Username
60+
* @param username Username
61+
* @param tenantName Tenant Name
5962
*/
60-
boolean cancelToken(String username);
63+
boolean cancelToken(String username, String tenantName);
6164
}

dc3-center/dc3-center-auth/src/main/java/io/github/pnoker/center/auth/service/impl/TokenServiceImpl.java

+25-18
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,9 @@ public class TokenServiceImpl implements TokenService {
6363
private RedisUtil redisUtil;
6464

6565
@Override
66-
public String generateSalt(String username) {
66+
public String generateSalt(String username, String tenantName) {
67+
// todo 此处一个bug,会抛异常,导致无法记录失败登录次数
68+
Tenant tenant = tenantService.selectByName(tenantName);
6769
String redisSaltKey = CacheConstant.Entity.USER + CacheConstant.Suffix.SALT + CommonConstant.Symbol.SEPARATOR + username;
6870
String salt = redisUtil.getKey(redisSaltKey, String.class);
6971
if (StrUtil.isBlank(salt)) {
@@ -74,43 +76,48 @@ public String generateSalt(String username) {
7476
}
7577

7678
@Override
77-
public String generateToken(String tenant, String name, String salt, String password) {
78-
checkUserLimit(name);
79-
Tenant tempTenant = tenantService.selectByName(tenant);
80-
User tempUser = userService.selectByName(name, false);
81-
if (tempTenant.getEnable() && tempUser.getEnable()) {
82-
tenantBindService.selectByTenantIdAndUserId(tempTenant.getId(), tempUser.getId());
83-
String redisSaltKey = CacheConstant.Entity.USER + CacheConstant.Suffix.SALT + CommonConstant.Symbol.SEPARATOR + name;
84-
String tempSalt = redisUtil.getKey(redisSaltKey, String.class);
85-
if (StrUtil.isNotEmpty(tempSalt) && tempSalt.equals(salt)) {
86-
if (Dc3Util.md5(tempUser.getPassword() + tempSalt).equals(password)) {
87-
String redisTokenKey = CacheConstant.Entity.USER + CacheConstant.Suffix.TOKEN + CommonConstant.Symbol.SEPARATOR + name;
88-
String token = KeyUtil.generateToken(name, tempSalt);
79+
public String generateToken(String username, String salt, String password, String tenantName) {
80+
checkUserLimit(username);
81+
// todo 此处一个bug,会抛异常,导致无法记录失败登录次数
82+
Tenant tenant = tenantService.selectByName(tenantName);
83+
User user = userService.selectByName(username, false);
84+
if (tenant.getEnable() && user.getEnable()) {
85+
tenantBindService.selectByTenantIdAndUserId(tenant.getId(), user.getId());
86+
String redisSaltKey = CacheConstant.Entity.USER + CacheConstant.Suffix.SALT + CommonConstant.Symbol.SEPARATOR + username;
87+
String saltValue = redisUtil.getKey(redisSaltKey, String.class);
88+
if (StrUtil.isNotEmpty(saltValue) && saltValue.equals(salt)) {
89+
if (Dc3Util.md5(user.getPassword() + saltValue).equals(password)) {
90+
String redisTokenKey = CacheConstant.Entity.USER + CacheConstant.Suffix.TOKEN + CommonConstant.Symbol.SEPARATOR + username;
91+
String token = KeyUtil.generateToken(username, saltValue, tenant.getId());
8992
redisUtil.setKey(redisTokenKey, token, CacheConstant.Timeout.TOKEN_CACHE_TIMEOUT, TimeUnit.HOURS);
9093
return token;
9194
}
9295
}
9396
}
94-
updateUserLimit(name, true);
95-
throw new ServiceException("Invalid tenant、username、password");
97+
updateUserLimit(username, true);
98+
throw new ServiceException("Invalid username、password、tenant");
9699
}
97100

98101
@Override
99-
public TokenValid checkTokenValid(String username, String salt, String token) {
102+
public TokenValid checkTokenValid(String username, String salt, String token, String tenantName) {
103+
// todo 此处一个bug,会抛异常,导致无法记录失败登录次数
104+
Tenant tenant = tenantService.selectByName(tenantName);
100105
String redisToken = redisUtil.getKey(CacheConstant.Entity.USER + CacheConstant.Suffix.TOKEN + CommonConstant.Symbol.SEPARATOR + username, String.class);
101106
if (StrUtil.isBlank(redisToken) || !redisToken.equals(token)) {
102107
return new TokenValid(false, null);
103108
}
104109
try {
105-
Claims claims = KeyUtil.parserToken(username, salt, token);
110+
// todo 需要传 tenantId
111+
Claims claims = KeyUtil.parserToken(username, salt, token, tenant.getId());
106112
return new TokenValid(true, claims.getExpiration());
107113
} catch (Exception e) {
108114
return new TokenValid(false, null);
109115
}
110116
}
111117

112118
@Override
113-
public boolean cancelToken(String username) {
119+
public boolean cancelToken(String username, String tenantName) {
120+
Tenant tenant = tenantService.selectByName(tenantName);
114121
redisUtil.deleteKey(CacheConstant.Entity.USER + CacheConstant.Suffix.TOKEN + CommonConstant.Symbol.SEPARATOR + username);
115122
return true;
116123
}

dc3-common/dc3-common-base/pom.xml

+6
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,12 @@
3838
<artifactId>spring-web</artifactId>
3939
</dependency>
4040

41+
<!-- Spring Aop -->
42+
<dependency>
43+
<groupId>org.springframework</groupId>
44+
<artifactId>spring-aspects</artifactId>
45+
</dependency>
46+
4147
<!-- Spring Data MongoDB -->
4248
<dependency>
4349
<groupId>org.springframework.data</groupId>

dc3-common/dc3-common-core/src/main/java/io/github/pnoker/common/annotation/LogsAspect.java dc3-common/dc3-common-base/src/main/java/io/github/pnoker/common/annotation/LogsAspect.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ public void logsCut() {
4040
}
4141

4242
// 2022-03-13 检查:通过
43-
@Around("logsCut()&&@annotation(logs)")
43+
@Around("logsCut() && @annotation(logs)")
4444
public Object doAround(ProceedingJoinPoint proceedingJoinPoint, Logs logs) throws Throwable {
4545
String uuid = IdUtil.fastSimpleUUID();
4646
String className = proceedingJoinPoint.getSignature().getDeclaringType().getSimpleName();
@@ -49,7 +49,7 @@ public Object doAround(ProceedingJoinPoint proceedingJoinPoint, Logs logs) throw
4949
log.info("Start => [{}].[{}.{}]: {}", uuid, className, methodName, logs.value());
5050
try {
5151
Object proceed = proceedingJoinPoint.proceed();
52-
log.info("End <= [{}].[{}.{}].[{}ms]: {}", uuid, className, methodName, System.currentTimeMillis() - startTime, logs.value());
52+
log.info("End <= [{}].[{}.{}].[{}ms]: {}", uuid, className, methodName, System.currentTimeMillis() - startTime, logs.value());
5353
return proceed;
5454
} catch (Throwable throwable) {
5555
log.info("End <= [{}].[{}.{}].[{}ms]: {}", uuid, className, methodName, System.currentTimeMillis() - startTime, logs.value());

dc3-common/dc3-common-base/src/main/java/io/github/pnoker/common/constant/CommonConstant.java

+6-1
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,11 @@ interface Symbol {
5151
* 分隔符
5252
*/
5353
String SEPARATOR = "::";
54+
55+
/**
56+
* 斜线
57+
*/
58+
String SLASH = "/";
5459
}
5560

5661
/**
@@ -60,7 +65,7 @@ interface Algorithm {
6065
/**
6166
* 默认密钥
6267
*/
63-
String DEFAULT_KEY = "pnoker/dc3";
68+
String DEFAULT_KEY = "io.github.pnoker.dc3";
6469

6570
/**
6671
* 默认密码

dc3-common/dc3-common-base/src/main/java/io/github/pnoker/common/constant/ServiceConstant.java

+3-4
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,11 @@ public interface ServiceConstant {
2727
* 请求 Header 相关
2828
*/
2929
interface Header {
30+
String X_AUTH_TENANT_ID = "X-Auth-Tenant-Id";
31+
String X_AUTH_TENANT = "X-Auth-Tenant";
32+
String X_AUTH_USER_ID = "X-Auth-User-Id";
3033
String X_AUTH_USER = "X-Auth-User";
31-
String X_AUTH_SALT = "X-Auth-Salt";
3234
String X_AUTH_TOKEN = "X-Auth-Token";
33-
String X_AUTH_USER_ID = "X-Auth-User-Id";
34-
String X_AUTH_TENANT = "X-Auth-Tenant";
35-
String X_AUTH_TENANT_ID = "X-Auth-Tenant-Id";
3635
}
3736

3837
/**

dc3-common/dc3-common-base/src/main/java/io/github/pnoker/common/utils/Dc3Util.java

-35
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
import cn.hutool.crypto.digest.MD5;
2121
import io.github.pnoker.common.bean.TreeNode;
2222
import io.github.pnoker.common.constant.CommonConstant;
23-
import io.github.pnoker.common.constant.ServiceConstant;
2423
import lombok.extern.slf4j.Slf4j;
2524
import org.apache.commons.fileupload.FileItem;
2625
import org.apache.commons.fileupload.FileItemFactory;
@@ -536,38 +535,4 @@ public static String getRequestHeader(HttpServletRequest httpServletRequest, Str
536535
return httpServletRequest.getHeader(key);
537536
}
538537

539-
/**
540-
* 从 Request 中获取指定 User ID 的 Header 值
541-
*
542-
* @param httpServletRequest HttpServletRequest
543-
* @return String
544-
*/
545-
public static String getRequestUserId(HttpServletRequest httpServletRequest) {
546-
String userId = Long.toString(-1L);
547-
String header = getRequestHeader(httpServletRequest, ServiceConstant.Header.X_AUTH_USER_ID);
548-
try {
549-
userId = header.trim();
550-
return userId;
551-
} catch (Exception e) {
552-
return userId;
553-
}
554-
}
555-
556-
/**
557-
* 从 Request 中获取指定 Tenant ID 的 Header 值
558-
*
559-
* @param httpServletRequest HttpServletRequest
560-
* @return String
561-
*/
562-
public static String getRequestTenantId(HttpServletRequest httpServletRequest) {
563-
String tenantId = Long.toString(-1L);
564-
String header = getRequestHeader(httpServletRequest, ServiceConstant.Header.X_AUTH_TENANT_ID);
565-
try {
566-
tenantId = header.trim();
567-
return tenantId;
568-
} catch (Exception e) {
569-
return tenantId;
570-
}
571-
}
572-
573538
}

dc3-common/dc3-common-base/src/main/java/io/github/pnoker/common/utils/KeyUtil.java

+4-4
Original file line numberDiff line numberDiff line change
@@ -161,9 +161,9 @@ public static String decryptRsa(String str, String privateKey) throws Exception
161161
* @param username String
162162
* @return String
163163
*/
164-
public static String generateToken(String username, String salt) {
164+
public static String generateToken(String username, String salt, String tenantId) {
165165
JwtBuilder builder = Jwts.builder()
166-
.setIssuer(CommonConstant.Algorithm.DEFAULT_KEY)
166+
.setIssuer(CommonConstant.Algorithm.DEFAULT_KEY + CommonConstant.Symbol.SLASH + tenantId)
167167
.setSubject(username)
168168
.setIssuedAt(new Date())
169169
.signWith(SignatureAlgorithm.HS256, salt.getBytes(StandardCharsets.UTF_8))
@@ -179,9 +179,9 @@ public static String generateToken(String username, String salt) {
179179
* @param token String
180180
* @return Claims
181181
*/
182-
public static Claims parserToken(String username, String salt, String token) {
182+
public static Claims parserToken(String username, String salt, String token, String tenantId) {
183183
return Jwts.parser()
184-
.requireIssuer(CommonConstant.Algorithm.DEFAULT_KEY)
184+
.requireIssuer(CommonConstant.Algorithm.DEFAULT_KEY+ CommonConstant.Symbol.SLASH + tenantId)
185185
.requireSubject(username)
186186
.setSigningKey(salt.getBytes(StandardCharsets.UTF_8))
187187
.parseClaimsJws(token)
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
2-
io.github.pnoker.common.exception.GlobalExceptionAdvice
2+
io.github.pnoker.common.exception.GlobalExceptionAdvice,\
3+
io.github.pnoker.common.annotation.LogsAspect

dc3-common/dc3-common-core/pom.xml

-6
Original file line numberDiff line numberDiff line change
@@ -71,12 +71,6 @@
7171
<artifactId>spring-webmvc</artifactId>
7272
</dependency>
7373

74-
<!-- Spring Aop -->
75-
<dependency>
76-
<groupId>org.springframework</groupId>
77-
<artifactId>spring-aspects</artifactId>
78-
</dependency>
79-
8074
<!-- Dc3 Common Base -->
8175
<dependency>
8276
<groupId>io.github.pnoker</groupId>

dc3-common/dc3-common-core/src/main/resources/META-INF/spring.factories

+1-2
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,4 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
55
io.github.pnoker.common.config.RedisCacheConfig,\
66
io.github.pnoker.common.config.ThreadPoolConfig,\
77
io.github.pnoker.common.config.WebMvcConfig,\
8-
io.github.pnoker.common.utils.RedisUtil,\
9-
io.github.pnoker.common.annotation.LogsAspect
8+
io.github.pnoker.common.utils.RedisUtil
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
* Copyright 2022 Pnoker All Rights Reserved
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package io.github.pnoker.gateway.bean;
18+
19+
import lombok.AllArgsConstructor;
20+
import lombok.Data;
21+
import lombok.NoArgsConstructor;
22+
import lombok.experimental.Accessors;
23+
24+
/**
25+
* Request Token Header
26+
*
27+
* @author pnoker
28+
*/
29+
@Data
30+
@NoArgsConstructor
31+
@AllArgsConstructor
32+
@Accessors(chain = true)
33+
public class TokenRequestHeader {
34+
private String salt;
35+
private String token;
36+
}

0 commit comments

Comments
 (0)