Files
admin-portal/src/api/auth.ts
T
Pine fc1841dfe6 refactor(auth): 管理端清除多身份残留(identities/currentIdentity/selectIdentity/Identity)
- auth.tsx/type 去 identities/currentIdentity 状态与 Identity 类型,role 恒取 user.role
- api/auth.ts 删 selectIdentity、getSavedUser/saveUser 去 identity 字段
- types.ts LoginResponse 去 identities/identity_id/port/identity_name 字段

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-26 19:16:14 +08:00

71 lines
2.8 KiB
TypeScript

import { api, setToken } from "@/api/client";
import type { LoginResponse } from "@/types";
export async function login(username: string, password: string): Promise<LoginResponse> {
const res = await api.post<LoginResponse>("/auth/login", { username, password });
setToken(res.token);
return res;
}
// ---- 四种登录:短信验证码 / 微信扫码 / 小程序扫码 ----
export async function sendCode(phone: string): Promise<{ sent: boolean; message: string; stub_code?: string }> {
return api.post("/auth/send-code", { phone });
}
export async function phoneLogin(phone: string, code: string): Promise<LoginResponse> {
const res = await api.post<LoginResponse>("/auth/phone-login", { phone, code });
setToken(res.token);
return res;
}
/** 绑定手机号(验证码;若手机号已被占用则后端按手机号合并,返回新令牌需切换) */
export async function bindPhone(phone: string, code: string): Promise<LoginResponse> {
const res = await api.post<LoginResponse>("/auth/bind-phone", { phone, code });
setToken(res.token); // 可能合并成另一个账号,必须切换到新令牌
return res;
}
/** 解绑登录方式:phone | wx | wx_mini(至少保留一种) */
export async function unbind(type: "phone" | "wx" | "wx_mini") {
return api.post("/auth/unbind", { type });
}
export async function wxQrStart(): Promise<{ scene: string; qr_url: string; redirect_uri: string; stub: boolean }> {
return api.get("/auth/wx-qr/start");
}
export async function wxQrPoll(scene: string): Promise<{ status: string; token?: string; profile?: LoginResponse }> {
return api.get(`/auth/wx-qr/poll?scene=${encodeURIComponent(scene)}`);
}
export async function mpQrStart(): Promise<{ scene: string; qr_url: string; mp_enabled: boolean }> {
return api.get("/auth/mp-qr/start");
}
export async function mpQrPoll(scene: string): Promise<{ status: string; token?: string; profile?: LoginResponse; message?: string }> {
return api.get(`/auth/mp-qr/poll?scene=${encodeURIComponent(scene)}`);
}
/** 发起「绑定小程序」:返回小程序码(微信扫码自动打开小程序确认),绑定到当前账号 */
export async function bindMpStart(): Promise<{ scene: string; qr_image?: string; qr_url?: string; mp_enabled: boolean }> {
return api.get("/auth/mp-qr/bind-start");
}
export async function fetchMe(): Promise<Record<string, unknown>> {
return api.get("/auth/me");
}
export function getSavedUser(): { username?: string; role?: string } | null {
try {
return JSON.parse(localStorage.getItem("@cloud-opc-admin/user") || "null");
} catch {
return null;
}
}
export function saveUser(user: { username?: string; role?: string } | null) {
if (user) localStorage.setItem("@cloud-opc-admin/user", JSON.stringify(user));
else localStorage.removeItem("@cloud-opc-admin/user");
}