From 8a3ecabdc0afc79a131ba25b4a7cfb42cd878e72 Mon Sep 17 00:00:00 2001 From: lxp <2770281812@qq.com> Date: Mon, 19 Oct 2026 13:53:53 +0800 Subject: [PATCH] =?UTF-8?q?=E7=94=A8=E6=88=B7=E7=BC=96=E7=A0=81=E7=94=9F?= =?UTF-8?q?=E6=88=90=E7=BC=A9=E7=9F=AD=E4=B8=BA12=E5=AD=97=E7=AC=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../linkerbot/community/api/WorkflowTest.java | 21 +++- .../linkerbot/community/common/UserCodes.java | 19 ++++ .../service/impl/UserServiceImpl.java | 38 +++++-- .../service/impl/UserServiceImplTest.java | 100 ++++++++++++++++++ docs/community-api.md | 9 +- docs/database.md | 2 +- 6 files changed, 171 insertions(+), 18 deletions(-) create mode 100644 community-common/src/main/java/com/linkerbot/community/common/UserCodes.java create mode 100644 community-service/src/test/java/com/linkerbot/community/service/impl/UserServiceImplTest.java diff --git a/community-api/src/test/java/com/linkerbot/community/api/WorkflowTest.java b/community-api/src/test/java/com/linkerbot/community/api/WorkflowTest.java index d3aa595..5f41bd1 100644 --- a/community-api/src/test/java/com/linkerbot/community/api/WorkflowTest.java +++ b/community-api/src/test/java/com/linkerbot/community/api/WorkflowTest.java @@ -282,7 +282,7 @@ class WorkflowTest { perform(auth(put("/api/community/projects/" + legacy + "/like"), owner), 200); JsonNode comment = perform(body(auth(post("/api/community/projects/" + legacy + "/comments"), owner), Map.of("content", "兼容测试")), 200).path("data"); assertThat(comment.path("commentCode").asText()).hasSize(32); - assertThat(copy.path("owner").path("userCode").asText()).hasSize(32); + assertThat(copy.path("owner").path("userCode").asText()).hasSize(12); } @Test @@ -589,7 +589,8 @@ class WorkflowTest { JsonNode first = loginData("OWNER@example.com"); JsonNode second = loginData("owner@example.com"); assertThat(first.path("user").path("userCode").asText()) - .isEqualTo(second.path("user").path("userCode").asText()); + .isEqualTo(second.path("user").path("userCode").asText()) + .matches("[0-9abcdefghjkmnpqrstvwxyz]{12}"); assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_user", Long.class)).isEqualTo(1L); JsonNode challenge = perform(get("/api/auth/captcha"), 200).path("data"); assertThat(challenge.path("image").asText()).startsWith("data:image/png;base64,"); @@ -621,6 +622,22 @@ class WorkflowTest { perform(get("/api/workspace/projects"), 401); } + @Test + void loginPreservesLegacyUserCodes() throws Exception { + String legacyCode = "1234567890abcdef1234567890abcdef"; + jdbc.update( + "INSERT INTO sys_user (user_code, email, nickname, status, created_at, updated_at)" + + " VALUES (?, ?, ?, 'ACTIVE', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)", + legacyCode, "legacy@example.com", "历史用户"); + JsonNode data = loginData("LEGACY@example.com"); + assertThat(data.path("user").path("userCode").asText()).isEqualTo(legacyCode); + JsonNode me = perform(auth(get("/api/users/me"), data.path("token").asText()), 200) + .path("data"); + assertThat(me.path("userCode").asText()).isEqualTo(legacyCode); + assertThat(me.has("id")).isFalse(); + assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_user", Long.class)).isEqualTo(1L); + } + @Test void openApiMatchesRoutesAndPublicAuthenticationAndOnlyFourTablesExist() throws Exception { JsonNode spec = perform(get("/v3/api-docs"), 200); diff --git a/community-common/src/main/java/com/linkerbot/community/common/UserCodes.java b/community-common/src/main/java/com/linkerbot/community/common/UserCodes.java new file mode 100644 index 0000000..93e3e69 --- /dev/null +++ b/community-common/src/main/java/com/linkerbot/community/common/UserCodes.java @@ -0,0 +1,19 @@ +package com.linkerbot.community.common; + +import java.security.SecureRandom; + +/** 仅用于新用户编码;历史 32 位编码继续有效。 */ +public final class UserCodes { + private static final String ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz"; + private static final SecureRandom RANDOM = new SecureRandom(); + + private UserCodes() {} + + public static String next() { + StringBuilder code = new StringBuilder(12); + for (int index = 0; index < 12; index++) { + code.append(ALPHABET.charAt(RANDOM.nextInt(ALPHABET.length()))); + } + return code.toString(); + } +} diff --git a/community-service/src/main/java/com/linkerbot/community/service/impl/UserServiceImpl.java b/community-service/src/main/java/com/linkerbot/community/service/impl/UserServiceImpl.java index 4cdfa77..79cefae 100644 --- a/community-service/src/main/java/com/linkerbot/community/service/impl/UserServiceImpl.java +++ b/community-service/src/main/java/com/linkerbot/community/service/impl/UserServiceImpl.java @@ -22,34 +22,50 @@ import java.util.Locale; @RequiredArgsConstructor public class UserServiceImpl implements UserService { private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class); + private static final int MAX_CODE_ATTEMPTS = 5; private final UserMapper users; @Override public User login(String email) { String normalized = email.trim().toLowerCase(Locale.ROOT); User user = users.selectOne(new LambdaQueryWrapper().eq(User::getEmail, normalized)); - if (user == null) { + if (user == null) user = create(normalized); + if (!"ACTIVE".equals(user.getStatus())) + throw new BusinessException(403, "ACCOUNT_DISABLED", "账号不可用"); + log.info("用户登录 userCode={}", user.getUserCode()); + return user; + } + + private User create(String normalizedEmail) { + for (int attempt = 1; attempt <= MAX_CODE_ATTEMPTS; attempt++) { User candidate = new User(); - candidate.setUserCode(Codes.next()); - candidate.setEmail(normalized); + candidate.setUserCode(UserCodes.next()); + candidate.setEmail(normalizedEmail); candidate.setNickname("用户_" + candidate.getUserCode().substring(0, 8)); candidate.setStatus("ACTIVE"); candidate.setCreatedAt(LocalDateTime.now(Clock.systemUTC())); candidate.setUpdatedAt(candidate.getCreatedAt()); try { users.insert(candidate); - user = candidate; - log.info("创建用户 userCode={}", user.getUserCode()); + log.info("创建用户 userCode={}", candidate.getUserCode()); + return candidate; } catch (DuplicateKeyException duplicate) { - user = + // 同一邮箱并发首次登录时,复用另一个请求已创建的用户。 + User existing = users.selectOne( - new LambdaQueryWrapper().eq(User::getEmail, normalized)); + new LambdaQueryWrapper().eq(User::getEmail, normalizedEmail)); + if (existing != null) return existing; + User conflict = + users.selectOne( + new LambdaQueryWrapper() + .eq(User::getUserCode, candidate.getUserCode())); + if (conflict == null) throw duplicate; + log.warn("用户编码冲突 userCode={} attempt={}", candidate.getUserCode(), attempt); + if (attempt == MAX_CODE_ATTEMPTS) + throw new BusinessException(503, "USER_CODE_EXHAUSTED", "用户编码分配失败,请稍后重试"); } } - if (user == null || !"ACTIVE".equals(user.getStatus())) - throw new BusinessException(403, "ACCOUNT_DISABLED", "账号不可用"); - log.info("用户登录 userCode={}", user.getUserCode()); - return user; + throw new IllegalStateException("用户编码分配未完成"); } @Override diff --git a/community-service/src/test/java/com/linkerbot/community/service/impl/UserServiceImplTest.java b/community-service/src/test/java/com/linkerbot/community/service/impl/UserServiceImplTest.java new file mode 100644 index 0000000..2cdd5a9 --- /dev/null +++ b/community-service/src/test/java/com/linkerbot/community/service/impl/UserServiceImplTest.java @@ -0,0 +1,100 @@ +package com.linkerbot.community.service.impl; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import com.linkerbot.community.bean.entity.User; +import com.linkerbot.community.common.BusinessException; +import com.linkerbot.community.service.mapper.UserMapper; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; +import org.springframework.dao.DuplicateKeyException; + +import java.util.List; + +class UserServiceImplTest { + private final UserMapper users = mock(UserMapper.class); + private final UserServiceImpl service = new UserServiceImpl(users); + + @Test + void codeCollisionRetriesWithAnotherCodeInsteadOfLoggingInAsItsOwner() { + User conflict = existingUser("ACTIVE"); + when(users.selectOne(any())).thenReturn(null, null, conflict); + when(users.insert(any(User.class))) + .thenThrow(new DuplicateKeyException("uk_user_code")) + .thenReturn(1); + + User created = service.login(" NEW@example.com "); + + ArgumentCaptor candidates = ArgumentCaptor.forClass(User.class); + verify(users, times(2)).insert(candidates.capture()); + List attempts = candidates.getAllValues(); + assertThat(created).isSameAs(attempts.get(1)).isNotSameAs(conflict); + assertThat(created.getUserCode()) + .matches("[0-9abcdefghjkmnpqrstvwxyz]{12}") + .isNotEqualTo(attempts.get(0).getUserCode()); + assertThat(created.getEmail()).isEqualTo("new@example.com"); + assertThat(created.getNickname()).isEqualTo("用户_" + created.getUserCode().substring(0, 8)); + assertThat(created.getStatus()).isEqualTo("ACTIVE"); + } + + @ParameterizedTest + @ValueSource(strings = {"ACTIVE", "DISABLED"}) + void concurrentRegistrationReusesExistingAccountAndRespectsItsStatus(String status) { + User existing = existingUser(status); + when(users.selectOne(any())).thenReturn(null, existing); + when(users.insert(any(User.class))) + .thenThrow(new DuplicateKeyException("uk_user_email")); + + if ("ACTIVE".equals(status)) { + assertThat(service.login("existing@example.com")).isSameAs(existing); + } else { + assertThatThrownBy(() -> service.login("existing@example.com")) + .isInstanceOfSatisfying(BusinessException.class, error -> { + assertThat(error.status()).isEqualTo(403); + assertThat(error.code()).isEqualTo("ACCOUNT_DISABLED"); + }); + } + verify(users).insert(any(User.class)); + assertThat(existing.getUserCode()).isEqualTo("1234567890abcdef1234567890abcdef"); + } + + @Test + void persistentCodeCollisionsStopAfterFiveAttempts() { + User conflict = existingUser("ACTIVE"); + when(users.selectOne(any())) + .thenReturn(null, null, conflict, null, conflict, null, conflict, null, conflict, null, conflict); + when(users.insert(any(User.class))) + .thenThrow(new DuplicateKeyException("uk_user_code")); + + assertThatThrownBy(() -> service.login("new@example.com")) + .isInstanceOfSatisfying(BusinessException.class, error -> { + assertThat(error.status()).isEqualTo(503); + assertThat(error.code()).isEqualTo("USER_CODE_EXHAUSTED"); + }); + verify(users, times(5)).insert(any(User.class)); + } + + @Test + void unrelatedDuplicateKeyFailuresAreNotReportedAsDisabledAccounts() { + DuplicateKeyException failure = new DuplicateKeyException("unexpected unique constraint"); + when(users.insert(any(User.class))).thenThrow(failure); + + assertThatThrownBy(() -> service.login("new@example.com")).isSameAs(failure); + verify(users).insert(any(User.class)); + } + + private User existingUser(String status) { + User user = new User(); + user.setId(1L); + user.setUserCode("1234567890abcdef1234567890abcdef"); + user.setEmail("existing@example.com"); + user.setNickname("历史用户"); + user.setStatus(status); + return user; + } +} diff --git a/docs/community-api.md b/docs/community-api.md index da5f019..54699ad 100644 --- a/docs/community-api.md +++ b/docs/community-api.md @@ -99,7 +99,7 @@ Git SHA 使用完整的 40 或 64 位十六进制字符串,不使用缩写。 | publishedCommitSha | 项目详情 | 社区当前发布版本;Fork 时原样提交此值 | | blobSha | 文件或目录条目 | 文件或目录对应的 Git 对象标识,前端不用它提交文件 | -新建、Fork 和 GitHub 初始化导入的 `projectCode` 为 12 位小写字母和数字,例如 `7m4k9x2p8q6r`。已有 32 位项目编码及链接继续有效。前端将编码作为不透明字符串传递,不截取、不补齐,也不固定要求 32 位;`sourceProjectCode`、AI 的 `previousProjectCodes` 及结果编码同样兼容两种长度,最大长度仍为 32。用户编码、评论编码及 Commit SHA 的规则不变。 +新建、Fork 和 GitHub 初始化导入的 `projectCode` 为 12 位小写字母和数字,例如 `7m4k9x2p8q6r`。已有 32 位项目编码及链接继续有效。前端将编码作为不透明字符串传递,不截取、不补齐,也不固定要求 32 位;`sourceProjectCode`、AI 的 `previousProjectCodes` 及结果编码同样兼容两种长度,最大长度仍为 32。新注册用户的 `userCode` 同样为 12 位小写字母和数字,历史用户保留原有 32 位编码;登录、用户信息、项目归属、评论作者及封面上传路径均使用真实编码,不假定固定长度。评论编码及 Commit SHA 的规则不变。 项目详情不包含工作区当前 main 的 SHA。进入编辑器、提交或发布前,从工作区目录或文件接口获取 `commitSha`。 @@ -298,7 +298,7 @@ export interface Comment { "urdfBaseUrl": null, "projectType": "GENERAL", "owner": { - "userCode": "11111111111111111111111111111111", + "userCode": "111111111111", "nickname": "用户_11111111" }, "repoStatus": "READY", @@ -379,7 +379,7 @@ data 示例中 image 仅展示格式前缀,实际值为完整图片: "tokenType": "Bearer", "expiresIn": 86400, "user": { - "userCode": "11111111111111111111111111111111", + "userCode": "111111111111", "nickname": "用户_11111111", "email": "user@example.com" } @@ -962,7 +962,7 @@ data 为 PageResult<Comment>,按创建时间倒序,平铺展示,不 { "commentCode": "33333333333333333333333333333333", "author": { - "userCode": "11111111111111111111111111111111", + "userCode": "111111111111", "nickname": "用户_11111111" }, "content": "这个项目的结构很清楚", @@ -1260,6 +1260,7 @@ if (result.status !== 'CHAT') { | 502 | GITEA_ERROR | 仓库服务异常;写请求先核对结果,避免自动重试 | | 502 | GITEA_INVALID_RESPONSE | 仓库响应无法确认;写请求先核对结果,避免自动重试 | | 503 | GITEA_NOT_CONFIGURED | 后端缺少仓库配置,请后端处理 | +| 503 | USER_CODE_EXHAUSTED | 用户编码分配连续冲突,重新获取验证码后稍后登录,并保留 requestId | | 504 | REMOTE_RESULT_UNKNOWN | 仓库连接异常或超时;读请求可重新读取,写请求需先核对结果 | 通过 HTTP 状态和 code 判断行为,保留 requestId 供排查。通用请求封装不要自动重试创建项目、Fork、评论或文件写入。浏览器超时、取消请求、连接中断不保证后端没有执行成功。 diff --git a/docs/database.md b/docs/database.md index 939d27d..a57e45d 100644 --- a/docs/database.md +++ b/docs/database.md @@ -83,7 +83,7 @@ CREATE TABLE project_like ( 内部 ID 仅用于数据库关联,对外使用业务编码。时间均由后端写入 UTC。`CREATING` 项目表示仓库初始化未完成,不代表编辑草稿。Gitea 数据库与业务库分离,不修改 Gitea 内部表。 -新增项目使用 12 位项目编码,历史 32 位编码继续保留。现有 `project_code CHAR(32)` 可容纳两者,不需要修改表结构或历史记录;仓库名称仍为 `p_{projectCode}`。用户编码和评论编码保持 32 位。GitHub 运维导入的来源和进度保存于批次状态目录,GitHub 来源不占用社区内部 Fork 来源字段。 +新增项目和用户使用 12 位小写字母和数字编码,历史 32 位编码继续保留。现有 `project_code CHAR(32)` 和 `user_code CHAR(32)` 可容纳两者,不需要修改表结构或历史记录;仓库名称仍为 `p_{projectCode}`。用户编码由安全随机数生成,唯一索引兜底,冲突时最多尝试 5 次;同一邮箱并发注册复用已有用户。评论编码保持 32 位。GitHub 运维导入的来源和进度保存于批次状态目录,GitHub 来源不占用社区内部 Fork 来源字段。 ## 已有数据库增加项目封面