useAuthStore.ts 4.49 KB
import { create } from 'zustand';
import { persist } from 'zustand/middleware';

export interface AuthUser {
  username: string;
}

/** 启动续期最多等这么久,超了就当后台没在,直接放页面进去 */
const BOOTSTRAP_TIMEOUT_MS = 4000;

interface AuthState {
  token: string | null;
  user: AuthUser | null;
  status: 'idle' | 'loading' | 'authed' | 'error';
  error: string | null;
  /** 最近一次登录失败的机器可读原因,登录页据此决定要不要立刻换一张验证码 */
  errorCode: string | null;
  login: (username: string, password: string, captcha: LoginCaptcha) => Promise<boolean>;
  logout: () => Promise<void>;
  /** 启动续期:用本地 token 调 /api/me 校验,失效则清态 */
  bootstrap: () => Promise<void>;
}

/** 服务端签发的验证码:id 与图片,明文码不在前端 */
export interface LoginCaptcha {
  id: string;
  code: string;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      token: null,
      user: null,
      status: 'idle',
      error: null,
      errorCode: null,

      async login(username, password, captcha) {
        set({ status: 'loading', error: null, errorCode: null });
        try {
          const res = await fetch('/api/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              username,
              password,
              captchaId: captcha.id,
              captchaCode: captcha.code,
            }),
          });
          if (!res.ok) {
            // 服务端已经给了具体原因(验证码错 / 过期 / 锁定),照抄比统一糊成
            // 「用户名或密码错误」有用得多——否则用户会一直重试密码,其实是图错了
            const data = (await res.json().catch(() => ({}))) as {
              error?: string;
              message?: string;
            };
            const code = data.error ?? `http_${res.status}`;
            set({
              status: 'error',
              errorCode: code,
              error: data.message ?? '用户名或密码错误',
            });
            return false;
          }
          const data = (await res.json()) as { token: string; user: AuthUser };
          set({ token: data.token, user: data.user, status: 'authed', error: null, errorCode: null });
          return true;
        } catch {
          set({
            status: 'error',
            errorCode: 'network',
            error: '登录服务不可用,请确认后台已启动',
          });
          return false;
        }
      },

      async logout() {
        const token = get().token;
        if (token) {
          // 无状态 JWT:后端不留存会话,调一下仅作语义清晰,失败不阻塞前端清态
          try {
            await fetch('/api/logout', {
              method: 'POST',
              headers: { Authorization: `Bearer ${token}` },
            });
          } catch {
            /* ignore */
          }
        }
        set({ token: null, user: null, status: 'idle', error: null, errorCode: null });
      },

      async bootstrap() {
        const token = get().token;
        if (!token) return;
        try {
          const res = await fetch('/api/me', {
            headers: { Authorization: `Bearer ${token}` },
            // 有上限的等待:这个 fetch 挂在 RequireAuth 前面,它不返回,受保护页面就一直不出内容。
            // 后台没起来 / 端口被上一次 concurrently 的残留进程占住时,连接会一直悬着而不是立刻失败。
            signal: AbortSignal.timeout(BOOTSTRAP_TIMEOUT_MS),
          });
          if (res.ok) {
            const data = (await res.json()) as { user: AuthUser };
            set({ user: data.user, status: 'authed' });
          } else if (res.status === 401 || res.status === 403) {
            // 只有「凭证本身不被接受」才清 token(过期 / 伪造),回到未登录
            set({ token: null, user: null, status: 'idle' });
          }
          // 其它非 2xx(dev 代理连不上后台时是 502/504):当成没联系上后台,
          // 保留本地 token 让页面照常出内容,不把人踢到登录页
        } catch {
          // 超时或网络错先保留本地 token,下次启动再续期,不强制登出
        }
      },
    }),
    {
      name: 'hm-auth',
      // 只持久化凭证,状态机字段不入库
      partialize: (s) => ({ token: s.token, user: s.user }),
    },
  ),
);