登录1
This commit is contained in:
@@ -0,0 +1,186 @@
|
||||
import { JSEncrypt } from 'jsencrypt';
|
||||
|
||||
/**
|
||||
* 鼎捷云 IAM 登录服务(纯前端实现)
|
||||
*
|
||||
* 加密流程(RSA + AES):
|
||||
* 1. 客户端生成 RSA 密钥对
|
||||
* 2. GET /api/iam/v2/identity/publickey 获取服务端公钥
|
||||
* 3. 用服务端公钥加密客户端公钥 → clientEncryptPublicKey
|
||||
* 4. POST /api/iam/v2/identity/aeskey 获取被加密的 AES 密钥
|
||||
* 5. 用客户端私钥解密得到 aesKey(16 位)
|
||||
* 6. AES-CBC 加密密码 → passwordHash
|
||||
* 7. POST /api/iam/v2/identity/login 获取 userToken
|
||||
*/
|
||||
|
||||
// 代理路径(vite.config.ts 中 /iam-api → https://iam.digiwincloud.com.cn)
|
||||
const IAM_BASE = '/iam-api/api/iam/v2/identity';
|
||||
|
||||
// 应用 apptoken(digi-middleware-auth-app)
|
||||
export const APP_TOKEN =
|
||||
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6ImRhdGEtYnVzaW5lc3MtZGVtbyIsInNpZCI6MH0.Spo64LstbWxjYNefVFAbEbgfjzZoQGNcqKSGuYUOCRk';
|
||||
|
||||
// IAM AES 加密固定 IV(16 字节)
|
||||
const AES_IV = 'ghUb#er57HBh(u%g';
|
||||
|
||||
/** PEM 包装/剥离工具 */
|
||||
function wrapPem(base64Key: string): string {
|
||||
if (base64Key.includes('BEGIN')) return base64Key;
|
||||
const body = base64Key.replace(/-----(BEGIN|END)[^-]+-----/g, '').replace(/\s+/g, '');
|
||||
const lines = body.match(/.{1,64}/g) || [];
|
||||
return `-----BEGIN PUBLIC KEY-----\n${lines.join('\n')}\n-----END PUBLIC KEY-----`;
|
||||
}
|
||||
|
||||
function stripPem(pem: string): string {
|
||||
return pem.replace(/-----(BEGIN|END)[^-]+-----/g, '').replace(/\s+/g, '');
|
||||
}
|
||||
|
||||
/** AES-CBC/PKCS7 加密,输出 base64(与 Java AES/CBC/PKCS5Padding 等价) */
|
||||
async function aesEncryptToBase64(plainText: string, aesKey: string): Promise<string> {
|
||||
const enc = new TextEncoder();
|
||||
const keyData = enc.encode(aesKey);
|
||||
const ivData = enc.encode(AES_IV);
|
||||
const cryptoKey = await crypto.subtle.importKey('raw', keyData, { name: 'AES-CBC' }, false, ['encrypt']);
|
||||
const cipherBuf = await crypto.subtle.encrypt({ name: 'AES-CBC', iv: ivData }, cryptoKey, enc.encode(plainText));
|
||||
const bytes = new Uint8Array(cipherBuf);
|
||||
let bin = '';
|
||||
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
|
||||
return btoa(bin);
|
||||
}
|
||||
|
||||
/** 通用请求头 */
|
||||
function iamHeaders(extra?: Record<string, string>): Record<string, string> {
|
||||
return {
|
||||
'Content-Type': 'application/json',
|
||||
'digi-middleware-auth-app': APP_TOKEN,
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
export interface IamLoginParams {
|
||||
userId: string;
|
||||
password: string;
|
||||
tenantId?: string;
|
||||
}
|
||||
|
||||
export interface IamLoginResult {
|
||||
token: string;
|
||||
userId: string;
|
||||
tenantId: string;
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* IAM 普通登录(identityType: query)
|
||||
* 支持用户 id / 手机号 / 邮箱
|
||||
*/
|
||||
export async function iamLogin({ userId, password, tenantId }: IamLoginParams): Promise<IamLoginResult> {
|
||||
// 1. 客户端生成 RSA 密钥对(1024)
|
||||
const client = new JSEncrypt({ default_key_size: '1024' });
|
||||
client.getKey();
|
||||
const clientPrivateKeyPem = client.getPrivateKey();
|
||||
const clientPublicKeyB64 = stripPem(client.getPublicKey());
|
||||
|
||||
// 2. 获取服务端公钥
|
||||
const pkRes = await fetch(`${IAM_BASE}/publickey`, { headers: iamHeaders() });
|
||||
if (!pkRes.ok) throw new Error(`获取服务端公钥失败 (HTTP ${pkRes.status})`);
|
||||
const pkJson = await pkRes.json();
|
||||
const serverPublicKey: string = pkJson.publicKey;
|
||||
if (!serverPublicKey) throw new Error('服务端公钥为空');
|
||||
|
||||
// 3. 服务端公钥加密客户端公钥
|
||||
const server = new JSEncrypt();
|
||||
server.setPublicKey(wrapPem(serverPublicKey));
|
||||
const clientEncryptPublicKey = server.encrypt(clientPublicKeyB64);
|
||||
if (!clientEncryptPublicKey) throw new Error('加密客户端公钥失败');
|
||||
|
||||
// 4. 获取加密的 AES 密钥
|
||||
const aesRes = await fetch(`${IAM_BASE}/aeskey`, {
|
||||
method: 'POST',
|
||||
headers: iamHeaders(),
|
||||
body: JSON.stringify({ clientEncryptPublicKey }),
|
||||
});
|
||||
if (!aesRes.ok) throw new Error(`获取 AES 密钥失败 (HTTP ${aesRes.status})`);
|
||||
const aesJson = await aesRes.json();
|
||||
const encryptAesKey: string = aesJson.encryptAesKey;
|
||||
if (!encryptAesKey) throw new Error(`获取 AES 密钥失败: ${JSON.stringify(aesJson)}`);
|
||||
|
||||
// 5. 客户端私钥解密 AES 密钥
|
||||
client.setPrivateKey(clientPrivateKeyPem);
|
||||
const aesKey = client.decrypt(encryptAesKey);
|
||||
if (!aesKey) throw new Error('解密 AES 密钥失败');
|
||||
|
||||
// 6. AES 加密密码
|
||||
const passwordHash = await aesEncryptToBase64(password, aesKey);
|
||||
|
||||
// 7. 登录
|
||||
const body: Record<string, string> = {
|
||||
userId,
|
||||
passwordHash,
|
||||
clientEncryptPublicKey,
|
||||
identityType: 'query',
|
||||
};
|
||||
if (tenantId) body.tenantId = tenantId;
|
||||
|
||||
const loginRes = await fetch(`${IAM_BASE}/login`, {
|
||||
method: 'POST',
|
||||
headers: iamHeaders(),
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const loginJson = await loginRes.json().catch(() => ({}));
|
||||
|
||||
const token: string | undefined = loginJson.token ?? loginJson.data?.token ?? loginJson.userToken;
|
||||
if (!loginRes.ok || !token) {
|
||||
const msg = loginJson.message || loginJson.msg || loginJson.error || `HTTP ${loginRes.status}`;
|
||||
throw new Error(`登录失败: ${msg}`);
|
||||
}
|
||||
|
||||
return {
|
||||
token,
|
||||
userId,
|
||||
tenantId: loginJson.tenantId ?? tenantId ?? '',
|
||||
raw: loginJson,
|
||||
};
|
||||
}
|
||||
|
||||
/* ---------------- sessionStorage 会话管理 ---------------- */
|
||||
|
||||
const KEY_USER_TOKEN = 'userToken';
|
||||
const KEY_USER_INFO = 'userInfo';
|
||||
const KEY_APP_TOKEN = 'digi-middleware-auth-app';
|
||||
|
||||
export interface SessionUserInfo {
|
||||
userId: string;
|
||||
tenantId: string;
|
||||
loginTime: string;
|
||||
}
|
||||
|
||||
/** 保存登录会话 */
|
||||
export function saveSession(token: string, info: SessionUserInfo): void {
|
||||
sessionStorage.setItem(KEY_USER_TOKEN, token);
|
||||
sessionStorage.setItem(KEY_USER_INFO, JSON.stringify(info));
|
||||
sessionStorage.setItem(KEY_APP_TOKEN, APP_TOKEN);
|
||||
}
|
||||
|
||||
/** 获取当前 userToken */
|
||||
export function getUserToken(): string | null {
|
||||
return sessionStorage.getItem(KEY_USER_TOKEN);
|
||||
}
|
||||
|
||||
/** 获取当前用户信息 */
|
||||
export function getUserInfo(): SessionUserInfo | null {
|
||||
const raw = sessionStorage.getItem(KEY_USER_INFO);
|
||||
if (!raw) return null;
|
||||
try {
|
||||
return JSON.parse(raw) as SessionUserInfo;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 退出登录,清空会话 */
|
||||
export function clearSession(): void {
|
||||
sessionStorage.removeItem(KEY_USER_TOKEN);
|
||||
sessionStorage.removeItem(KEY_USER_INFO);
|
||||
sessionStorage.removeItem(KEY_APP_TOKEN);
|
||||
}
|
||||
Reference in New Issue
Block a user