Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FIX]解决etherpad登录失败问题 #8

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

<properties>
<java.version>17</java.version>
<netty.version>4.1.108.Final</netty.version>
<spring-framework.version>6.1.14</spring-framework.version>
</properties>

Expand Down Expand Up @@ -115,11 +114,6 @@
<artifactId>unirest-java</artifactId>
<version>3.13.8</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.108.Final</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
Expand Down
95 changes: 93 additions & 2 deletions src/main/java/com/om/dao/AuthingManagerDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
import cn.authing.core.types.AuthorizedTargetsParam;
import cn.authing.core.types.CommonMessage;
import cn.authing.core.types.FindUserParam;
import cn.authing.core.types.IAction;
import cn.authing.core.types.IResourceDto;
import cn.authing.core.types.IResourceResponse;
import cn.authing.core.types.Identity;
import cn.authing.core.types.Operator;
import cn.authing.core.types.PaginatedAuthorizedResources;
Expand All @@ -31,6 +34,7 @@
import com.om.controller.bean.request.NamespaceInfoPage;
import com.om.dao.bean.AuthorizeInfo;
import com.om.dao.bean.UserInfo;
import com.om.utils.CommonUtil;
import jakarta.annotation.PostConstruct;

import com.alibaba.fastjson2.JSON;
Expand Down Expand Up @@ -107,6 +111,11 @@ public class AuthingManagerDao {
*/
private static final String LIST_COMMON_RESOURCE = "/list-common-resource";

/**
* 创建账号.
*/
private static final String CREATE_USER = "/create-user";

/**
* 允许的社区列表.
*/
Expand Down Expand Up @@ -621,7 +630,11 @@ public List<UserOfResourceInfo> listUserOfResource(String nameSpaceCode, String
}
List<String> userIds = sourceList.stream()
.map(ResourcePermissionAssignment::getTargetIdentifier).collect(Collectors.toList());
List<User> users = managementClient.users().batch(userIds).execute();
List<List<String>> splitUserIds = CommonUtil.splitList(userIds, 80);
List<User> users = new ArrayList<>();
for (List<String> userIdList : splitUserIds) {
users.addAll(managementClient.users().batch(userIdList).execute());
}
HashMap<String, List<IdentityInfo>> identityBeanMap = new HashMap<>();
HashMap<String, User> userMap = new HashMap<>();
for (User user : users) {
Expand Down Expand Up @@ -890,6 +903,46 @@ public String updateAccountInfo(String token, String account, String type) {
return "true";
}

/**
* 创建资源.
*
* @param namespace 命名空间
* @param resource 资源
* @param actions 操作
* @return 创建结果
*/
public boolean createResource(String namespace, String resource, List<String> actions) {
try {
String resourceName = convertResource(resource);
IResourceResponse execute = managementClient.acl().findResourceByCode(resourceName, namespace).execute();
if (execute != null && StringUtils.isNotBlank(execute.getCode())) {
return true;
}
ArrayList<IAction> list = new ArrayList<>();
for (String action : actions) {
list.add(new IAction(action, null));
}
IResourceDto iResourceDto = new IResourceDto(
resourceName,
ResourceType.DATA,
null,
list,
namespace
);
IResourceResponse res = managementClient.acl().createResource(iResourceDto).execute();
if (res != null && StringUtils.equals(res.getCode(), resourceName)) {
LOGGER.info("create resource({}:{}) success", namespace, resource);
return true;
} else {
LOGGER.info("create resource({}:{}) failed", namespace, resource);
return false;
}
} catch (Exception e) {
LOGGER.error("create resource {} failed {}", resource, e.getMessage());
return false;
}
}

/**
* 授权.
*
Expand Down Expand Up @@ -973,7 +1026,7 @@ public boolean revokeResource(String namespaceCode, String resource, List<String
}

/**
* 根据ID批量获取用户.
* 根据ID批量获取用户(最多一次只能查询50个用户).
*
* @param type 用户类型
* @param extIdpId 三方平台ID
Expand Down Expand Up @@ -1033,6 +1086,44 @@ public List<UserInfo> getUsersByIds(String type, String extIdpId, List<String> u
}
}

/**
* 创建用户.
*
* @param usersObj 用户消息体
* @return 创建用户结果
*/
public UserInfo createUser(JSONObject usersObj) {
try {
String mToken = (String) redisDao.get(Constant.REDIS_KEY_AUTH_MANAGER_TOKEN);
if (StringUtils.isBlank(mToken) || "null".equals(mToken)) {
mToken = getManagementToken();
}
System.out.println(usersObj.toString());
HttpResponse<JsonNode> response = Unirest.post(authingApiHostV3 + CREATE_USER)
.header("Content-Type", "application/json")
.header("x-authing-userpool-id", userPoolId)
.header("authorization", mToken)
.body(usersObj.toString())
.asJson();
JSONObject resObj = response.getBody().getObject();
if (resObj.getInt("statusCode") != 200) {
LOGGER.error("create users failed {}", resObj.getString("message"));
return null;
}
JSONObject data = resObj.getJSONObject("data");
if (data == null) {
return null;
}
UserInfo userInfo = new UserInfo();
userInfo.setUserId(data.getString("userId"));
userInfo.setUsername(data.getString("username"));
return userInfo;
} catch (Exception e) {
LOGGER.error("delete resource failed {}", e.getMessage());
return null;
}
}

/**
* 转换resource(部分resource在authing无法使用,需要转化使用).
*
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/om/service/AuthingService.java
Original file line number Diff line number Diff line change
Expand Up @@ -1598,11 +1598,11 @@ public ResponseEntity message(String res) {
if (!res.contains(":")) {
return result(HttpStatus.BAD_REQUEST, null, res, null);
}
ObjectMapper objectMapper = new ObjectMapper();
ObjectMapper jsonReader = new ObjectMapper();
String message = "faild";
try {
res = res.substring(Constant.AUTHING_RES_PREFIX_LENGTH);
Iterator<JsonNode> buckets = objectMapper.readTree(res).iterator();
Iterator<JsonNode> buckets = jsonReader.readTree(res).iterator();
if (buckets.hasNext()) {
message = buckets.next().get("message").get("message").asText();
}
Expand Down
21 changes: 20 additions & 1 deletion src/main/java/com/om/service/OidcService.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import cn.authing.core.types.Application;
import com.alibaba.fastjson2.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
Expand Down Expand Up @@ -55,7 +56,9 @@
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
Expand Down Expand Up @@ -737,7 +740,7 @@ private ResponseEntity getOidcTokenByCode(String appId, String appSecret, String
}
String idToken = jsonNode.get("idToken").asText();
if (scopes.contains("id_token")) {
tokens.put("id_token", idToken);
tokens.put("id_token", createOidcIdToken(appId, appSecret, userId));
}
redisDao.remove(code);
addOidcLogoutUrl(userId, idToken, redirectUri, logoutUrl);
Expand All @@ -750,6 +753,22 @@ private ResponseEntity getOidcTokenByCode(String appId, String appSecret, String
}
}

private String createOidcIdToken(String appId, String appSecret, String userId) throws NoSuchAlgorithmException {
LocalDateTime nowDate = LocalDateTime.now();
Date issuedAt = Date.from(nowDate.atZone(ZoneId.systemDefault()).toInstant());
LocalDateTime expireDate = nowDate.plusSeconds(72000);
Date expireAt = Date.from(expireDate.atZone(ZoneId.systemDefault()).toInstant());
String token = JWT.create()
.withAudience(appId) //谁接受签名
.withIssuedAt(issuedAt) //生成签名的时间
.withExpiresAt(expireAt) //过期时间
.withJWTId(codeUtil.randomStrBuilder(Constant.RANDOM_DEFAULT_LENGTH))
.withClaim("sub", userId)
.withClaim("iss", env.getProperty("oidc.login.page"))
.sign(Algorithm.HMAC256(appSecret));
return token;
}

/**
* oidc扩展协议,增加退出接入应用的机制.
*
Expand Down
100 changes: 0 additions & 100 deletions src/main/java/com/om/service/OneIdManageService.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,7 @@

import cn.authing.core.auth.AuthenticationClient;
import cn.authing.core.types.Application;
import cn.authing.core.types.ResourcePermissionAssignment;
import cn.authing.core.types.User;
import com.om.controller.bean.request.BatchAuthInfo;
import com.om.controller.bean.request.IdentityUser;
import com.om.dao.bean.AuthorizeInfo;
import com.om.dao.bean.UserInfo;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

Expand Down Expand Up @@ -55,7 +49,6 @@
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.util.HtmlUtils;

Expand All @@ -65,7 +58,6 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OneIdManageService {
Expand Down Expand Up @@ -154,11 +146,6 @@ public class OneIdManageService {
@Value("${enterprise.extIdpId.gitcode: }")
private String enterExtIdpIdGitcode;

/**
* 能用于三方用户查询authing用户的三方平台.
*/
private HashMap<String, String> extIdpIdMap;

/**
* 静态日志记录器,用于记录 OneIdManageService 类的日志信息.
*/
Expand All @@ -174,15 +161,6 @@ public class OneIdManageService {
*/
private static final String TOKEN_REGEX = "token_info:";

/**
* 初始化方法.
*/
@PostConstruct
public void init() {
extIdpIdMap = new HashMap<>();
extIdpIdMap.put("gitcode", enterExtIdpIdGitcode);
}

/**
* 处理令牌申请请求.
*
Expand Down Expand Up @@ -571,84 +549,6 @@ public ResponseEntity revokePrivacy(String userId) {
}
}

/**
* 批量根据三方用户ID获取活用户.
*
* @param identityUser 三方用户信息
* @return authing用户
*/
public ResponseEntity getUserByIdentities(IdentityUser identityUser) {
if (!extIdpIdMap.containsValue(identityUser.getThirdPlatform())) {
return authingService.result(HttpStatus.BAD_REQUEST, MessageCodeConfig.E00012, null, null);
}
String extIdpId = extIdpIdMap.get(identityUser.getThirdPlatform());
List<UserInfo> userInfos = authingManagerDao.getUsersByIds("identity",
extIdpId, identityUser.getUserIds());
if (userInfos == null) {
return authingService.result(HttpStatus.BAD_REQUEST, MessageCodeConfig.E00012, null, null);
}
return authingService.result(HttpStatus.OK, MessageCodeConfig.S0001, null, userInfos);
}

/**
* 批量授权.
*
* @param batchAuthInfo 权限信息
* @return 授权结果
*/
public ResponseEntity batchAuthrize(BatchAuthInfo batchAuthInfo) {
try {
List<ResourcePermissionAssignment> authorizedUsers = authingManagerDao.getAuthorizedUser(
batchAuthInfo.getNamespaceCode(),
batchAuthInfo.getResource(), batchAuthInfo.getActions());
List<String> authUserIds = authorizedUsers.stream()
.map(ResourcePermissionAssignment::getTargetIdentifier).collect(Collectors.toList());
if (batchAuthInfo.getIsDeleteOthers()) {
List<String> deleteUserIds = new ArrayList<>();
for (String userId : authUserIds) {
if (!batchAuthInfo.getUserIds().contains(userId)) {
deleteUserIds.add(userId);
}
}
authingManagerDao.revokeResource(batchAuthInfo.getNamespaceCode(), batchAuthInfo.getResource(),
deleteUserIds);
}
List<String> addUserIds = new ArrayList<>();
for (String userId : batchAuthInfo.getUserIds()) {
if (!authUserIds.contains(userId)) {
addUserIds.add(userId);
}
}
if (!CollectionUtils.isEmpty(addUserIds)) {
String authActionPre = batchAuthInfo.getResource() + ":";
List<String> authActions = batchAuthInfo.getActions().stream().map(x -> authActionPre + x)
.collect(Collectors.toList());
AuthorizeInfo authorizeInfo = new AuthorizeInfo();
authorizeInfo.setNamespace(batchAuthInfo.getNamespaceCode());
AuthorizeInfo.AuthorizeData authorizeData = authorizeInfo.new AuthorizeData();
authorizeData.setTargetType("USER");
authorizeData.setTargetIdentifiers(addUserIds);
AuthorizeInfo.AuthorizeResource authorizeResource = authorizeInfo.new AuthorizeResource();
authorizeResource.setResourceType("DATA");
authorizeResource.setCode(batchAuthInfo.getResource());
authorizeResource.setActions(authActions);
List<AuthorizeInfo.AuthorizeResource> resources = new ArrayList<>();
resources.add(authorizeResource);
authorizeData.setResources(resources);
List<AuthorizeInfo.AuthorizeData> list = new ArrayList<>();
list.add(authorizeData);
authorizeInfo.setList(list);
if (!authingManagerDao.authrizeResource(authorizeInfo)) {
return authingService.result(HttpStatus.BAD_REQUEST, MessageCodeConfig.E00012, null, null);
}
}
return authingService.result(HttpStatus.OK, MessageCodeConfig.S0001, null, null);
} catch (Exception e) {
LOGGER.error(e.getMessage());
return authingService.result(HttpStatus.BAD_REQUEST, MessageCodeConfig.E00012, null, null);
}
}

/**
* APP是否存在,且密码是否正确.
*
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/om/service/PrivacyHistoryService.java
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public class PrivacyHistoryService {
/**
* 允许的社区列表.
*/
private List<String> allowedCommunity = Arrays.asList("openeuler", "mindspore", "modelfoundry");;
private List<String> allowedCommunity = Arrays.asList("openeuler", "mindspore", "modelfoundry", "openubmc");

/**
* 用户池id.
Expand Down
Loading
Loading