hejianhao
2026-08-28 16a57a8fc6868cea9171a1119698572407a2fc03
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
package com.tcm.training.admin.app.auth.service;
 
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.tcm.training.admin.app.auth.dto.AppPasswordLoginRequest;
import com.tcm.training.admin.app.auth.dto.AppPasswordResetRequest;
import com.tcm.training.admin.app.auth.dto.AppPasswordResetVerifyRequest;
import com.tcm.training.admin.app.auth.dto.AppAppleLoginRequest;
import com.tcm.training.admin.app.auth.dto.AppSmsCodeSendRequest;
import com.tcm.training.admin.app.auth.dto.AppWechatLoginRequest;
import com.tcm.training.admin.app.auth.vo.AppLoginResponse;
import com.tcm.training.admin.app.auth.vo.AppPasswordResetVerifyResponse;
import com.tcm.training.admin.app.share.service.AppShareService;
import com.tcm.training.admin.member.entity.AppUser;
import com.tcm.training.admin.member.mapper.UserMapper;
import cn.dev33.satoken.stp.SaTokenInfo;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
 
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
 
/**
 * APP 认证服务测试。
 */
@ExtendWith(MockitoExtension.class)
class AppAuthServiceTest {
 
    @BeforeAll
    static void initLambdaCache() {
        MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
        TableInfoHelper.initTableInfo(assistant, AppUser.class);
    }
 
    @Mock
    private UserMapper userMapper;
 
    @Mock
    private AppSmsCodeService appSmsCodeService;
 
    @Mock
    private BCryptPasswordEncoder passwordEncoder;
 
    @Mock
    private AppAuthSessionService appAuthSessionService;
 
    @Mock
    private AppWechatAuthClient appWechatAuthClient;
 
    @Mock
    private AppAppleAuthClient appAppleAuthClient;
 
    @Mock
    private AppShareService appShareService;
 
    @Mock
    private StringRedisTemplate stringRedisTemplate;
 
    private AppAuthService appAuthService;
 
    @Captor
    private ArgumentCaptor<AppUser> appUserCaptor;
 
    /**
     * 每个用例前重新构造被测认证服务。
     */
    @BeforeEach
    void setUp() {
        appAuthService = new AppAuthService(
                userMapper,
                appSmsCodeService,
                passwordEncoder,
                appAuthSessionService,
                appWechatAuthClient,
                appAppleAuthClient,
                appShareService,
                stringRedisTemplate
        );
    }
 
    /**
     * 密码登录能力下线后旧客户端调用应返回统一提示。
     */
    @Test
    void passwordLoginShouldReturnDisabledMessage() {
        AppPasswordLoginRequest request = new AppPasswordLoginRequest();
        request.setPhone("13800138000");
        request.setPassword("abc123!!");
 
        IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
                () -> appAuthService.passwordLogin(request));
 
        assertEquals("当前版本仅支持验证码登录", exception.getMessage());
        verify(passwordEncoder, never()).matches(anyString(), anyString());
        verify(appAuthSessionService, never()).login(anyLong());
    }
 
    /**
     * 忘记密码发码能力下线后旧客户端调用应返回统一提示。
     */
    @Test
    void sendPasswordResetCodeShouldReturnDisabledMessage() {
        AppSmsCodeSendRequest request = new AppSmsCodeSendRequest();
        request.setPhone("13800138001");
 
        IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
                () -> appAuthService.sendPasswordResetCode(request));
 
        assertEquals("当前版本仅支持验证码登录", exception.getMessage());
        verify(appSmsCodeService, never()).createPasswordResetCode(anyString());
    }
 
    /**
     * 忘记密码验证码校验能力下线后旧客户端调用应返回统一提示。
     */
    @Test
    void verifyPasswordResetCodeShouldReturnDisabledMessage() {
        AppPasswordResetVerifyRequest request = new AppPasswordResetVerifyRequest();
        request.setPhone("13800138002");
        request.setCode("666666");
 
        IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
                () -> appAuthService.verifyPasswordResetCode(request));
 
        assertEquals("当前版本仅支持验证码登录", exception.getMessage());
        verify(appSmsCodeService, never()).validatePasswordResetCode(anyString(), anyString());
    }
 
    /**
     * 重置密码能力下线后旧客户端调用应返回统一提示。
     */
    @Test
    void resetPasswordShouldReturnDisabledMessage() {
        AppPasswordResetRequest request = new AppPasswordResetRequest();
        request.setResetTicket("ticket-1");
        request.setPassword("abc123!!");
        request.setConfirmPassword("abc123!!");
 
        IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
                () -> appAuthService.resetPassword(request));
 
        assertEquals("当前版本仅支持验证码登录", exception.getMessage());
        verify(passwordEncoder, never()).encode(anyString());
        verify(userMapper, never()).updateById(any(AppUser.class));
    }
 
    /**
     * 微信已绑定用户登录时应更新微信资料并返回统一登录响应。
     */
    @Test
    void wechatLoginShouldReuseExistingUser() {
        AppWechatLoginRequest request = new AppWechatLoginRequest();
        request.setAccessToken("access-token");
        request.setOpenid("openid-1");
 
        AppWechatUserProfile profile = new AppWechatUserProfile();
        profile.setOpenid("openid-1");
        profile.setNickname("微信昵称");
        profile.setAvatar("https://cdn.example/avatar.png");
        profile.setSex(2);
 
        AppUser user = buildEnabledUser("13800138000", "ENCODED");
        user.setWechatOpenid("openid-1");
        user.setNickname(null);
        user.setAvatar(null);
 
        SaTokenInfo tokenInfo = new SaTokenInfo();
        tokenInfo.setTokenValue("wechat-token");
        tokenInfo.setTokenTimeout(7200L);
 
        when(appWechatAuthClient.resolveUserProfile(request)).thenReturn(profile);
        when(userMapper.selectOne(any())).thenReturn(user);
        when(appAuthSessionService.getTokenInfo()).thenReturn(tokenInfo);
 
        AppLoginResponse response = appAuthService.wechatLogin(request);
 
        verify(userMapper).updateById(appUserCaptor.capture());
        verify(userMapper, never()).insert(any());
        assertEquals("openid-1", appUserCaptor.getValue().getWechatOpenid());
        assertEquals("微信昵称", appUserCaptor.getValue().getNickname());
        assertEquals("https://cdn.example/avatar.png", appUserCaptor.getValue().getAvatar());
        assertEquals(Integer.valueOf(0), appUserCaptor.getValue().getGender());
        assertEquals("微信昵称", response.getUser().getNickname());
        assertEquals("https://cdn.example/avatar.png", response.getUser().getAvatar());
    }
 
    /**
     * 微信首次登录时应自动创建普通用户并返回统一登录响应。
     */
    @Test
    void wechatLoginShouldCreateUserWhenOpenidNotExists() {
        AppWechatLoginRequest request = new AppWechatLoginRequest();
        request.setAccessToken("access-token");
        request.setOpenid("openid-new");
        request.setInviteCode("ABC123");
 
        AppWechatUserProfile profile = new AppWechatUserProfile();
        profile.setOpenid("openid-new");
        profile.setNickname("新微信用户");
        profile.setAvatar("https://cdn.example/new-avatar.png");
        profile.setSex(1);
 
        SaTokenInfo tokenInfo = new SaTokenInfo();
        tokenInfo.setTokenValue("new-token");
        tokenInfo.setTokenTimeout(7200L);
 
        when(appWechatAuthClient.resolveUserProfile(request)).thenReturn(profile);
        when(userMapper.selectOne(any())).thenReturn(null);
        when(appShareService.resolveInviteBindingTarget("ABC123")).thenReturn(buildInviteTarget());
        when(appAuthSessionService.getTokenInfo()).thenReturn(tokenInfo);
 
        AppLoginResponse response = appAuthService.wechatLogin(request);
 
        verify(userMapper).insert(appUserCaptor.capture());
        verify(userMapper, never()).updateById(any());
        assertNull(appUserCaptor.getValue().getPhone());
        assertEquals("openid-new", appUserCaptor.getValue().getWechatOpenid());
        assertEquals("新微信用户", appUserCaptor.getValue().getNickname());
        assertEquals("https://cdn.example/new-avatar.png", appUserCaptor.getValue().getAvatar());
        assertEquals(Integer.valueOf(1), appUserCaptor.getValue().getGender());
        assertEquals(Integer.valueOf(0), appUserCaptor.getValue().getType());
        assertEquals(Long.valueOf(10L), appUserCaptor.getValue().getClinicId());
        assertEquals(Long.valueOf(20L), appUserCaptor.getValue().getSuperiorClinicUserId());
        assertEquals("new-token", response.getToken());
    }
 
    /**
     * 微信首次登录未携带邀请码时应创建待绑定手机号的临时用户。
     */
    @Test
    void wechatLoginShouldCreatePendingUserWhenInviteCodeMissing() {
        AppWechatLoginRequest request = new AppWechatLoginRequest();
        request.setAccessToken("access-token");
        request.setOpenid("openid-new");
 
        AppWechatUserProfile profile = new AppWechatUserProfile();
        profile.setOpenid("openid-new");
 
        when(appWechatAuthClient.resolveUserProfile(request)).thenReturn(profile);
        when(userMapper.selectOne(any())).thenReturn(null);
        when(userMapper.insert(any(AppUser.class))).thenAnswer(invocation -> {
            AppUser inserted = invocation.getArgument(0);
            inserted.setId(2001L);
            return 1;
        });
        when(appAuthSessionService.getTokenInfo()).thenReturn(buildTokenInfo("wechat-pending-token", 7200L));
 
        AppLoginResponse response = appAuthService.wechatLogin(request);
 
        verify(userMapper).insert(appUserCaptor.capture());
        assertNull(appUserCaptor.getValue().getPhone());
        assertEquals("openid-new", appUserCaptor.getValue().getWechatOpenid());
        assertEquals("wechat-pending-token", response.getToken());
    }
 
    /**
     * 苹果已绑定用户登录时应更新苹果绑定信息并返回统一登录响应。
     */
    @Test
    void appleLoginShouldReuseExistingUser() {
        AppAppleLoginRequest request = new AppAppleLoginRequest();
        request.setIdentityToken("identity-token");
        request.setUserIdentifier("apple-user-1");
 
        AppAppleUserProfile profile = new AppAppleUserProfile();
        profile.setSubject("apple-subject-1");
        profile.setUserIdentifier("apple-user-1");
 
        AppUser user = buildEnabledUser("13800138009", "ENCODED");
        user.setAppleIdentitySubject("apple-subject-1");
        user.setAppleUserIdentifier("apple-user-legacy");
        user.setNickname("已存在用户");
 
        SaTokenInfo tokenInfo = new SaTokenInfo();
        tokenInfo.setTokenValue("apple-token");
        tokenInfo.setTokenTimeout(7200L);
 
        when(appAppleAuthClient.resolveUserProfile(request)).thenReturn(profile);
        when(userMapper.selectOne(any())).thenReturn(user);
        when(appAuthSessionService.getTokenInfo()).thenReturn(tokenInfo);
 
        AppLoginResponse response = appAuthService.appleLogin(request);
 
        verify(userMapper).updateById(appUserCaptor.capture());
        verify(userMapper, never()).insert(any());
        assertEquals("apple-subject-1", appUserCaptor.getValue().getAppleIdentitySubject());
        assertEquals("apple-user-1", appUserCaptor.getValue().getAppleUserIdentifier());
        assertEquals("已存在用户", response.getUser().getNickname());
        assertEquals("apple-token", response.getToken());
    }
 
    /**
     * 苹果首次登录时应自动创建普通用户并等待后续绑定手机号。
     */
    @Test
    void appleLoginShouldCreateUserWhenSubjectNotExists() {
        AppAppleLoginRequest request = new AppAppleLoginRequest();
        request.setIdentityToken("identity-token");
        request.setUserIdentifier("apple-user-new");
        request.setInviteCode("ABC123");
 
        AppAppleUserProfile profile = new AppAppleUserProfile();
        profile.setSubject("apple-subject-new");
        profile.setUserIdentifier("apple-user-new");
 
        SaTokenInfo tokenInfo = new SaTokenInfo();
        tokenInfo.setTokenValue("apple-new-token");
        tokenInfo.setTokenTimeout(7200L);
 
        when(appAppleAuthClient.resolveUserProfile(request)).thenReturn(profile);
        when(userMapper.selectOne(any())).thenReturn(null);
        when(appShareService.resolveInviteBindingTarget("ABC123")).thenReturn(buildInviteTarget());
        when(appAuthSessionService.getTokenInfo()).thenReturn(tokenInfo);
 
        AppLoginResponse response = appAuthService.appleLogin(request);
 
        verify(userMapper).insert(appUserCaptor.capture());
        verify(userMapper, never()).updateById(any());
        assertNull(appUserCaptor.getValue().getPhone());
        assertEquals("apple-subject-new", appUserCaptor.getValue().getAppleIdentitySubject());
        assertEquals("apple-user-new", appUserCaptor.getValue().getAppleUserIdentifier());
        assertEquals("苹果用户", appUserCaptor.getValue().getNickname());
        assertEquals(Integer.valueOf(0), appUserCaptor.getValue().getType());
        assertEquals(Long.valueOf(10L), appUserCaptor.getValue().getClinicId());
        assertEquals(Long.valueOf(20L), appUserCaptor.getValue().getSuperiorClinicUserId());
        assertEquals("apple-new-token", response.getToken());
    }
 
    /**
     * 苹果首次登录未携带邀请码时应创建待绑定手机号的临时用户。
     */
    @Test
    void appleLoginShouldCreatePendingUserWhenInviteCodeMissing() {
        AppAppleLoginRequest request = new AppAppleLoginRequest();
        request.setIdentityToken("identity-token");
        request.setUserIdentifier("apple-user-new");
 
        AppAppleUserProfile profile = new AppAppleUserProfile();
        profile.setSubject("apple-subject-new");
        profile.setUserIdentifier("apple-user-new");
 
        when(appAppleAuthClient.resolveUserProfile(request)).thenReturn(profile);
        when(userMapper.selectOne(any())).thenReturn(null);
        when(userMapper.insert(any(AppUser.class))).thenAnswer(invocation -> {
            AppUser inserted = invocation.getArgument(0);
            inserted.setId(3001L);
            return 1;
        });
        when(appAuthSessionService.getTokenInfo()).thenReturn(buildTokenInfo("apple-pending-token", 7200L));
 
        AppLoginResponse response = appAuthService.appleLogin(request);
 
        verify(userMapper).insert(appUserCaptor.capture());
        assertNull(appUserCaptor.getValue().getPhone());
        assertEquals("apple-subject-new", appUserCaptor.getValue().getAppleIdentitySubject());
        assertEquals("apple-pending-token", response.getToken());
    }
 
    /**
     * 苹果授权无效时应直接拒绝登录。
     */
    @Test
    void appleLoginShouldFailWhenIdentityTokenInvalid() {
        AppAppleLoginRequest request = new AppAppleLoginRequest();
        request.setIdentityToken("bad-token");
        request.setUserIdentifier("apple-user-bad");
 
        when(appAppleAuthClient.resolveUserProfile(request)).thenThrow(new IllegalArgumentException("苹果登录授权失败"));
 
        IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
                () -> appAuthService.appleLogin(request));
 
        assertEquals("苹果登录授权失败", exception.getMessage());
    }
 
    /**
     * 构造邀请绑定目标。
     */
    private AppShareService.InviteBindingTarget buildInviteTarget() {
        AppShareService.InviteBindingTarget target = new AppShareService.InviteBindingTarget();
        target.setInviteCode("ABC123");
        target.setClinicId(10L);
        target.setSuperiorClinicUserId(20L);
        return target;
    }
 
    /**
     * 构造测试用 token 信息。
     */
    private SaTokenInfo buildTokenInfo(String tokenValue, long timeout) {
        SaTokenInfo tokenInfo = new SaTokenInfo();
        tokenInfo.setTokenValue(tokenValue);
        tokenInfo.setTokenTimeout(timeout);
        return tokenInfo;
    }
 
    /**
     * 统一构造启用中的 APP 用户测试桩。
     */
    private AppUser buildEnabledUser(String phone, String password) {
        AppUser user = new AppUser();
        user.setId(1L);
        user.setPhone(phone);
        user.setPassword(password);
        user.setNickname("测试用户");
        user.setStatus(1);
        user.setType(0);
        return user;
    }
}