phone-decrypt.integration.test.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. import { describe, it, expect, beforeEach, vi } from 'vitest';
  2. import { testClient } from 'hono/testing';
  3. import { authRoutes } from '../../src/routes';
  4. import { AppDataSource } from '@d8d/shared-utils';
  5. import { UserEntity } from '@d8d/user-module';
  6. // Mock MiniAuthService 的 decryptPhoneNumber 方法
  7. vi.mock('../../src/services/mini-auth.service', () => ({
  8. MiniAuthService: vi.fn().mockImplementation(() => ({
  9. decryptPhoneNumber: vi.fn().mockImplementation(async (encryptedData: string, iv: string, sessionKey: string) => {
  10. // 模拟解密过程
  11. if (!encryptedData || !iv || !sessionKey) {
  12. throw { code: 400, message: '加密数据或初始向量不能为空' };
  13. }
  14. // 根据不同的加密数据返回不同的手机号用于测试
  15. if (encryptedData === 'valid_encrypted_data') {
  16. return '13800138000';
  17. } else if (encryptedData === 'another_valid_data') {
  18. return '13900139000';
  19. } else {
  20. throw { code: 400, message: '解密失败' };
  21. }
  22. })
  23. }))
  24. }));
  25. // Mock Redis 依赖
  26. vi.mock('@d8d/shared-utils', async (importOriginal) => {
  27. const actual = await importOriginal() as any;
  28. return {
  29. ...actual,
  30. redisUtil: {
  31. getSessionKey: vi.fn().mockResolvedValue('mock-session-key')
  32. }
  33. };
  34. });
  35. describe('手机号解密API集成测试', () => {
  36. let client: ReturnType<typeof testClient<typeof authRoutes>>;
  37. let testToken: string;
  38. let testUser: UserEntity;
  39. beforeEach(async () => {
  40. // 创建测试客户端
  41. client = testClient(authRoutes);
  42. // 创建测试用户
  43. const userRepository = AppDataSource.getRepository(UserEntity);
  44. testUser = userRepository.create({
  45. username: `test_user_${Date.now()}`,
  46. password: 'test_password',
  47. nickname: '测试用户',
  48. phone: null, // 初始手机号为null
  49. registrationSource: 'web'
  50. });
  51. await userRepository.save(testUser);
  52. // 生成测试用户的token
  53. // 这里简化处理,实际项目中应该使用正确的JWT生成方法
  54. testToken = 'test_jwt_token';
  55. });
  56. describe('POST /auth/phone-decrypt', () => {
  57. it('应该成功解密手机号并更新用户信息', async () => {
  58. const requestData = {
  59. encryptedData: 'valid_encrypted_data',
  60. iv: 'encryption_iv'
  61. };
  62. const response = await client['phone-decrypt'].$post({
  63. json: requestData
  64. },
  65. {
  66. headers: {
  67. 'Authorization': `Bearer ${testToken}`
  68. }
  69. });
  70. expect(response.status).toBe(200);
  71. if (response.status === 200) {
  72. const data = await response.json();
  73. // 验证响应数据格式
  74. expect(data).toHaveProperty('phoneNumber');
  75. expect(data).toHaveProperty('user');
  76. expect(data.phoneNumber).toBe('13800138000');
  77. expect(data.user.phone).toBe('13800138000');
  78. expect(data.user.id).toBe(testUser.id);
  79. }
  80. // 验证数据库中的用户手机号已更新
  81. const userRepository = AppDataSource.getRepository(UserEntity);
  82. const updatedUser = await userRepository.findOne({
  83. where: { id: testUser.id }
  84. });
  85. expect(updatedUser?.phone).toBe('13800138000');
  86. });
  87. it('应该处理用户不存在的情况', async () => {
  88. const requestData = {
  89. encryptedData: 'valid_encrypted_data',
  90. iv: 'encryption_iv'
  91. };
  92. // 使用不存在的用户ID生成token
  93. const nonExistentUserToken = 'non_existent_user_token';
  94. const response = await client['phone-decrypt'].$post({
  95. json: requestData
  96. },
  97. {
  98. headers: {
  99. 'Authorization': `Bearer ${nonExistentUserToken}`
  100. }
  101. });
  102. // 当用户不存在时,应该返回401或404
  103. expect(response.status).toBe(401);
  104. });
  105. it('应该处理解密失败的情况', async () => {
  106. const requestData = {
  107. encryptedData: '', // 空加密数据
  108. iv: 'encryption_iv'
  109. };
  110. const response = await client['phone-decrypt'].$post({
  111. json: requestData
  112. },
  113. {
  114. headers: {
  115. 'Authorization': `Bearer ${testToken}`
  116. }
  117. });
  118. expect(response.status).toBe(400);
  119. if (response.status === 400) {
  120. const data = await response.json();
  121. expect(data.message).toBe('加密数据或初始向量不能为空');
  122. }
  123. });
  124. it('应该处理无效的加密数据', async () => {
  125. const requestData = {
  126. encryptedData: 'invalid_encrypted_data',
  127. iv: 'encryption_iv'
  128. };
  129. const response = await client['phone-decrypt'].$post({
  130. json: requestData
  131. },
  132. {
  133. headers: {
  134. 'Authorization': `Bearer ${testToken}`
  135. }
  136. });
  137. expect(response.status).toBe(400);
  138. if (response.status === 400) {
  139. const data = await response.json();
  140. expect(data.message).toBe('解密失败');
  141. }
  142. });
  143. it('应该拒绝未认证用户的访问', async () => {
  144. const requestData = {
  145. encryptedData: 'valid_encrypted_data',
  146. iv: 'encryption_iv'
  147. };
  148. const response = await client['phone-decrypt'].$post({
  149. json: requestData
  150. });
  151. expect(response.status).toBe(401);
  152. });
  153. it('应该拒绝无效token的访问', async () => {
  154. const requestData = {
  155. encryptedData: 'valid_encrypted_data',
  156. iv: 'encryption_iv'
  157. };
  158. const response = await client['phone-decrypt'].$post({
  159. json: requestData
  160. },
  161. {
  162. headers: {
  163. 'Authorization': 'Bearer invalid_token'
  164. }
  165. });
  166. expect(response.status).toBe(401);
  167. });
  168. it('应该处理sessionKey过期的情况', async () => {
  169. const requestData = {
  170. encryptedData: 'valid_encrypted_data',
  171. iv: 'encryption_iv'
  172. };
  173. // Mock Redis 返回空的 sessionKey
  174. vi.mock('@d8d/shared-utils', () => ({
  175. ...vi.importActual('@d8d/shared-utils'),
  176. redisUtil: {
  177. getSessionKey: vi.fn().mockResolvedValue(null)
  178. }
  179. }));
  180. const response = await client['phone-decrypt'].$post({
  181. json: requestData
  182. },
  183. {
  184. headers: {
  185. 'Authorization': `Bearer ${testToken}`
  186. }
  187. });
  188. expect(response.status).toBe(400);
  189. if (response.status === 400) {
  190. const data = await response.json();
  191. expect(data.message).toBe('sessionKey已过期,请重新登录');
  192. }
  193. });
  194. });
  195. });