All files / stores / useAuthStore.ts

100.00% Branches 0/0
14.29% Lines 19/133
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
 
 
 
 
 
x4
x4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x4
x4
x4
 
x8
x8
x8
x8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x4
x4
x4
x4
 
x8
x8
x8
x4
 
 
 
 
x4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x4























































































































































































































/**
 * 用户认证状态管理 Store
 * 使用 Zustand 管理用户登录状态和用户信息
 */

import { create } from "zustand";
import { persist } from "zustand/middleware";
import type { AppUser } from "@utils/auth.ts";

// 认证状态接口
export interface AuthState {
  // 状态
  isAuthenticated: boolean;
  isLoading: boolean;
  user: Partial<AppUser> | null;
  error: string | null;

  // 操作方法
  login: (user: Partial<AppUser>) => void;
  logout: () => void;
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
  clearError: () => void;
  updateUser: (updates: Partial<AppUser>) => void;

  // 异步操作
  checkAuth: () => Promise<void>;
  performLogout: (redirectTo?: string) => Promise<void>;
}

// 创建认证状态 Store
export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      // 初始状态
      isAuthenticated: false,
      isLoading: false,
      user: null,
      error: null,

      // 登录操作
      login: (user: Partial<AppUser>) => {
        set({
          isAuthenticated: true,
          user,
          error: null,
          isLoading: false,
        });
      },

      // 退出登录操作
      logout: () => {
        set({
          isAuthenticated: false,
          user: null,
          error: null,
          isLoading: false,
        });
      },

      // 设置加载状态
      setLoading: (loading: boolean) => {
        set({ isLoading: loading });
      },

      // 设置错误信息
      setError: (error: string | null) => {
        set({ error, isLoading: false });
      },

      // 清除错误信息
      clearError: () => {
        set({ error: null });
      },

      // 更新用户信息
      updateUser: (updates: Partial<AppUser>) => {
        const currentUser = get().user;
        if (currentUser) {
          set({
            user: { ...currentUser, ...updates },
          });
        }
      },

      // 检查认证状态
      checkAuth: async () => {
        const { setLoading, login, logout, setError } = get();

        setLoading(true);

        try {
          const response = await fetch("/api/auth/me", {
            method: "GET",
            credentials: "include",
          });

          if (response.ok) {
            const data = await response.json();
            if (data.authenticated && data.user) {
              login(data.user);
            } else {
              logout();
            }
          } else {
            logout();
          }
        } catch (error) {
          console.error("Auth check failed:", error);
          setError("Failed to check authentication status");
          logout();
        } finally {
          setLoading(false);
        }
      },

      // 执行退出登录
      performLogout: async (redirectTo = "/") => {
        const { setLoading, logout, setError } = get();

        setLoading(true);

        try {
          const response = await fetch("/api/auth/logout", {
            method: "POST",
            credentials: "include",
          });

          if (response.ok) {
            logout();
            // 重定向到指定页面
            if (typeof globalThis.location !== "undefined") {
              globalThis.location.href = redirectTo;
            }
          } else {
            setError("Failed to logout");
          }
        } catch (error) {
          console.error("Logout failed:", error);
          setError("Logout failed");
          // 即使请求失败,也清除本地状态
          logout();
        } finally {
          setLoading(false);
        }
      },
    }),
    {
      name: "auth-storage", // 本地存储键名
      partialize: (state) => ({
        // 只持久化必要的状态,不包括 isLoading 和 error
        isAuthenticated: state.isAuthenticated,
        user: state.user,
      }),
    },
  ),
);

// 认证相关的工具函数
export const authUtils = {
  /**
   * 检查用户是否已登录
   */
  isLoggedIn: (): boolean => {
    return useAuthStore.getState().isAuthenticated;
  },

  /**
   * 获取当前用户信息
   */
  getCurrentUser: (): Partial<AppUser> | null => {
    return useAuthStore.getState().user;
  },

  /**
   * 检查用户是否有特定权限(扩展功能)
   */
  hasPermission: (_permission: string): boolean => {
    const user = useAuthStore.getState().user;
    // 这里可以根据实际需求实现权限检查逻辑
    // 例如检查用户角色、权限列表等
    return !!user; // 简单实现:只要登录就有权限
  },

  /**
   * 获取用户头像 URL
   */
  getUserAvatar: (size = 40): string => {
    const user = useAuthStore.getState().user;
    if (user?.avatar) {
      return `${user.avatar}&s=${size}`;
    }
    return `https://github.com/identicons/${
      user?.username || "anonymous"
    }.png?size=${size}`;
  },

  /**
   * 获取用户显示名称
   */
  getDisplayName: (): string => {
    const user = useAuthStore.getState().user;
    return user?.name || user?.username || "Anonymous";
  },

  /**
   * 启动 GitHub 登录流程
   */
  startGitHubLogin: (redirectTo = "/") => {
    const loginUrl = `/api/auth/github?redirect=${
      encodeURIComponent(redirectTo)
    }`;
    if (typeof globalThis.location !== "undefined") {
      globalThis.location.href = loginUrl;
    }
  },
};