session.ts 2.49 KB
/** 登录会话:令牌、用户信息和权限均属于访问控制范围。 */
export interface LoginSession {
  token: string;
  tokenType: 'Bearer' | string;
  expireAt: string;
  userId: number;
  account: string;
  name: string;
  orgId: number;
  dataScope: number;
  roleCodes: string[];
  permCodes: string[];
}

const SESSION_KEY = 'session';
/** 用户信息及权限的统一本地存储键。 */
const USER_INFO_KEY = 'uj-auth-user-info';

export function saveLoginSession(session: LoginSession) {
  localStorage.setItem(SESSION_KEY, JSON.stringify(session));
}

export function getLoginSession(): LoginSession | undefined {
  const raw = localStorage.getItem(SESSION_KEY);
  if (!raw) return undefined;
  try {
    const session = JSON.parse(raw) as LoginSession;
    if (
      !session.token ||
      (session.expireAt && new Date(session.expireAt).getTime() <= Date.now())
    ) {
      localStorage.removeItem(SESSION_KEY);
      return undefined;
    }
    return session;
  } catch {
    localStorage.removeItem(SESSION_KEY);
    return undefined;
  }
}

export function getAuthorization() {
  const session = getLoginSession();
  return session ? `${session.tokenType || 'Bearer'} ${session.token}` : undefined;
}

export function saveUserInfo(info: unknown, fallbackPermCodes: string[] = []) {
  const userInfo =
    info && typeof info === 'object' && !Array.isArray(info)
      ? (info as Record<string, unknown>)
      : {};
  const permCodes = Array.isArray(userInfo.permCodes)
    ? userInfo.permCodes.filter((code): code is string => typeof code === 'string')
    : fallbackPermCodes;
  localStorage.setItem(USER_INFO_KEY, JSON.stringify({ ...userInfo, permCodes }));
}

/** 获取本地用户信息,权限按钮以其中的 permCodes 为唯一依据。 */
export function getUserInfo(): Record<string, unknown> | undefined {
  const raw = localStorage.getItem(USER_INFO_KEY);
  if (!raw) return undefined;
  try {
    const userInfo = JSON.parse(raw);
    return userInfo && typeof userInfo === 'object' && !Array.isArray(userInfo)
      ? (userInfo as Record<string, unknown>)
      : undefined;
  } catch {
    localStorage.removeItem(USER_INFO_KEY);
    return undefined;
  }
}

export function getUserPermCodes(): string[] {
  const permCodes = getUserInfo()?.permCodes;
  return Array.isArray(permCodes)
    ? permCodes.filter((code): code is string => typeof code === 'string')
    : [];
}

export function clearLoginSession() {
  localStorage.removeItem(SESSION_KEY);
  localStorage.removeItem(USER_INFO_KEY);
}