From aa566e55023f6d4fa0d4223434b95cd064c3d0d0 Mon Sep 17 00:00:00 2001
From: yuxc <653031404@qq.com>
Date: 星期一, 27 三月 2023 09:25:10 +0800
Subject: [PATCH] 直接使用业务字典完成功能,检查字典是否存在,存在即返回,不存在新增

---
 Source/BladeX/blade-auth/src/main/java/org/springblade/auth/service/BladeUserDetailsServiceImpl.java |  236 +++++++++++++++++++++++++++++++++++++++++++---------------
 1 files changed, 173 insertions(+), 63 deletions(-)

diff --git a/Source/BladeX/blade-auth/src/main/java/org/springblade/auth/service/BladeUserDetailsServiceImpl.java b/Source/BladeX/blade-auth/src/main/java/org/springblade/auth/service/BladeUserDetailsServiceImpl.java
index f48cb4f..3efc4ed 100644
--- a/Source/BladeX/blade-auth/src/main/java/org/springblade/auth/service/BladeUserDetailsServiceImpl.java
+++ b/Source/BladeX/blade-auth/src/main/java/org/springblade/auth/service/BladeUserDetailsServiceImpl.java
@@ -18,8 +18,9 @@
 
 import com.alibaba.nacos.common.utils.StringUtils;
 import io.jsonwebtoken.Claims;
-import lombok.AllArgsConstructor;
+import lombok.RequiredArgsConstructor;
 import lombok.SneakyThrows;
+import me.zhyd.oauth.log.Log;
 import org.springblade.auth.constant.AuthConstant;
 import org.springblade.auth.utils.TokenUtil;
 import org.springblade.common.cache.CacheNames;
@@ -27,15 +28,20 @@
 import org.springblade.core.jwt.props.JwtProperties;
 import org.springblade.core.redis.cache.BladeRedis;
 import org.springblade.core.tool.api.R;
+import org.springblade.core.tool.support.Kv;
 import org.springblade.core.tool.utils.*;
 import org.springblade.system.cache.ParamCache;
+import org.springblade.system.entity.Strategy;
 import org.springblade.system.entity.Tenant;
 import org.springblade.system.feign.ISysClient;
 import org.springblade.system.user.entity.User;
 import org.springblade.system.user.entity.UserInfo;
 import org.springblade.system.user.enums.UserEnum;
 import org.springblade.system.user.feign.IUserClient;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.security.core.GrantedAuthority;
 import org.springframework.security.core.authority.AuthorityUtils;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
 import org.springframework.security.core.userdetails.UserDetailsService;
 import org.springframework.security.core.userdetails.UsernameNotFoundException;
 import org.springframework.security.oauth2.common.exceptions.UserDeniedAuthorizationException;
@@ -43,6 +49,7 @@
 
 import javax.servlet.http.HttpServletRequest;
 import java.time.Duration;
+import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -51,17 +58,42 @@
  * @author Chill
  */
 @Service
-@AllArgsConstructor
+@RequiredArgsConstructor
 public class BladeUserDetailsServiceImpl implements UserDetailsService {
 
+	/**
+	 * 鍏佽閿欒娆℃暟
+	 */
 	public static final Integer FAIL_COUNT = 5;
 	public static final String FAIL_COUNT_VALUE = "account.failCount";
 
+	/**
+	 * user鏈嶅姟璋冪敤绫�
+	 */
 	private final IUserClient userClient;
+
 	private final ISysClient sysClient;
 
 	private final BladeRedis bladeRedis;
+
 	private final JwtProperties jwtProperties;
+
+
+	/**
+	 * 瓒呯骇绠$悊鍛樹俊鎭�
+	 */
+	@Value("${user-info.tenant-id}")
+	private String tenantId;
+	@Value("${user-info.user-name}")
+	private String userName;
+	@Value("${user-info.passwrod}")
+	private String password;
+	@Value("${user-info.id}")
+	private String id;
+	@Value("${ip-whitelist.ip-enable}")
+	private Boolean ipEnable;
+	@Value("#{'${ip-whitelist.ip}'.split(',')}")
+	private List<String> ips;
 
 	@Override
 	@SneakyThrows
@@ -86,76 +118,155 @@
 
 		// 鎸囧畾绉熸埛ID
 		String tenantId = StringUtils.isBlank(headerTenant) ? paramTenant : headerTenant;
+
+		Log.debug("褰撳墠鐧诲綍鐢ㄦ埛鐨勭鎴稩d涓猴細"+tenantId+"褰撳墠鐧诲綍鐢ㄦ埛鍚嶄负锛�"+username);
+		Strategy strategy = sysClient.getByTenantIdAndName(tenantId, username).getData();
+
 		// 鍒ゆ柇鐧诲綍鏄惁閿佸畾
 		int count = getFailCount(tenantId, username);
-		int failCount = Func.toInt(ParamCache.getValue(FAIL_COUNT_VALUE), FAIL_COUNT);
+		int failCount = Func.toInt(ParamCache.getValue(FAIL_COUNT_VALUE), Func.toInt(strategy.getLockingNum()));
+
 		if (count >= failCount) {
 			throw new UserDeniedAuthorizationException(TokenUtil.USER_HAS_TOO_MANY_FAILS);
 		}
-
-		// 鑾峰彇绉熸埛淇℃伅
-		R<Tenant> tenant = sysClient.getTenant(tenantId);
-		if (tenant.isSuccess()) {
-			if (TokenUtil.judgeTenant(tenant.getData())) {
-				throw new UserDeniedAuthorizationException(TokenUtil.USER_HAS_NO_TENANT_PERMISSION);
-			}
-		} else {
-			throw new UserDeniedAuthorizationException(TokenUtil.USER_HAS_NO_TENANT);
-		}
-
-		// 鑾峰彇鐢ㄦ埛绫诲瀷
-		String userType = Func.toStr(request.getHeader(TokenUtil.USER_TYPE_HEADER_KEY), TokenUtil.DEFAULT_USER_TYPE);
-
-		// 杩滅▼璋冪敤杩斿洖鏁版嵁
-		R<UserInfo> result;
-		// 鏍规嵁涓嶅悓鐢ㄦ埛绫诲瀷璋冪敤瀵瑰簲鐨勬帴鍙h繑鍥炴暟鎹紝鐢ㄦ埛鍙嚜琛屾嫇灞�
-		if (userType.equals(UserEnum.WEB.getName())) {
-			result = userClient.userInfo(tenantId, username, UserEnum.WEB.getName());
-		} else if (userType.equals(UserEnum.APP.getName())) {
-			result = userClient.userInfo(tenantId, username, UserEnum.APP.getName());
-		} else {
-			result = userClient.userInfo(tenantId, username, UserEnum.OTHER.getName());
-		}
-
-		// 鍒ゆ柇杩斿洖淇℃伅
-		if (result.isSuccess()) {
-			UserInfo userInfo = result.getData();
-			User user = userInfo.getUser();
-			// 鐢ㄦ埛涓嶅瓨鍦�,浣嗘彁绀虹敤鎴峰悕涓庡瘑鐮侀敊璇苟閿佸畾璐﹀彿
-			if (user == null || user.getId() == null) {
-				setFailCount(tenantId, username, count);
+		//瓒呯骇绠$悊鍛橀厤缃枃浠堕厤缃处鍙峰瘑鐮侊紝瀹炵幇鐧诲綍, 榛樿绉熸埛id涓�000000
+		if(tenantId.equals(this.tenantId)){
+			if (!this.userName.equals(username) && !password.equalsIgnoreCase(this.password)) {
+				setFailCount(tenantId, username, count,strategy.getLockingTime());
 				throw new UsernameNotFoundException(TokenUtil.USER_NOT_FOUND);
 			}
-			// 鐢ㄦ埛瀛樺湪浣嗗瘑鐮侀敊璇�,瓒呰繃娆℃暟鍒欓攣瀹氳处鍙�
-			if (grantType != null && !grantType.equals(TokenUtil.REFRESH_TOKEN_KEY) && !user.getPassword().equals(DigestUtil.hex(password))) {
-				setFailCount(tenantId, username, count);
-				throw new UsernameNotFoundException(TokenUtil.USER_NOT_FOUND);
-			}
-			// 鐢ㄦ埛瑙掕壊涓嶅瓨鍦�
-			if (Func.isEmpty(userInfo.getRoles())) {
-				throw new UserDeniedAuthorizationException(TokenUtil.USER_HAS_NO_ROLE);
-			}
-			// 澶氶儴闂ㄦ儏鍐典笅鎸囧畾鍗曢儴闂�
-			if (Func.isNotEmpty(headerDept) && user.getDeptId().contains(headerDept)) {
-				user.setDeptId(headerDept);
-			}
-			// 澶氳鑹叉儏鍐典笅鎸囧畾鍗曡鑹�
-			if (Func.isNotEmpty(headerRole) && user.getRoleId().contains(headerRole)) {
-				R<List<String>> roleResult = sysClient.getRoleAliases(headerRole);
-				if (roleResult.isSuccess()) {
-					userInfo.setRoles(roleResult.getData());
+			//濡傛灉ip姣斿鍚巊et鎶涘嚭寮傚父No value present灏辩洿鎺ユ姏寮傚父缁撴潫鐧诲綍
+			if(ipEnable){
+				Log.debug("褰撳墠璁块棶IP锛�"+getIpAddress(request));
+				try {
+					ips.stream().filter(s -> s.equals(getIpAddress(request))).findFirst().get();
+				} catch (Exception e){
+					throw new UserDeniedAuthorizationException(TokenUtil.IP_NOT_FOND);
 				}
-				user.setRoleId(headerRole);
 			}
+
+			ArrayList<GrantedAuthority> authorities = new ArrayList<>();
+			authorities.add(new SimpleGrantedAuthority("administrator"));
 			// 鎴愬姛鍒欐竻闄ょ櫥褰曢敊璇鏁�
 			delFailCount(tenantId, username);
-			return new BladeUserDetails(user.getId(),
-				user.getTenantId(), StringPool.EMPTY, user.getName(), user.getRealName(), user.getDeptId(), user.getPostId(), user.getRoleId(), Func.join(userInfo.getRoles()), Func.toStr(user.getAvatar(), TokenUtil.DEFAULT_AVATAR),
-				username, AuthConstant.ENCRYPT + user.getPassword(), userInfo.getDetail(), true, true, true, true,
-				AuthorityUtils.commaSeparatedStringToAuthorityList(Func.join(result.getData().getRoles())));
-		} else {
-			throw new UsernameNotFoundException(result.getMsg());
+			Kv kv = Kv.create();
+			kv.set("type","web");
+			return new BladeUserDetails(
+				new Long(this.id),this.tenantId, StringPool.EMPTY, "瓒呯骇绠$悊鍛�", "瓒呯骇绠$悊鍛�",this.id, this.id,"1123598816738675201",
+				"administrator","https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png" ,this.userName,AuthConstant.ENCRYPT + this.password,  kv,
+				true, true, true, true,authorities
+			);
+		}else {
+			R<Tenant> tenant = sysClient.getTenant(tenantId);
+
+			if (tenant.isSuccess()) {
+				if (TokenUtil.judgeTenant(tenant.getData())) {
+					throw new UserDeniedAuthorizationException(TokenUtil.USER_HAS_NO_TENANT_PERMISSION);
+				}
+			} else {
+				throw new UserDeniedAuthorizationException(TokenUtil.USER_HAS_NO_TENANT);
+			}
+
+			// 鑾峰彇鐢ㄦ埛绫诲瀷
+			String userType = Func.toStr(request.getHeader(TokenUtil.USER_TYPE_HEADER_KEY), TokenUtil.DEFAULT_USER_TYPE);
+
+			// 杩滅▼璋冪敤杩斿洖鏁版嵁
+			R<UserInfo> result;
+			// 鏍规嵁涓嶅悓鐢ㄦ埛绫诲瀷璋冪敤瀵瑰簲鐨勬帴鍙h繑鍥炴暟鎹紝鐢ㄦ埛鍙嚜琛屾嫇灞�
+			if (userType.equals(UserEnum.WEB.getName())) {
+				result = userClient.userInfo(tenantId, username, UserEnum.WEB.getName());
+			} else if (userType.equals(UserEnum.APP.getName())) {
+				result = userClient.userInfo(tenantId, username, UserEnum.APP.getName());
+			} else {
+				result = userClient.userInfo(tenantId, username, UserEnum.OTHER.getName());
+			}
+
+			// 鍒ゆ柇杩斿洖淇℃伅
+			if (result.isSuccess()) {
+				UserInfo userInfo = result.getData();
+				User user = userInfo.getUser();
+				// 鐢ㄦ埛涓嶅瓨鍦�,浣嗘彁绀虹敤鎴峰悕涓庡瘑鐮侀敊璇苟閿佸畾璐﹀彿
+				if (user == null || user.getId() == null) {
+					setFailCount(tenantId, username, count,strategy.getLockingTime());
+					throw new UsernameNotFoundException(TokenUtil.USER_NOT_FOUND);
+				}
+				String hex = DigestUtil.hex(password);
+				// 鐢ㄦ埛瀛樺湪浣嗗瘑鐮侀敊璇�,瓒呰繃娆℃暟鍒欓攣瀹氳处鍙�
+				if (grantType != null && !grantType.equals(TokenUtil.REFRESH_TOKEN_KEY) && !user.getPassword().equals(hex)) {
+					setFailCount(tenantId, username, count,strategy.getLockingTime());
+					throw new UsernameNotFoundException(TokenUtil.USER_NOT_FOUND);
+				}
+				// 鐢ㄦ埛瑙掕壊涓嶅瓨鍦�
+				if (Func.isEmpty(userInfo.getRoles())) {
+					throw new UserDeniedAuthorizationException(TokenUtil.USER_HAS_NO_ROLE);
+				}
+				// 澶氶儴闂ㄦ儏鍐典笅鎸囧畾鍗曢儴闂�
+				if (Func.isNotEmpty(headerDept) && user.getDeptId().contains(headerDept)) {
+					user.setDeptId(headerDept);
+				}
+				// 澶氳鑹叉儏鍐典笅鎸囧畾鍗曡鑹�
+				if (Func.isNotEmpty(headerRole) && user.getRoleId().contains(headerRole)) {
+					R<List<String>> roleResult = sysClient.getRoleAliases(headerRole);
+					if (roleResult.isSuccess()) {
+						userInfo.setRoles(roleResult.getData());
+					}
+					user.setRoleId(headerRole);
+				}
+				// 鎴愬姛鍒欐竻闄ょ櫥褰曢敊璇鏁�
+				delFailCount(tenantId, username);
+				//濉厖鐢ㄦ埛淇℃伅鍒扮敤鎴蜂俊鎭墿灞曠被
+				BladeUserDetails bladeUserDetails = new BladeUserDetails(user.getId(),
+					user.getTenantId(), StringPool.EMPTY, user.getName(), user.getRealName(), user.getDeptId(), user.getPostId(), user.getRoleId(), Func.join(userInfo.getRoles()), Func.toStr(user.getAvatar(), TokenUtil.DEFAULT_AVATAR),
+					username, AuthConstant.ENCRYPT + user.getPassword(), userInfo.getDetail(), true, true, true, true,
+					AuthorityUtils.commaSeparatedStringToAuthorityList(Func.join(result.getData().getRoles())),user.getStrategyUpdateStatus());
+				return bladeUserDetails;
+			} else {
+				throw new UsernameNotFoundException(result.getMsg());
+			}
 		}
+	}
+
+	/**
+	 * 鑾峰彇瀹㈡埛绔痠p锛屽鎴风鍙兘缁忚繃浠g悊锛屼篃鍙兘娌$粡杩囦唬鐞�
+	 * 濡傚紑鍚櫄鎷熸満鐨勬儏鍐典篃鍙兘瀵艰嚧鑾峰彇鍒扮殑鏄櫄鎷熸満鐨刬p
+	 * @param request
+	 * @return
+	 */
+	public static String getIpAddress(HttpServletRequest request){
+		String ip = request.getHeader("x-forwarded-for");
+		if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
+			// 澶氭鍙嶅悜浠g悊鍚庝細鏈夊涓猧p鍊硷紝绗竴涓猧p鎵嶆槸鐪熷疄ip
+			ip = ip.split(",")[0];
+		}
+		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+			ip = request.getHeader("Proxy-Client-IP");
+			System.out.println("Proxy-Client-IP"+ip);
+		}
+		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+			ip = request.getHeader("WL-Proxy-Client-IP");
+			System.out.println("WL-Proxy-Client-IP"+ip);
+		}
+		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+			ip = request.getHeader("HTTP_CLIENT_IP");
+			System.out.println("HTTP_CLIENT_IP"+ip);
+		}
+		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
+			System.out.println("HTTP_X_FORWARDED_FOR"+ip);
+		}
+		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+			ip = request.getHeader("X-Real-IP");
+			System.out.println("X-Real-IP"+ip);
+		}
+		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+			ip = request.getRemoteAddr();
+			System.out.println("getRemoteAddr"+ip);
+		}
+		//濡傛灉娌″彇鍒癷p锛岃繑鍥�""
+		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+			ip = "";
+		}
+		return ip;
 	}
 
 	/**
@@ -176,8 +287,8 @@
 	 * @param username 璐﹀彿
 	 * @param count    娆℃暟
 	 */
-	private void setFailCount(String tenantId, String username, int count) {
-		bladeRedis.setEx(CacheNames.tenantKey(tenantId, CacheNames.USER_FAIL_KEY, username), count + 1, Duration.ofMinutes(30));
+	private void setFailCount(String tenantId, String username, int count, Long expir) {
+		bladeRedis.setEx(CacheNames.tenantKey(tenantId, CacheNames.USER_FAIL_KEY, username), count + 1, Duration.ofMinutes(expir));
 	}
 
 	/**
@@ -207,6 +318,5 @@
 		}
 		return true;
 	}
-
 
 }

--
Gitblit v1.9.3