All files / store userStore.ts

57.72% Statements 71/123
54.41% Branches 37/68
68.18% Functions 15/22
57.72% Lines 71/123

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                          12x   12x                         4x 4x     4x     4x   4x 1x       3x             3x   3x   1x 1x 1x           2x 2x     2x             2x   2x 1x       1x           1x             1x   1x   1x 1x 1x           3x   3x     2x               1x                     2x 2x   2x   1x 1x       1x         1x               8x 8x   8x   1x   1x       1x               1x     1x     7x     1x   1x       1x 1x   1x           3x 3x   3x   3x 1x       2x   2x   1x 1x 1x                                                                                                                                                                                     2x       3x               1x       13x         12x   86x           12x 12x       12x                                                          
/**
 * 用户状态管理 Store
 */
 
import AsyncStorage from '@react-native-async-storage/async-storage';
import { create } from 'zustand';
import { createJSONStorage, persist } from 'zustand/middleware';
 
import type { UserWithPets } from '@/src/lib/supabase';
import { supabaseAuthService, supabaseProfileService } from '@/src/lib/supabase';
import { logger } from '@/src/utils/logger';
import { loginSchema, registerSchema } from '@/src/schemas/auth.schema';
 
import type { Session } from '@supabase/supabase-js';
 
// ==================== 类型定义 ====================
 
interface UserState {
  // 用户信息
  user: UserWithPets | null;
  session: Session | null;
  accessToken: string | null;
 
  // 状态标志
  isAuthenticated: boolean;
  isLoading: boolean;
  _hasHydrated: boolean;
 
  // 认证方法
  login: (email: string, password: string) => Promise<void>;
  register: (email: string, username: string, password: string) => Promise<void>;
  logout: () => Promise<void>;
  refreshAccessToken: () => Promise<void>;
 
  // 用户信息方法
  fetchCurrentUser: () => Promise<void>;
  updateProfile: (params: { username?: string; bio?: string; phone?: string }) => Promise<void>;
  uploadAvatar: (imageUri: string) => Promise<void>;
  deleteAvatar: () => Promise<void>;
 
  // 密码管理
  updatePassword: (newPassword: string) => Promise<void>;
  resetPassword: (email: string) => Promise<void>;
 
  // 状态管理方法
  setUser: (user: UserWithPets | null) => void;
  setSession: (session: Session | null) => void;
  setLoading: (loading: boolean) => void;
  setHasHydrated: (hasHydrated: boolean) => void;
}
 
// ==================== Store 实现 ====================
 
export const useUserStore = create<UserState>()(
  persist(
    (set, get) => ({
      // ==================== 初始状态 ====================
      user: null,
      session: null,
      accessToken: null,
      isAuthenticated: false,
      isLoading: false,
      _hasHydrated: false,
 
      // ==================== 认证方法 ====================
 
      /** 用户登录 */
      login: async (email: string, password: string) => {
        try {
          set({ isLoading: true });
 
          // 使用 Zod 验证输入
          const validatedData = loginSchema.parse({ email, password });
 
          // 调用 Supabase Auth 登录
          const { data, error } = await supabaseAuthService.login(validatedData);
 
          if (error || !data) {
            throw new Error(error?.message || '登录失败');
          }
 
          // 保存 session 和 accessToken
          set({
            session: data.session,
            accessToken: data.session?.access_token || null,
            isAuthenticated: true,
          });
 
          // 获取用户完整信息(含头像、宠物)
          await get().fetchCurrentUser();
 
          set({ isLoading: false });
        } catch (error) {
          set({ isLoading: false });
          logger.error('登录失败', error as Error);
          throw error;
        }
      },
 
      /** 用户注册 */
      register: async (email: string, username: string, password: string) => {
        try {
          set({ isLoading: true });
 
          // 使用 Zod 验证输入
          const validatedData = registerSchema.parse({
            email,
            username,
            password,
          });
 
          // 调用 Supabase Auth 注册
          const { data, error } = await supabaseAuthService.register(validatedData);
 
          if (error || !data) {
            throw new Error(error?.message || '注册失败');
          }
 
          // 如果没有 session,说明需要邮箱验证
          Iif (!data.session) {
            set({ isLoading: false });
            return; // 正常返回,不抛出错误
          }
 
          // 保存 session 和 accessToken 并自动登录
          set({
            session: data.session,
            accessToken: data.session?.access_token || null,
            isAuthenticated: true,
          });
 
          // 获取用户完整信息
          await get().fetchCurrentUser();
 
          set({ isLoading: false });
        } catch (error) {
          set({ isLoading: false });
          logger.error('注册失败', error as Error);
          throw error;
        }
      },
 
      /** 用户登出 */
      logout: async () => {
        try {
          // 调用 Supabase Auth 登出
          await supabaseAuthService.logout();
 
          // 清除本地状态
          set({
            user: null,
            session: null,
            accessToken: null,
            isAuthenticated: false,
          });
        } catch (error) {
          // 即使登出失败,也清除本地状态
          set({
            user: null,
            session: null,
            accessToken: null,
            isAuthenticated: false,
          });
        }
      },
 
      /** 刷新访问令牌 */
      refreshAccessToken: async () => {
        try {
          const { data, error } = await supabaseAuthService.refreshSession();
 
          if (error || !data) {
            // Token 刷新失败,清除登录状态
            get().logout();
            throw new Error('登录已过期,请重新登录');
          }
 
          // 更新 session 和 accessToken
          set({
            session: data,
            accessToken: data.access_token,
          });
        } catch (error) {
          throw error;
        }
      },
 
      // ==================== 用户信息方法 ====================
 
      /** 获取当前用户完整信息 */
      fetchCurrentUser: async () => {
        try {
          const { data, error } = await supabaseProfileService.getCurrentProfile();
 
          if (error || !data) {
            // 如果是认证错误,静默处理
            const errorMessage = error?.message || '获取用户信息失败';
            const isAuthError =
              errorMessage.includes('session') ||
              errorMessage.includes('token') ||
              errorMessage.includes('Auth');
 
            Iif (isAuthError) {
              // 静默清除本地状态,不打印日志
              set({
                user: null,
                session: null,
                isAuthenticated: false,
              });
            } else {
              logger.error('获取用户信息失败', new Error(errorMessage));
            }
 
            throw new Error(errorMessage);
          }
 
          set({ user: data });
        } catch (error) {
          // 认证相关错误不需要打印堆栈
          const errorMessage = error instanceof Error ? error.message : String(error);
          const isAuthError =
            errorMessage.includes('session') ||
            errorMessage.includes('token') ||
            errorMessage.includes('Auth');
 
          Eif (!isAuthError) {
            logger.error('用户信息获取失败', error as Error);
          }
          throw error;
        }
      },
 
      /** 更新用户资料 */
      updateProfile: async (params: { username?: string; bio?: string; phone?: string }) => {
        try {
          set({ isLoading: true });
 
          const { error } = await supabaseProfileService.updateProfile(params);
 
          if (error) {
            throw new Error(error.message || '更新资料失败');
          }
 
          // 刷新用户信息
          await get().fetchCurrentUser();
 
          set({ isLoading: false });
        } catch (error) {
          set({ isLoading: false });
          logger.error('更新资料失败', error as Error);
          throw error;
        }
      },
 
      /** 上传头像 */
      uploadAvatar: async (imageUri: string) => {
        try {
          set({ isLoading: true });
 
          const { error } = await supabaseProfileService.uploadAvatar(imageUri);
 
          if (error) {
            throw new Error(error.message || '上传头像失败');
          }
 
          // 刷新用户信息
          await get().fetchCurrentUser();
 
          set({ isLoading: false });
        } catch (error) {
          set({ isLoading: false });
          logger.error('头像上传失败', error as Error);
          throw error;
        }
      },
 
      /** 删除头像 */
      deleteAvatar: async () => {
        try {
          set({ isLoading: true });
 
          const { error } = await supabaseProfileService.deleteAvatar();
 
          if (error) {
            throw new Error(error.message || '删除头像失败');
          }
 
          // 刷新用户信息
          await get().fetchCurrentUser();
 
          set({ isLoading: false });
        } catch (error) {
          set({ isLoading: false });
          logger.error('头像删除失败', error as Error);
          throw error;
        }
      },
 
      // ==================== 密码管理 ====================
 
      /** 更新密码(需要已登录) */
      updatePassword: async (newPassword: string) => {
        try {
          set({ isLoading: true });
 
          const { error } = await supabaseAuthService.updatePassword({ newPassword });
 
          if (error) {
            throw new Error(error.message || '修改密码失败');
          }
 
          set({ isLoading: false });
        } catch (error) {
          set({ isLoading: false });
          logger.error('修改密码失败', error as Error);
          throw error;
        }
      },
 
      /** 发送密码重置邮件 */
      resetPassword: async (email: string) => {
        try {
          set({ isLoading: true });
 
          const { error } = await supabaseAuthService.resetPassword({ email });
 
          if (error) {
            throw new Error(error.message || '发送重置邮件失败');
          }
 
          set({ isLoading: false });
        } catch (error) {
          set({ isLoading: false });
          logger.error('发送重置邮件失败', error as Error);
          throw error;
        }
      },
 
      // ==================== 状态管理方法 ====================
 
      setUser: (user: UserWithPets | null) => {
        set({ user, isAuthenticated: !!user });
      },
 
      setSession: (session: Session | null) => {
        set({
          session,
          accessToken: session?.access_token || null,
          isAuthenticated: !!session,
        });
      },
 
      setLoading: (loading: boolean) => {
        set({ isLoading: loading });
      },
 
      setHasHydrated: (hasHydrated: boolean) => {
        set({ _hasHydrated: hasHydrated });
      },
    }),
    {
      name: 'userStorage',
      storage: createJSONStorage(() => AsyncStorage),
      // 只持久化这些字段
      partialize: (state) => ({
        // 注意:session 不需要持久化,Supabase SDK 会自动处理
        user: state.user,
        isAuthenticated: state.isAuthenticated,
      }),
      // 水化完成后的回调
      onRehydrateStorage: () => (state) => {
        state?.setHasHydrated(true);
 
        // Supabase SDK 会自动从 AsyncStorage 恢复 Session
        // 检查是否有有效的 Session
        Iif (state?.isAuthenticated) {
          supabaseAuthService
            .getSession()
            .then(({ data: session, error }) => {
              if (error || !session) {
                // Session 无效或已过期,静默清除登录状态
                state.setUser(null);
                state.setSession(null);
                return;
              }
 
              // Session 有效,设置并刷新用户信息
              state.setSession(session);
              state.fetchCurrentUser().catch(() => {
                // 如果获取用户信息失败,静默清除登录状态
                state.setUser(null);
                state.setSession(null);
              });
            })
            .catch(() => {
              // Refresh Token 失效或其他认证错误,静默清除
              state.setUser(null);
              state.setSession(null);
            });
        }
      },
    }
  )
);