auth-guard.ts 13.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
import i18n from '@/locale';
import { handleLocaleMap } from '@/locale/local-util';
import { Environment } from '@/environments/environment';
import { GlobalHelp } from '@ibiz/dynamic-model-api';
import { AppModelService, AppServiceBase, Http, setSessionStorage, getSessionStorage } from 'ibiz-core';
import { LogUtil } from 'ibiz-core';
import { AppCenterService, AppLoadingService, AppViewLogicService } from 'ibiz-vue';
import qs from 'qs';
import { getCookie, SyncSeriesHook } from 'qx-util';
import { AppComponentService } from '../service/app-component-service';

/**
 * AuthGuard net 对象
 * 调用 getInstance() 获取实例
 *
 * @class Http
 */
export class AuthGuard {

    /**
     * 执行钩子(包含获取租户前、获取租户后、获取应用数据前、获取应用数据后)
     *
     * @memberof AuthGuard
     */
    public static hooks = {
        dcSystemBefore: new SyncSeriesHook<[], { dcsystem: string }>(),
        dcSystemAfter: new SyncSeriesHook<[], { dcsystem: string, data: any }>(),
        appBefore: new SyncSeriesHook<[], { url: string, param: any }>(),
        appAfter: new SyncSeriesHook<[], { data: any }>()
    };

    /**
     * 获取 Auth 单例对象
     *
     * @static
     * @returns {Auth}
     * @memberof Auth
     */
    public static getInstance(): AuthGuard {
        if (!AuthGuard.auth) {
            AuthGuard.auth = new AuthGuard();
        }
        return this.auth;
    }

    /**
     * 单例变量声明
     *
     * @private
     * @static
     * @type {AuthGuard}
     * @memberof AuthGuard
     */
    private static auth: AuthGuard;

    /**
     * Creates an instance of AuthGuard.
     * 私有构造,拒绝通过 new 创建对象
     *
     * @memberof AuthGuard
     */
    private constructor() { }

    /**
     * 获取应用数据
     *
     * @param {string} url url 请求路径
     * @param {*} [params={}] 请求参数
     * @param {*} [router] 路由对象
     * @returns {Promise<any>} 请求相响应对象
     * @memberof AuthGuard
     */
    public authGuard(url: string, params: any = {}, router: any): any {
        return new Promise((resolve: any, reject: any) => {
            const appStore = router.app.$store;
            let appData: any = appStore?.getters.getAppData();
            getSessionStorage('activeOrgData')
            let activeOrgData = getSessionStorage('activeOrgData');
            if (appData && activeOrgData?.systemid) {
                return resolve(true);
            }
            if (Environment && Environment.SaaSMode) {
                this.getOrgsByDcsystem(router).then((result: boolean) => {
                    if (!result) {
                        reject(false);
                    }
                    this.getAppData(url, params, router).then((result: any) => {
                        result ? resolve(true) : reject(false);
                    });
                });
            } else {
                this.getAppData(url, params, router).then((result: any) => {
                    result ? resolve(true) : reject(false);
                });
            }
        });
    }

    /**
     * 通过租户获取组织数据
     * 
     * @memberof AuthGuard
     */
    public getOrgsByDcsystem(router: any): Promise<boolean> {
        return new Promise((resolve: any) => {
            let tempViewParam = this.hanldeViewParam(window.location.href);
            if (!tempViewParam.srfdcsystem) {
                if (!tempViewParam.redirect) {
                    if (getSessionStorage('dcsystem')) {
                        tempViewParam = getSessionStorage('dcsystem');
                    }
                } else {
                    tempViewParam = this.hanldeViewParam(tempViewParam.redirect);
                }
            }
            if (!tempViewParam.srfdcsystem && Environment.mockDcSystemId) {
                Object.assign(tempViewParam, { srfdcsystem: Environment.mockDcSystemId });
            }
            if (tempViewParam.srfdcsystem) {
                AuthGuard.hooks.dcSystemBefore.callSync({ dcsystem: tempViewParam.srfdcsystem });
                setSessionStorage('dcsystem', tempViewParam);
                let requestUrl: string = `/uaa/getbydcsystem/${tempViewParam.srfdcsystem}`;
                const get: Promise<any> = Http.getInstance().get(requestUrl);
                get.then((response: any) => {
                    if (response && response.status === 200) {
                        let { data }: { data: any } = response;
                        AuthGuard.hooks.dcSystemAfter.callSync({ dcsystem: tempViewParam.srfdcsystem, data: data });
                        if (data && data.length > 0) {
                            setSessionStorage('orgsData', data);
                            setSessionStorage('activeOrgData', data[0]);
                        }
                        resolve(true);
                    } else {
                        resolve(false);
                    }
                }).catch(() => {
                    resolve(false);
                    this.doNoLogin(router, "登录失败,请联系管理员");
                });
            } else {
                resolve(false);
                this.doNoLogin(router, "登录失败,请联系管理员");
            }
        });
    }

    /**
     * 获取应用数据
     *
     * @param {string} url url 请求路径
     * @param {*} [params={}] 请求参数
     * @param {*} [router] 路由对象
     * @returns {Promise<boolean>} 是否通过
     * @memberof AuthGuard
     */
    public getAppData(url: string, params: any = {}, router: any): Promise<boolean> {
        return new Promise((resolve: any, reject: any) => {
            AuthGuard.hooks.appBefore.callSync({ url: url, param: params });
            const get: Promise<any> = Http.getInstance().get(url);
            get.then((response: any) => {
                if (response && response.status === 200) {
                    let { data }: { data: any } = response;
                    AuthGuard.hooks.appAfter.callSync({ data: data });
                    if (data) {
                        // token认证把用户信息放入应用级数据
                        if (getCookie('ibzuaa-user')) {
                            let user: any = JSON.parse(getCookie('ibzuaa-user') as string);
                            let localAppData: any = {};
                            if (user.sessionParams) {
                                localAppData = { context: user.sessionParams };
                                Object.assign(localAppData, data);
                            }
                            data = JSON.parse(JSON.stringify(localAppData));
                        }
                        if (localStorage.getItem('localdata')) {
                            router.app.$store.commit(
                                'addLocalData',
                                JSON.parse(localStorage.getItem('localdata') as string),
                            );
                        }
                        router.app.$store.commit('addAppData', data);
                        // 提交统一资源数据
                        router.app.$store.dispatch('authresource/commitAuthData', data);
                    }
                }
                this.initAppService(router).then(() => {
                    resolve(true);
                });
            }).catch((error: any) => {
                this.initAppService(router).then(() => {
                    resolve(false);
                    console.error('获取应用数据出现异常');
                });
            });
        });
    }

    /**
     * 初始化应用服务
     *
     * @param {*} [router] 路由对象
     *
     * @memberof AuthGuard
     */
    public async initAppService(router: any) {
        const service = new AppModelService()
        AppServiceBase.getInstance().setAppEnvironment(Environment);
        if (!AppServiceBase.getInstance().getAppStore()) {
            AppServiceBase.getInstance().setAppStore(router.app.$store);
        }
        await GlobalHelp.install(service, async (strPath: string) => {
            let url: string = "";
            if (Environment.bDynamic) {
                url = `${Environment.remoteDynaPath}${strPath}`;
                const queryParam = {};
                const { dynamodeltag } = AppServiceBase.getInstance().getAppStore().getters.getAppData();
                if (dynamodeltag) {
                    Object.assign(queryParam, { dynamodeltag });
                }
                if (queryParam && Object.keys(queryParam).length > 0) {
                    url += `?${qs.stringify(queryParam)}`;
                }
            } else {
                url = `./assets/model${strPath}`;
            }
            try {
                const result: any = await Http.getInstance().get(url);
                return result.data ? result.data : null;
            } catch (error) {
                return null;
            }
        }, { lang: handleLocaleMap(i18n.locale) });
        await this.initAppStyle('PSSYSAPP.json.css');
        AppServiceBase.getInstance().setAppModelDataObject(service.app);
        AppServiceBase.getInstance().setI18n(i18n);
        AppCenterService.getInstance(router.app.$store);
        const appLoadingService = AppLoadingService.getInstance();
        AppServiceBase.getInstance().setLoadingService(appLoadingService);
        AppServiceBase.getInstance().setViewLogicService(AppViewLogicService.getInstance());
        AppServiceBase.getInstance().setAppComponentService(AppComponentService);
    }

    /**
     * 处理路径数据
     *
     * @param {*} [urlStr] 路径
     *
     * @memberof AuthGuard
     */
    public hanldeViewParam(urlStr: string) {
        let tempViewParam: any = {};
        const tempViewparam: any = urlStr.slice(urlStr.indexOf('?') + 1);
        const viewparamArray: Array<string> = decodeURIComponent(tempViewparam).split(';');
        if (viewparamArray.length > 0) {
            viewparamArray.forEach((item: any) => {
                Object.assign(tempViewParam, qs.parse(item));
            });
        }
        return tempViewParam;
    }
    
    /**
     * 处理未登录异常情况
     *
     * @memberof AuthGuard
     */
    public doNoLogin(router: any, message: string) {
        this.clearAppData(router.app.$store);
        const Environment = AppServiceBase.getInstance().getAppEnvironment();
        if (Environment.loginUrl) {
            window.location.href = `${Environment.loginUrl}?redirect=${window.location.href}`;
        } else {
            if (Object.is(router.currentRoute.name, 'login')) {
                return;
            }
            router.push({ name: 'login', query: { redirect: router.currentRoute.fullPath } });
        }
    }

    /**
     * 清除应用数据
     *
     * @private
     * @memberof AuthGuard
     */
    private clearAppData(store: any) {
        // 清除user、token
        let leftTime = new Date();
        leftTime.setTime(leftTime.getSeconds() - 1);
        document.cookie = "ibzuaa-token=;expires=" + leftTime.toUTCString();
        document.cookie = "ibzuaa-user=;expires=" + leftTime.toUTCString();
        // 清除应用级数据
        localStorage.removeItem('localdata')
        store.commit('addAppData', {});
        store.dispatch('authresource/commitAuthData', {});
    }

    /**
     * 初始化应用样式表
     * 
     * @param cssUrl 样式路径
     */
    public async initAppStyle(cssUrl: string) {
        const cssContent = await this.loadAppStyle(cssUrl);
        if(!cssContent){
            LogUtil.warn("暂无应用样式表");
            return;
        }
        this.mountedAppStyle(cssContent);
    }

    /**
     * 加载应用样式表
     * 
     * @param cssUrl 样式路径
     */
    public async loadAppStyle(cssUrl: string) {
        let url = '';
        if (Environment.bDynamic) {
            url = `${Environment.remoteDynaPath}/${cssUrl}`;
            const queryParam = {};
            const { dynamodeltag } = AppServiceBase.getInstance().getAppStore().getters.getAppData();
            if (dynamodeltag) {
                Object.assign(queryParam, { dynamodeltag });
            }
            if (queryParam && Object.keys(queryParam).length > 0) {
                url += `?${qs.stringify(queryParam)}`;
            }
        } else {
            const microAppService = AppServiceBase.getInstance().getMicroAppService();
            if (microAppService && microAppService.getIsMicroApp() && microAppService.getMicroAppFolder()) {
                url = `./${microAppService.getMicroAppFolder()}/assets/model/${cssUrl}`;
            } else {
                url = `./assets/model/${cssUrl}`;
            }
        }
        try {
            const result: any = await Http.getInstance().get(url);
            return result.data ? result.data : null;
        } catch (error) {
            return null;
        }
    }

    /**
     * 挂载应用样式表
     * 
     * @param cssContent 
     */
    public mountedAppStyle(cssContent:string){
        let appStyleDom:any;
        for (let i = document.head.childNodes.length - 1; i >= 0; i--) {
            const children: any = document.head.childNodes[i]
            if (children.nodeName == "STYLE" && children.getAttribute('title') && children.getAttribute('title') == 'app-style-css') {
                appStyleDom = children;
            }
        }
        if (appStyleDom) {
            appStyleDom.innerText = cssContent;
        } else {
            const styleDom = document.createElement('style');
            styleDom.type = "text/css";
            styleDom.setAttribute('title', 'app-style-css');
            styleDom.innerText = cssContent;
            document.head.appendChild(styleDom);
        }
    }
}