All files / src/stores session.ts

57.6% Statements 53/92
51.51% Branches 17/33
77.77% Functions 14/18
56.17% Lines 50/89

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                        6x 6x 6x     10x       5x       11x                     6x 11x 11x 11x 11x 11x 11x 11x 11x 11x   11x     1x   11x                             7x 7x 7x 7x 7x                                                                                                 13x 12x   1x     1x 1x 1x       1x 1x 1x 1x   1x 1x 1x 1x       1x 1x     1x   1x       1x 1x 1x 1x 1x                                 5x 5x     11x                              
import { computed, ref } from "vue";
import { defineStore } from "pinia";
 
import {
  ApiError,
  createApiClient,
  createIdentityApi,
  type AuthTokens,
  type LoginInput,
  type UserProfile,
} from "@plain-journal/foundation";
 
const REFRESH_TOKEN_KEY = "plain-journal:staff-refresh-token:v1";
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL?.trim() ?? "";
const WORKSPACE_ROLES = new Set(["ADMIN", "OPERATOR", "WAREHOUSE"]);
 
export function hasWorkspaceRole(roles: string[]): boolean {
  return roles.some((role) => WORKSPACE_ROLES.has(role));
}
 
export function hasAnyRole(roles: string[], required: string[]): boolean {
  return required.length === 0 || roles.some((role) => required.includes(role));
}
 
function storedRefreshToken(): string | null {
  return typeof localStorage === "undefined"
    ? null
    : localStorage.getItem(REFRESH_TOKEN_KEY);
}
 
export interface AccessDeniedFact {
  email: string;
  roles: string[];
  remoteLogoutConfirmed: boolean;
}
 
export const useStaffSessionStore = defineStore("staff-session", () => {
  const profile = ref<UserProfile | null>(null);
  const accessToken = ref<string | null>(null);
  const refreshToken = ref<string | null>(storedRefreshToken());
  const initialized = ref(false);
  const busy = ref(false);
  const error = ref<string | null>(null);
  const logoutError = ref<string | null>(null);
  const accessDenied = ref<AccessDeniedFact | null>(null);
  let restorePromise: Promise<void> | null = null;
 
  const identityApi = createIdentityApi(createApiClient({
    baseUrl: apiBaseUrl,
    timeoutMs: 8000,
    tokenProvider: () => accessToken.value,
  }));
  const authenticated = computed(() => Boolean(
    profile.value
    && accessToken.value
    && hasWorkspaceRole(profile.value.roles),
  ));
 
  function persistTokens(tokens: AuthTokens) {
    accessToken.value = tokens.accessToken;
    refreshToken.value = tokens.refreshToken;
    if (typeof localStorage !== "undefined") {
      localStorage.setItem(REFRESH_TOKEN_KEY, tokens.refreshToken);
    }
  }
 
  function clearSession() {
    profile.value = null;
    accessToken.value = null;
    refreshToken.value = null;
    Eif (typeof localStorage !== "undefined") {
      localStorage.removeItem(REFRESH_TOKEN_KEY);
    }
  }
 
  async function rejectNonStaff(candidate: UserProfile, token: string) {
    let remoteLogoutConfirmed = false;
    try {
      await identityApi.logout(token);
      remoteLogoutConfirmed = true;
    } catch {
      // The local admin session is still cleared; no privileged role was granted.
    }
    clearSession();
    accessDenied.value = {
      email: candidate.email,
      roles: [...candidate.roles],
      remoteLogoutConfirmed,
    };
  }
 
  async function establish(tokens: AuthTokens): Promise<boolean> {
    persistTokens(tokens);
    const candidate = await identityApi.currentUser();
    if (!hasWorkspaceRole(candidate.roles)) {
      await rejectNonStaff(candidate, tokens.refreshToken);
      return false;
    }
    profile.value = candidate;
    accessDenied.value = null;
    return true;
  }
 
  async function login(input: LoginInput): Promise<boolean> {
    busy.value = true;
    error.value = null;
    logoutError.value = null;
    accessDenied.value = null;
    try {
      return await establish(await identityApi.login(input));
    } catch (cause) {
      error.value = cause instanceof Error ? cause.message : "员工登录未完成。";
      throw cause;
    } finally {
      busy.value = false;
      initialized.value = true;
    }
  }
 
  function restore(): Promise<void> {
    if (initialized.value) {
      return Promise.resolve();
    }
    Iif (restorePromise) {
      return restorePromise;
    }
    restorePromise = (async () => {
      const stored = refreshToken.value;
      Iif (!stored) {
        initialized.value = true;
        return;
      }
      busy.value = true;
      error.value = null;
      try {
        await establish(await identityApi.refresh(stored));
      } catch (cause) {
        Eif (cause instanceof ApiError && cause.status === 401) {
          clearSession();
          error.value = null;
          return;
        }
        error.value = cause instanceof Error ? cause.message : "暂时无法恢复员工会话。";
      } finally {
        busy.value = false;
        initialized.value = true;
      }
    })().finally(() => {
      restorePromise = null;
    });
    return restorePromise;
  }
 
  async function logout() {
    logoutError.value = null;
    const token = refreshToken.value;
    Eif (!token) {
      clearSession();
      return;
    }
    busy.value = true;
    try {
      await identityApi.logout(token);
      clearSession();
    } catch (cause) {
      logoutError.value = cause instanceof Error
        ? cause.message
        : "服务端退出结果未知,当前员工会话仍保留。";
      throw cause;
    } finally {
      busy.value = false;
    }
  }
 
  function clearLocalOnly() {
    clearSession();
    logoutError.value = null;
  }
 
  return {
    profile,
    accessToken,
    initialized,
    busy,
    error,
    logoutError,
    accessDenied,
    authenticated,
    login,
    restore,
    logout,
    clearLocalOnly,
  };
});