LineCallbackDeviceTrustTest.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. package com.ruoyi.app.user;
  2. import com.ruoyi.app.user.service.DeviceTrustService;
  3. import com.ruoyi.app.utils.oauth.LineOAuthProperties;
  4. import com.ruoyi.app.utils.oauth.OAuthIdentity;
  5. import com.ruoyi.common.core.redis.RedisCache;
  6. import com.ruoyi.common.utils.spring.SpringUtils;
  7. import com.ruoyi.system.domain.InfoUser;
  8. import com.ruoyi.system.domain.InfoUserDevice;
  9. import com.ruoyi.system.domain.InfoUserOauth;
  10. import com.ruoyi.system.mapper.InfoUserDeviceMapper;
  11. import com.ruoyi.system.mapper.InfoUserOauthMapper;
  12. import com.ruoyi.system.service.IInfoUserService;
  13. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  14. import org.junit.jupiter.api.AfterAll;
  15. import org.junit.jupiter.api.AfterEach;
  16. import org.junit.jupiter.api.BeforeAll;
  17. import org.junit.jupiter.api.BeforeEach;
  18. import org.junit.jupiter.api.Test;
  19. import org.mockito.ArgumentCaptor;
  20. import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
  21. import org.springframework.beans.factory.support.DefaultListableBeanFactory;
  22. import org.springframework.context.support.StaticMessageSource;
  23. import org.springframework.mock.web.MockHttpServletRequest;
  24. import org.springframework.mock.web.MockHttpServletResponse;
  25. import org.springframework.test.util.ReflectionTestUtils;
  26. import org.springframework.web.context.request.RequestContextHolder;
  27. import org.springframework.web.context.request.ServletRequestAttributes;
  28. import java.util.concurrent.TimeUnit;
  29. import static org.junit.jupiter.api.Assertions.assertEquals;
  30. import static org.junit.jupiter.api.Assertions.assertTrue;
  31. import static org.mockito.ArgumentMatchers.any;
  32. import static org.mockito.ArgumentMatchers.anyInt;
  33. import static org.mockito.ArgumentMatchers.anyString;
  34. import static org.mockito.ArgumentMatchers.eq;
  35. import static org.mockito.ArgumentMatchers.startsWith;
  36. import static org.mockito.Mockito.mock;
  37. import static org.mockito.Mockito.never;
  38. import static org.mockito.Mockito.verify;
  39. import static org.mockito.Mockito.when;
  40. /**
  41. * LINE 回调设备信任免绑分支测试(029-device-trust-phone-bind,TDD 先行)。
  42. * state 参数语义:前端把 deviceId 放进 LINE authorize 的 state 带回(见 contracts/api-contract.md §5)。
  43. */
  44. class LineCallbackDeviceTrustTest {
  45. private static ConfigurableListableBeanFactory originalBeanFactory;
  46. private final RedisCache redisCache = mock(RedisCache.class);
  47. private final IInfoUserService infoUserService = mock(IInfoUserService.class);
  48. private final InfoUserOauthMapper infoUserOauthMapper = mock(InfoUserOauthMapper.class);
  49. private final com.ruoyi.app.utils.oauth.OAuthVerifyService oauthVerifyService =
  50. mock(com.ruoyi.app.utils.oauth.OAuthVerifyService.class);
  51. private final InfoUserDeviceMapper deviceMapper = mock(InfoUserDeviceMapper.class);
  52. private LineCallbackController controller;
  53. private MockHttpServletResponse response;
  54. @BeforeAll
  55. static void saveStatics() {
  56. originalBeanFactory = (ConfigurableListableBeanFactory)
  57. ReflectionTestUtils.getField(SpringUtils.class, "beanFactory");
  58. }
  59. @AfterAll
  60. static void restoreStatics() {
  61. new SpringUtils().postProcessBeanFactory(originalBeanFactory);
  62. }
  63. @BeforeEach
  64. void setUp() throws Exception {
  65. DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
  66. StaticMessageSource messageSource = new StaticMessageSource();
  67. messageSource.setUseCodeAsDefaultMessage(true);
  68. beanFactory.registerSingleton("messageSource", messageSource);
  69. beanFactory.registerSingleton("redisCache", redisCache);
  70. new SpringUtils().postProcessBeanFactory(beanFactory);
  71. MockHttpServletRequest request = new MockHttpServletRequest();
  72. request.setRemoteAddr("127.0.0.1");
  73. request.addHeader("User-Agent", "JUnit");
  74. RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
  75. LineOAuthProperties properties = new LineOAuthProperties();
  76. LineOAuthProperties.Channel user = new LineOAuthProperties.Channel();
  77. user.setClientId("user-client");
  78. user.setClientSecret("secret");
  79. user.setRedirectUri("https://api.test/auth/line/callback");
  80. user.setAppRedirect("com.test.app://oauthLogin");
  81. properties.setUser(user);
  82. controller = new LineCallbackController();
  83. ReflectionTestUtils.setField(controller, "redisCache", redisCache);
  84. ReflectionTestUtils.setField(controller, "infoUserService", infoUserService);
  85. ReflectionTestUtils.setField(controller, "infoUserOauthMapper", infoUserOauthMapper);
  86. ReflectionTestUtils.setField(controller, "oauthVerifyService", oauthVerifyService);
  87. ReflectionTestUtils.setField(controller, "deviceTrustService", DeviceTrustTestSupport.service(deviceMapper, infoUserOauthMapper));
  88. ReflectionTestUtils.setField(controller, "lineOAuthProperties", properties);
  89. response = new MockHttpServletResponse();
  90. }
  91. @AfterEach
  92. void tearDown() {
  93. RequestContextHolder.resetRequestAttributes();
  94. }
  95. private static InfoUserDevice trust(String deviceId, String phone, long userId) {
  96. InfoUserDevice t = new InfoUserDevice();
  97. t.setDeviceId(deviceId);
  98. t.setPhone(phone);
  99. t.setUserId(userId);
  100. return t;
  101. }
  102. @Test
  103. void unboundWithTrustedDeviceRedirectsDeviceConfirmAndWritesBothKeys() throws Exception {
  104. when(oauthVerifyService.verifyIdentity("line", "code-1")).thenReturn(new OAuthIdentity("line-uid-1", null));
  105. when(infoUserOauthMapper.selectOne(any())).thenReturn(null);
  106. when(deviceMapper.selectById("dev-1")).thenReturn(trust("dev-1", "0987654321", 100L));
  107. controller.callback("line", "code-1", "dev-1", response);
  108. String location = response.getRedirectedUrl();
  109. assertTrue(location != null && location.startsWith("com.test.app://oauthLogin?deviceConfirm=1&tempKey="),
  110. "应回跳 deviceConfirm 分支,实际: " + location);
  111. assertTrue(location.endsWith("&maskedPhone=098****4321"), "应带脱敏手机号,实际: " + location);
  112. ArgumentCaptor<String> tempKeyCaptor = ArgumentCaptor.forClass(String.class);
  113. verify(redisCache).setCacheObject(startsWith("oauth:bind:"), eq("line@line-uid-1"), eq(5), eq(TimeUnit.MINUTES));
  114. verify(redisCache).setCacheObject(startsWith("oauth:bind:dev:"), eq("dev-1"), eq(5), eq(TimeUnit.MINUTES));
  115. }
  116. @Test
  117. void unboundWithUnknownStateStillRedirectsNeedPhone() throws Exception {
  118. when(oauthVerifyService.verifyIdentity("line", "code-2")).thenReturn(new OAuthIdentity("line-uid-2", null));
  119. when(infoUserOauthMapper.selectOne(any())).thenReturn(null);
  120. when(deviceMapper.selectById("dev-x")).thenReturn(null);
  121. controller.callback("line", "code-2", "dev-x", response);
  122. String location = response.getRedirectedUrl();
  123. assertTrue(location != null && location.startsWith("com.test.app://oauthLogin?needPhone=1&tempKey="),
  124. "应维持 needPhone 回跳,实际: " + location);
  125. verify(redisCache, never()).setCacheObject(startsWith("oauth:bind:dev:"), anyString(), anyInt(), any(TimeUnit.class));
  126. }
  127. @org.junit.jupiter.params.ParameterizedTest
  128. @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true})
  129. void boundUserWithDeviceStateRedirectsTokenAndRecordsTrust(boolean pending) throws Exception {
  130. when(oauthVerifyService.verifyIdentity("line", "code-3")).thenReturn(new OAuthIdentity("line-uid-3", null));
  131. InfoUserOauth bind = new InfoUserOauth(); bind.setId(77L);
  132. bind.setUserId(100L);
  133. bind.setProvider("line");
  134. bind.setProviderUid("line-uid-3");
  135. when(infoUserOauthMapper.selectOne(any())).thenReturn(bind);
  136. InfoUser u = new InfoUser();
  137. u.setUserId(100L);
  138. u.setPhone("0987654321");
  139. u.setUserType("0");
  140. u.setStatus("0");
  141. u.setDelFlag(pending ? "1" : "0");
  142. UserCancellationService cancellation = mock(UserCancellationService.class);
  143. ReflectionTestUtils.setField(controller, "userCancellationService", cancellation);
  144. if (pending) when(cancellation.prepareLogin(any())).thenReturn(new UserCancellationService.LoginConfirmationView(
  145. "cancellationConfirm", 1, new java.util.Date(System.currentTimeMillis() + 60000), "a".repeat(32), 60));
  146. when(infoUserService.getOne(any())).thenReturn(u);
  147. when(deviceMapper.selectById("dev-1")).thenReturn(null);
  148. controller.callback("line", "code-3", "dev-1", response);
  149. if (pending) {
  150. assertTrue(response.getRedirectedUrl().contains("cancellationConfirm=1"));
  151. assertTrue(response.getRedirectedUrl().contains("remainingDays=1"));
  152. org.junit.jupiter.api.Assertions.assertFalse(response.getRedirectedUrl().contains("token="));
  153. assertEquals("1", u.getDelFlag());
  154. verify(cancellation).prepareLogin(any());
  155. verify(deviceMapper, never()).updateById(any(InfoUserDevice.class));
  156. return;
  157. }
  158. String location = response.getRedirectedUrl();
  159. assertTrue(location != null && location.startsWith("com.test.app://oauthLogin?token="),
  160. "已绑定应直接回跳 token,实际: " + location);
  161. verify(deviceMapper).ensureExists("dev-1", "0987654321", 100L);
  162. org.mockito.Mockito.verifyNoInteractions(cancellation);
  163. }
  164. @Test
  165. void boundIdentityFromOldPhoneRequiresPhoneLoginWithoutIssuingToken() throws Exception {
  166. when(oauthVerifyService.verifyIdentity("line", "conflict")).thenReturn(new OAuthIdentity("old-identity", null));
  167. InfoUserOauth bind = new InfoUserOauth(); bind.setId(77L); bind.setUserId(100L);
  168. bind.setProvider("line"); bind.setProviderUid("old-identity");
  169. when(infoUserOauthMapper.selectOne(any())).thenReturn(bind);
  170. InfoUser user = new InfoUser(); user.setUserId(100L); user.setPhone("0987654321");
  171. user.setUserType("0"); user.setStatus("0"); user.setDelFlag("0");
  172. when(infoUserService.getOne(any())).thenReturn(user);
  173. when(deviceMapper.selectById("dev-1")).thenReturn(trust("dev-1", "0911111111", 200L));
  174. controller.callback("line", "conflict", "dev-1", response);
  175. assertEquals("com.test.app://oauthLogin?error=phone_login_required", response.getRedirectedUrl());
  176. verify(redisCache, never()).deleteKeys(anyString());
  177. verify(deviceMapper, never()).updateById(any(InfoUserDevice.class));
  178. }
  179. }