phone-decrypt.integration.test.ts 6.8 KB

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