auth.js 4.19 KB
/*
文件名: app/static/js/auth.js
职责: 全局认证状态管理:校验登录、显示用户信息、自动处理 401、退出登录。
注意: 不要删除这个注释。
*/

(function() {
    // 拦截全局 fetch,自动携带 Cookie 并处理 401
    const originalFetch = window.fetch;
    window.fetch = async function(...args) {
        const options = args[1] || {};
        options.credentials = 'include';
        args[1] = options;
        try {
            const response = await originalFetch.apply(this, args);
            if (response.status === 401 && !window.location.pathname.includes('/login')) {
                var loginRoot = window.APP_ROOT || window.resolveAppRoot?.() || '';
                window.location.href = loginRoot + '/login';
            }
            return response;
        } catch (err) {
            throw err;
        }
    };

    // API 基础路径:统一解析,兼容 /daw/harmony 等嵌套路由部署
    (function() {
        var PAGE_SUFFIXES = [
            '/harmony/sub-brand', '/strategy/detail', '/strategy/info',
            '/harmony', '/analysis', '/strategy', '/ods', '/dw', '/login',
        ];
        var p = window.location.pathname.replace(/\/$/, '');
        var root = (!p || p === '/') ? '' : p;
        for (var i = 0; i < PAGE_SUFFIXES.length; i++) {
            if (root.endsWith(PAGE_SUFFIXES[i])) {
                root = root.slice(0, -PAGE_SUFFIXES[i].length) || '';
                break;
            }
        }
        window.resolveAppRoot = function(pathname) {
            var path = (pathname || window.location.pathname || '').replace(/\/$/, '');
            if (!path || path === '/') return '';
            for (var j = 0; j < PAGE_SUFFIXES.length; j++) {
                if (path.endsWith(PAGE_SUFFIXES[j])) {
                    return path.slice(0, -PAGE_SUFFIXES[j].length) || '';
                }
            }
            return path;
        };
        window.APP_ROOT = root;
        window.API_BASE = root + '/api';
        window.STATIC_BASE = root + '/static';
    })();

    // 登录页不执行后续逻辑
    if (window.location.pathname.includes('/login')) {
        return;
    }

    // 获取当前用户信息
    async function loadCurrentUser() {
        try {
            const res = await fetch(window.API_BASE + '/auth/me', { credentials: 'include' });
            if (res.status === 401) {
                var loginRoot = window.APP_ROOT || window.resolveAppRoot?.() || '';
                window.location.href = loginRoot + '/login';
                return;
            }
            if (!res.ok) {
                console.error('获取用户信息失败:', res.status);
                return;
            }
            const user = await res.json();
            renderUserInfo(user.username);
        } catch (err) {
            console.error('加载用户信息失败:', err);
        }
    }

    // 渲染右上角用户信息
    function renderUserInfo(username) {
        const userInfo = document.getElementById('user-info') || document.querySelector('.user-info');
        if (!userInfo) return;
        userInfo.innerHTML = '';
        const nameSpan = document.createElement('span');
        nameSpan.textContent = username || '管理员';
        nameSpan.style.marginRight = '10px';
        const logoutLink = document.createElement('a');
        logoutLink.href = '#';
        logoutLink.textContent = '退出';
        logoutLink.style.color = '#ff6b6b';
        logoutLink.style.textDecoration = 'none';
        logoutLink.style.fontSize = '13px';
        logoutLink.addEventListener('click', async (e) => {
            e.preventDefault();
            try {
                await fetch(window.API_BASE + '/auth/logout', { method: 'POST', credentials: 'include' });
            } catch (err) {
                console.error('退出请求失败:', err);
            }
            window.location.href = (window.APP_ROOT || window.resolveAppRoot?.() || '') + '/login';
        });
        userInfo.appendChild(nameSpan);
        userInfo.appendChild(logoutLink);
    }

    document.addEventListener('DOMContentLoaded', loadCurrentUser);
})();