From 01aa13935ab4e8356d213cb2b003828ffc097d25 Mon Sep 17 00:00:00 2001 From: lxp <2770281812@qq.com> Date: Thu, 22 Oct 2026 16:48:37 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AE=A1=E7=90=86=E5=91=98=E8=A7=92=E8=89=B2?= =?UTF-8?q?=E4=B9=9F=E5=85=81=E8=AE=B8=E7=99=BB=E5=BD=95=E5=89=8D=E5=8F=B0?= =?UTF-8?q?=E7=94=A8=E6=88=B7=E7=AB=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- docs/admin-api.md | 2 + docs/vibemake-api.md | 4 +- .../vibemake/adminapi/AdminWorkflowTest.java | 4 +- .../api/controller/AuthController.java | 2 +- .../linkerbot/vibemake/api/WorkflowTest.java | 80 ++++++++++++++----- .../vibemake/security/BearerTokenFilter.java | 3 +- .../vibemake/security/SessionTest.java | 42 ++++++++++ .../service/impl/UserServiceImpl.java | 5 +- .../service/impl/UserServiceImplTest.java | 39 +++++++++ 10 files changed, 156 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 14feed4..9c6b824 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ UserService、ProjectService、FileService、InteractionService、CoverUploadSer 支持邮箱加图片验证码登录、我的项目列表、在线文本编辑、新建文件和目录、上传及多文件提交、手动发布和撤回、已发布版本浏览、快照 Fork、平铺评论和点赞,以及可配置开启的 Maker AI(聊天问答、查找、创建空项目、Fork)。工作区是用户项目列表,没有 workspace 表。没有 repository_operation 表、草稿保存、类型表、标签、收藏、成员协作;管理后台接口由 vibemake-adminapi 提供。 -**普通用户登录不验证邮箱归属,知道别人的邮箱也可能登录其账号;ADMIN 和 OFFICIAL 禁止通过该入口登录,后台管理员必须验证密码。** 验证码、登录会话和请求频率使用 Redis;两个应用仍各单实例部署,应用重启后保留 Redis 中未过期的会话。首次从本机缓存版本升级需要重新登录。所有仓库写入统一经过平台后端。 +**社区登录不验证邮箱归属,知道别人的邮箱并通过图片验证码即可登录其社区身份;USER 和 ADMIN 均使用邮箱加图片验证码登录前台,无需密码;后台仅允许 ADMIN 通过邮箱和密码登录;OFFICIAL 禁止登录。** 验证码、登录会话和请求频率使用 Redis;两个应用仍各单实例部署,应用重启后保留 Redis 中未过期的会话。首次从本机缓存版本升级需要重新登录。所有仓库写入统一经过平台后端。 ## 启动 diff --git a/docs/admin-api.md b/docs/admin-api.md index 63572eb..bca977d 100644 --- a/docs/admin-api.md +++ b/docs/admin-api.md @@ -248,6 +248,8 @@ async function login(email: string, password: string): Promise { 后台只允许正常的 `ADMIN` 登录。普通用户、官方账号、禁用账号、密码错误均不能登录,不根据失败文案判断账号是否存在。连续失败会触发 429,提示 15 分钟后重试。 +同一 `ADMIN` 账号也可通过社区 `/api/auth/login` 登录前台,只提交邮箱和图片验证码,无需密码;后台登录仍须提交邮箱和密码。社区与后台独立保存 Token,不能混用;在社区工作区仍只能操作自己的项目。修改后台密码或禁用账号会使该账号两端旧会话失效。前台请求字段见[邮箱登录](vibemake-api.md#邮箱登录)。 + 会话默认 8 小时,以 `expiresIn` 为准;服务重启后需要重新登录。无刷新 Token 接口。不要把 Token、密码写入控制台、埋点或错误上报。 ### 3.3 当前用户、退出、修改密码 diff --git a/docs/vibemake-api.md b/docs/vibemake-api.md index 8927896..e6d7cf4 100644 --- a/docs/vibemake-api.md +++ b/docs/vibemake-api.md @@ -393,7 +393,9 @@ data 示例中 image 仅展示格式前缀,实际值为完整图片: } ``` -首次登录自动创建用户,邮箱统一转成小写。当前只验证邮箱格式与图片验证码,不发送邮件、不使用密码,也不验证邮箱归属。Token 有效期默认 24 小时,以 expiresIn 为准,不是 JWT,没有刷新 Token 接口;会话存于 Redis,应用重启后保留未过期会话;首次从本机缓存版本升级需要重新登录。 +首次登录自动创建普通用户,邮箱统一转成小写。正常的 `USER` 和 `ADMIN` 都使用邮箱与图片验证码登录社区,请求只需 `email`、`captchaCode`、`captchaAnswer`,不需要密码。当前不发送邮件,也不验证邮箱归属;知道账号邮箱并通过图片验证码即可登录其社区身份。登录失败后重新获取图片验证码再提交。`OFFICIAL`、禁用账号和其他角色不能登录。 + +社区 Token 有效期默认 24 小时,以 expiresIn 为准,不是 JWT,没有刷新 Token 接口;会话存于 Redis,应用重启后保留未过期会话;首次从本机缓存版本升级需要重新登录。社区与后台独立保存登录状态,Token 不通用。管理员在社区工作区也只能操作自己的项目,后台仍使用邮箱和密码登录;修改后台密码或禁用账号会使该账号两端旧会话失效。现有登录请求频率限制同样适用于管理员社区登录。 ### 当前用户和退出登录 diff --git a/vibemake-adminapi/src/test/java/com/linkerbot/vibemake/adminapi/AdminWorkflowTest.java b/vibemake-adminapi/src/test/java/com/linkerbot/vibemake/adminapi/AdminWorkflowTest.java index 98cb99a..111c1ce 100644 --- a/vibemake-adminapi/src/test/java/com/linkerbot/vibemake/adminapi/AdminWorkflowTest.java +++ b/vibemake-adminapi/src/test/java/com/linkerbot/vibemake/adminapi/AdminWorkflowTest.java @@ -396,8 +396,8 @@ class AdminWorkflowTest { login(ordinary.getEmail(), PASSWORD, 401); String ordinaryToken = tokens.issue(ordinary.getId(), ordinary.getSessionVersion()); request(get("/admin-api/users").header("Authorization", "Bearer " + ordinaryToken), 403); - assertThatThrownBy(() -> userService.login(admin.getEmail())) - .isInstanceOf(BusinessException.class); + assertThat(userService.login(admin.getEmail()).getUserCode()) + .isEqualTo(admin.getUserCode()); JsonNode me = request(signed(get("/admin-api/auth/me")), 200).path("data"); assertThat(me.path("role").asText()).isEqualTo("ADMIN"); assertThat(me.has("id")).isFalse(); diff --git a/vibemake-api/src/main/java/com/linkerbot/vibemake/api/controller/AuthController.java b/vibemake-api/src/main/java/com/linkerbot/vibemake/api/controller/AuthController.java index 1f0c6dd..d052da9 100644 --- a/vibemake-api/src/main/java/com/linkerbot/vibemake/api/controller/AuthController.java +++ b/vibemake-api/src/main/java/com/linkerbot/vibemake/api/controller/AuthController.java @@ -38,7 +38,7 @@ public class AuthController { } @PostMapping("/api/auth/login") - @Operation(summary = "邮箱和图片验证码登录,首次自动创建用户") + @Operation(summary = "邮箱和图片验证码登录,支持普通用户和管理员,首次自动创建普通用户") @SecurityRequirements public ApiResponse login(@Valid @RequestBody LoginRequest input) { limits.request("login-account", input.email().trim().toLowerCase(Locale.ROOT)); diff --git a/vibemake-api/src/test/java/com/linkerbot/vibemake/api/WorkflowTest.java b/vibemake-api/src/test/java/com/linkerbot/vibemake/api/WorkflowTest.java index 012e854..eb6db69 100644 --- a/vibemake-api/src/test/java/com/linkerbot/vibemake/api/WorkflowTest.java +++ b/vibemake-api/src/test/java/com/linkerbot/vibemake/api/WorkflowTest.java @@ -118,20 +118,17 @@ class WorkflowTest { } private JsonNode loginData(String email) throws Exception { + return loginResponse(email, 200).path("data"); + } + + private JsonNode loginResponse(String email, int status) throws Exception { String captcha = perform(get("/api/auth/captcha"), 200).path("data").path("captchaCode").asText(); - return perform( - body( - post("/api/auth/login"), - Map.of( - "email", - email, - "captchaCode", - captcha, - "captchaAnswer", - "abcde")), - 200) - .path("data"); + Map input = new HashMap<>(); + input.put("email", email); + input.put("captchaCode", captcha); + input.put("captchaAnswer", "abcde"); + return perform(body(post("/api/auth/login"), input), status); } private String login(String email) throws Exception { @@ -1591,12 +1588,57 @@ class WorkflowTest { + " user_code=?", code); perform(auth(get("/api/users/me"), fresh), 401); - String captcha = - perform(get("/api/auth/captcha"), 200).path("data").path("captchaCode").asText(); - perform( - body( - post("/api/auth/login"), - Map.of("email", email, "captchaCode", captcha, "captchaAnswer", "ABCDE")), - 403); + String promoted = login(email); + perform(auth(get("/api/users/me"), promoted), 200); + } + + @Test + void adminCanUseItsOwnCommunityWorkspaceAfterCaptchaLogin() throws Exception { + String email = "community-admin@example.invalid"; + JsonNode previousLogin = loginData(email); + String userCode = previousLogin.path("user").path("userCode").asText(); + jdbc.update( + "UPDATE sys_user SET role='ADMIN'," + + " session_version=session_version+1 WHERE user_code=?", + userCode); + perform(auth(get("/api/users/me"), previousLogin.path("token").asText()), 401); + + JsonNode login = loginData(email); + String token = login.path("token").asText(); + assertThat(login.path("user").path("userCode").asText()).isEqualTo(userCode); + assertThat(login.path("user").has("id")).isFalse(); + assertThat(login.path("user").has("passwordHash")).isFalse(); + JsonNode me = perform(auth(get("/api/users/me"), token), 200).path("data"); + assertThat(me.path("userCode").asText()).isEqualTo(userCode); + assertThat(me.has("id")).isFalse(); + String projectCode = create(token, "管理员的社区项目"); + head(token, projectCode); + + String other = login("another-owner@example.invalid"); + String otherProject = create(other, "其他用户的项目"); + perform(auth(get("/api/workspace/projects/" + otherProject + "/tree"), token), 404); + + jdbc.update( + "UPDATE sys_user SET status='DISABLED', session_version=session_version+1" + + " WHERE user_code=?", + userCode); + perform(auth(get("/api/users/me"), token), 401); + assertThat(loginResponse(email, 403).path("code").asText()).isEqualTo("ACCOUNT_DISABLED"); + jdbc.update( + "UPDATE sys_user SET status='ACTIVE', session_version=session_version+1" + + " WHERE user_code=?", + userCode); + perform(auth(get("/api/users/me"), token), 401); + String fresh = login(email); + perform(auth(get("/api/users/me"), fresh), 200); + + jdbc.update( + "UPDATE sys_user SET session_version=session_version+1 WHERE user_code=?", + userCode); + perform(auth(get("/api/users/me"), fresh), 401); + String renewed = login(email); + perform(auth(get("/api/users/me"), renewed), 200); + perform(auth(post("/api/auth/logout"), renewed), 200); + perform(auth(get("/api/users/me"), renewed), 401); } } diff --git a/vibemake-security/src/main/java/com/linkerbot/vibemake/security/BearerTokenFilter.java b/vibemake-security/src/main/java/com/linkerbot/vibemake/security/BearerTokenFilter.java index 26536b7..5a1deb4 100644 --- a/vibemake-security/src/main/java/com/linkerbot/vibemake/security/BearerTokenFilter.java +++ b/vibemake-security/src/main/java/com/linkerbot/vibemake/security/BearerTokenFilter.java @@ -40,7 +40,8 @@ public class BearerTokenFilter extends OncePerRequestFilter { Long id = session == null ? null : session.userId(); if (id == null) throw new BusinessException(401, "UNAUTHORIZED", "登录已失效,请重新登录"); com.linkerbot.vibemake.bean.entity.User user = users.require(id); - if (!"USER".equals(user.getRole()) || user.getSessionVersion() != session.version()) + if ((!"USER".equals(user.getRole()) && !"ADMIN".equals(user.getRole())) + || user.getSessionVersion() != session.version()) throw new BusinessException(401, "UNAUTHORIZED", "登录已失效,请重新登录"); UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken( diff --git a/vibemake-security/src/test/java/com/linkerbot/vibemake/security/SessionTest.java b/vibemake-security/src/test/java/com/linkerbot/vibemake/security/SessionTest.java index 6010e5b..b6091da 100644 --- a/vibemake-security/src/test/java/com/linkerbot/vibemake/security/SessionTest.java +++ b/vibemake-security/src/test/java/com/linkerbot/vibemake/security/SessionTest.java @@ -1,15 +1,57 @@ package com.linkerbot.vibemake.security; import static org.assertj.core.api.Assertions.*; +import static org.mockito.Mockito.*; +import com.fasterxml.jackson.databind.ObjectMapper; import com.linkerbot.vibemake.common.BusinessException; +import com.linkerbot.vibemake.service.config.RedisStateProperties; import com.linkerbot.vibemake.service.config.VibemakeProperties; +import com.linkerbot.vibemake.service.state.RedisStateStore; import org.junit.jupiter.api.Test; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.ValueOperations; import java.time.Duration; +import java.util.HashMap; +import java.util.Map; class SessionTest { + @Test + @SuppressWarnings("unchecked") + void communityAndAdminTokensForTheSameAccountCannotCrossApplications() { + Map stored = new HashMap<>(); + StringRedisTemplate redis = mock(StringRedisTemplate.class); + ValueOperations values = mock(ValueOperations.class); + when(redis.opsForValue()).thenReturn(values); + when(values.setIfAbsent(anyString(), anyString(), any(Duration.class))) + .thenAnswer(input -> stored.putIfAbsent(input.getArgument(0), input.getArgument(1)) == null); + when(values.get(anyString())).thenAnswer(input -> stored.get(input.getArgument(0))); + RedisStateProperties communityNamespace = new RedisStateProperties(); + communityNamespace.setApplication("api"); + RedisStateProperties adminNamespace = new RedisStateProperties(); + adminNamespace.setApplication("admin"); + TokenService community = + new TokenService( + new VibemakeProperties(), + new RedisStateStore(redis, communityNamespace), + new ObjectMapper()); + TokenService admin = + new TokenService( + new VibemakeProperties(), + new RedisStateStore(redis, adminNamespace), + new ObjectMapper()); + + String communityToken = community.issue(8, 3); + String adminToken = admin.issue(8, 3); + + assertThat(community.resolve(communityToken)).isEqualTo(8L); + assertThat(admin.resolve(adminToken)).isEqualTo(8L); + assertThat(admin.session(communityToken)).isNull(); + assertThat(community.session(adminToken)).isNull(); + } + @Test void sharedStateSurvivesServiceReplacementAndStoresNoRawToken() { com.linkerbot.vibemake.testing.InMemoryStateStore state = diff --git a/vibemake-service/src/main/java/com/linkerbot/vibemake/service/impl/UserServiceImpl.java b/vibemake-service/src/main/java/com/linkerbot/vibemake/service/impl/UserServiceImpl.java index fe933ab..54c1469 100644 --- a/vibemake-service/src/main/java/com/linkerbot/vibemake/service/impl/UserServiceImpl.java +++ b/vibemake-service/src/main/java/com/linkerbot/vibemake/service/impl/UserServiceImpl.java @@ -32,9 +32,10 @@ public class UserServiceImpl implements UserService { throw new BusinessException(403, "ACCOUNT_DISABLED", "账号不可用"); User user = users.selectOne(new LambdaQueryWrapper().eq(User::getEmail, normalized)); if (user == null) user = create(normalized); - if (!"ACTIVE".equals(user.getStatus()) || !"USER".equals(user.getRole())) + if (!"ACTIVE".equals(user.getStatus()) + || (!"USER".equals(user.getRole()) && !"ADMIN".equals(user.getRole()))) throw new BusinessException(403, "ACCOUNT_DISABLED", "账号不可用"); - log.info("用户登录 userCode={}", user.getUserCode()); + log.info("用户登录 userCode={} role={}", user.getUserCode(), user.getRole()); return user; } diff --git a/vibemake-service/src/test/java/com/linkerbot/vibemake/service/impl/UserServiceImplTest.java b/vibemake-service/src/test/java/com/linkerbot/vibemake/service/impl/UserServiceImplTest.java index 8c5614b..1334a44 100644 --- a/vibemake-service/src/test/java/com/linkerbot/vibemake/service/impl/UserServiceImplTest.java +++ b/vibemake-service/src/test/java/com/linkerbot/vibemake/service/impl/UserServiceImplTest.java @@ -20,6 +20,45 @@ class UserServiceImplTest { private final UserMapper users = mock(UserMapper.class); private final UserServiceImpl service = new UserServiceImpl(users); + @ParameterizedTest + @ValueSource(strings = {"USER", "ADMIN"}) + void activeCommunityAccountsCanLogInWithoutAPassword(String role) { + User user = existingUser("ACTIVE"); + user.setRole(role); + when(users.selectOne(any())).thenReturn(user); + + assertThat(service.login(" EXISTING@example.com ")).isSameAs(user); + verify(users, never()).insert(any(User.class)); + } + + @ParameterizedTest + @ValueSource(strings = {"USER", "ADMIN", "OFFICIAL", "UNKNOWN"}) + void disabledAccountsCannotLogInRegardlessOfRole(String role) { + User user = existingUser("DISABLED"); + user.setRole(role); + when(users.selectOne(any())).thenReturn(user); + + assertThatThrownBy(() -> service.login(user.getEmail())) + .isInstanceOfSatisfying(BusinessException.class, error -> { + assertThat(error.status()).isEqualTo(403); + assertThat(error.code()).isEqualTo("ACCOUNT_DISABLED"); + }); + } + + @ParameterizedTest + @ValueSource(strings = {"OFFICIAL", "UNKNOWN"}) + void otherRolesCannotLogIn(String role) { + User user = existingUser("ACTIVE"); + user.setRole(role); + when(users.selectOne(any())).thenReturn(user); + + assertThatThrownBy(() -> service.login(user.getEmail())) + .isInstanceOfSatisfying(BusinessException.class, error -> { + assertThat(error.status()).isEqualTo(403); + assertThat(error.code()).isEqualTo("ACCOUNT_DISABLED"); + }); + } + @Test void codeCollisionRetriesWithAnotherCodeInsteadOfLoggingInAsItsOwner() { User conflict = existingUser("ACTIVE");