auth-web/src/utils/sso.ts

75 lines
2.3 KiB
TypeScript
Raw Normal View History

import { type DataInfo, removeToken, setToken } from './auth';
import { getQueryMap, subBefore } from '@pureadmin/utils';
2024-09-26 09:38:02 +08:00
/**
* http://localhost:8848/#/permission/page/index?username=sso&roles=admin&accessToken=eyJhbGciOiJIUzUxMiJ9.admin
*
*
* 1.
* 2.url中的重要参数信息 setToken
* 3. url
* 4.使 window.location.replace
*/
(function () {
// 获取 url 中的参数
const params = getQueryMap(location.href) as DataInfo<Date>;
const must = ['username', 'roles', 'accessToken'];
const mustLength = must.length;
if (Object.keys(params).length !== mustLength) return;
// url 参数满足 must 里的全部值,才判定为单点登录,避免非单点登录时刷新页面无限循环
let sso = [];
let start = 0;
while (start < mustLength) {
if (Object.keys(params).includes(must[start]) && sso.length <= mustLength) {
sso.push(must[start]);
} else {
sso = [];
}
start++;
}
if (sso.length === mustLength) {
// 判定为单点登录
// 清空本地旧信息
removeToken();
// 保存新信息到本地
setToken(params);
// 删除不需要显示在 url 的参数
delete params.roles;
delete params.accessToken;
const newUrl = `${location.origin}${location.pathname}${subBefore(location.hash, '?')}?${JSON.stringify(params).replace(/["{}]/g, '').replace(/:/g, '=').replace(/,/g, '&')}`;
// 替换历史记录项
window.location.replace(newUrl);
} else {
return;
}
2024-09-26 09:38:02 +08:00
})();
/**
*
* @param blob
* @param filename
*/
export function download(blob: any, filename: string) {
// 创建一个临时的 URL用于下载文件
const a = document.createElement('a');
const url = window.URL.createObjectURL(new Blob([blob]));
a.href = url;
// 创建一个<a>元素,设置其 download 属性和 href 属性,模拟点击下载
a.download = filename;
document.body.appendChild(a);
a.click();
// 清理创建的临时元素和 URL
URL.revokeObjectURL(url);
document.body.removeChild(a);
}