djAuth.ts 4.81 KB
import { KJUR } from 'jsrsasign';
import type { AxiosAdapter } from 'axios';
import { createRopClient } from './index';
import { loadDjLoginConfig, type DjLoginConfig } from './djConfig';

/** 与当前项目的 uj_token / session 分开保存,避免两个系统相互覆盖。 */
export const DJ_SESSION_STORAGE_KEY = 'uj_dj_session';
export const DJ_ACCOUNT_STORAGE_KEY = 'uj_dj_account';

interface DjAccountOption {
  sessionId?: string;
  loginAccout?: string;
  loginAccount?: string;
  merchantNo?: string | number;
}

interface DjLoginData extends Record<string, unknown> {
  sessionId?: string;
  loginToken?: string;
  accountList?: DjAccountOption[];
}

interface DjSelectionData {
  sessionId?: string;
}

export interface DjLoginServiceConfig extends DjLoginConfig {
  adapter?: AxiosAdapter;
}

export interface DjLoginSession {
  sessionId: string;
  account: Record<string, unknown>;
}

function setLocal(key: string, value: string): void {
  try {
    localStorage.setItem(key, value);
  } catch {
    // 隐私模式等无法写入本地存储时,不影响当前页面继续使用会话。
  }
}

function getLocal(key: string): string | null {
  try {
    return localStorage.getItem(key);
  } catch {
    return null;
  }
}

function removeLocal(key: string): void {
  try {
    localStorage.removeItem(key);
  } catch {
    /* ignore */
  }
}

export function getDjSessionId(): string | null {
  return getLocal(DJ_SESSION_STORAGE_KEY);
}

export function getDjAccount(): Record<string, unknown> | null {
  const raw = getLocal(DJ_ACCOUNT_STORAGE_KEY);
  if (!raw) return null;
  try {
    const value: unknown = JSON.parse(raw);
    return value && typeof value === 'object' && !Array.isArray(value)
      ? (value as Record<string, unknown>)
      : null;
  } catch {
    return null;
  }
}

export function clearDjLoginStorage(): void {
  removeLocal(DJ_SESSION_STORAGE_KEY);
  removeLocal(DJ_ACCOUNT_STORAGE_KEY);
}

function hashPassword(password: string): string {
  return KJUR.crypto.Util.hashString(password, 'md5').toLowerCase();
}

function assertRopConfig(config: DjLoginServiceConfig): void {
  if (!config.appKey || !config.secret) {
    throw new Error('嘀加登录缺少应用标识或签名配置,请检查配置中心返回内容');
  }
}

function extractSessionId(data: DjLoginData): string | undefined {
  return data.sessionId || data.accountList?.[0]?.sessionId;
}

/**
 * 创建嘀加登录服务。登录账号固定由独立环境配置读取,不使用当前项目登录表单的账号密码。
 */
export function createDjLoginService(config: DjLoginServiceConfig) {
  const clientConfig = {
    baseURL: config.baseURL,
    appKey: config.appKey,
    secret: config.secret,
    adapter: config.adapter,
  };

  async function login(): Promise<DjLoginSession> {
    assertRopConfig(config);
    const loginClient = createRopClient(clientConfig);
    const loginData = await loginClient.post<DjLoginData>({
      method: 'dj.api.user.login',
      userName: config.account,
      password: hashPassword(config.password),
    });

    let sessionId = extractSessionId(loginData);
    if (!sessionId && loginData.accountList?.length) {
      const selected = loginData.accountList[0];
      const loginAccount = selected.loginAccout ?? selected.loginAccount;
      const merchantId = Number(selected.merchantNo);
      if (!loginData.loginToken || !loginAccount || !Number.isFinite(merchantId)) {
        throw new Error('嘀加登录返回了多个商户,但缺少选择商户所需信息');
      }
      const selectedData = await loginClient.post<DjSelectionData>({
        method: 'dj.api.user.login.select',
        loginAccount,
        merchantId,
        loginToken: loginData.loginToken,
      });
      sessionId = selectedData.sessionId;
    }
    if (!sessionId) throw new Error('嘀加登录成功但未返回会话信息');

    const sessionClient = createRopClient({
      ...clientConfig,
      getSessionId: () => sessionId,
    });
    const userInfo = await sessionClient.post<Record<string, unknown>>({
      method: 'dj.api.user.info',
    });
    const account = { ...loginData, userInfo };
    setLocal(DJ_SESSION_STORAGE_KEY, sessionId);
    setLocal(DJ_ACCOUNT_STORAGE_KEY, JSON.stringify(account));
    return { sessionId, account };
  }

  return { login };
}

let runtimeConfig: Promise<DjLoginServiceConfig> | null = null;

async function getRuntimeConfig(): Promise<DjLoginServiceConfig> {
  if (!runtimeConfig) runtimeConfig = loadDjLoginConfig();
  try {
    return await runtimeConfig;
  } catch (error) {
    // 网络短暂失败后允许下一次登录重新拉取配置。
    runtimeConfig = null;
    throw error;
  }
}

/** 当前 React 登录页使用的默认嘀加登录服务。 */
export const djLogin = {
  async login(): Promise<DjLoginSession> {
    return createDjLoginService(await getRuntimeConfig()).login();
  },
};