This commit is contained in:
parent
5fe4b5fda3
commit
c6830b4fe6
|
@ -38,10 +38,6 @@ app.layout = lambda: fuc.FefferyTopProgress(
|
|||
dcc.Store(id='global-url-init-load'),
|
||||
# 应用根容器
|
||||
html.Div(id='root-container'),
|
||||
# 全局永久cookie登录令牌组件
|
||||
fuc.FefferyCookie(id='global-cookie-authorization-permanent', cookieKey='global-cookie-authorization-permanent', secure=True, expires=3600 * 24 * 365),
|
||||
# 全局会话cookie登录令牌组件
|
||||
fuc.FefferyCookie(id='global-cookie-authorization-session', cookieKey='global-cookie-authorization-session', secure=True),
|
||||
],
|
||||
listenPropsMode='include',
|
||||
includeProps=['root-container.children'],
|
||||
|
|
|
@ -9,41 +9,37 @@ console.error = function (...args) {
|
|||
}
|
||||
};
|
||||
|
||||
function getCookie(name) {
|
||||
const cookies = document.cookie.split(';');
|
||||
for (const cookie of cookies) {
|
||||
const [cookieName, cookieValue] = cookie.trim().split('=');
|
||||
if (cookieName === name) {
|
||||
return decodeURIComponent(cookieValue); // 解码特殊字符(如空格、中文)
|
||||
}
|
||||
}
|
||||
return null; // 未找到返回 null
|
||||
}
|
||||
// function getCookie(name) {
|
||||
// const cookies = document.cookie.split(';');
|
||||
// for (const cookie of cookies) {
|
||||
// const [cookieName, cookieValue] = cookie.trim().split('=');
|
||||
// if (cookieName === name) {
|
||||
// return decodeURIComponent(cookieValue); // 解码特殊字符(如空格、中文)
|
||||
// }
|
||||
// }
|
||||
// return null; // 未找到返回 null
|
||||
// }
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const originalFetch = window.fetch;
|
||||
window.fetch = function(url, config) {
|
||||
// if (url.includes('/_dash-update-component')) {
|
||||
config = config || {};
|
||||
let authToken = null;
|
||||
// 检查永久授权 cookie
|
||||
authToken = getCookie("global-cookie-authorization-permanent");
|
||||
// 如果永久授权 cookie 不存在,检查会话授权 cookie
|
||||
if (authToken == null || authToken == '' || authToken == '""') {
|
||||
authToken = getCookie("global-cookie-authorization-session");
|
||||
}
|
||||
// 如果存在 Token,添加 Header
|
||||
if (authToken !== null && authToken !== '' && authToken != '""') {
|
||||
authToken = authToken.replace(/"/g, '')
|
||||
if (!authToken.startsWith('Bearer ')) {
|
||||
authToken = 'Bearer ' + authToken;
|
||||
}
|
||||
config.headers = {
|
||||
...(config.headers || {}),
|
||||
Authorization: authToken // 添加 Authorization
|
||||
};
|
||||
}
|
||||
// }
|
||||
return originalFetch(url, config);
|
||||
};
|
||||
});
|
||||
// document.addEventListener('DOMContentLoaded', function() {
|
||||
// const originalFetch = window.fetch;
|
||||
// window.fetch = function(url, config) {
|
||||
// // if (url.includes('/_dash-update-component')) {
|
||||
// config = config || {};
|
||||
// let authToken = null;
|
||||
// // 检查授权 cookie
|
||||
// authToken = getCookie("access_token");
|
||||
// // 如果存在 Token,添加 Header
|
||||
// if (authToken !== null && authToken !== '' && authToken != '""') {
|
||||
// authToken = authToken.replace(/"/g, '')
|
||||
// if (!authToken.startsWith('Bearer ')) {
|
||||
// authToken = 'Bearer ' + authToken;
|
||||
// }
|
||||
// config.headers = {
|
||||
// ...(config.headers || {}),
|
||||
// Authorization: authToken // 添加 Authorization
|
||||
// };
|
||||
// }
|
||||
// // }
|
||||
// return originalFetch(url, config);
|
||||
// };
|
||||
// });
|
|
@ -3,6 +3,7 @@ from typing import Dict, Union, Optional
|
|||
from datetime import timedelta, datetime, timezone
|
||||
import jwt
|
||||
from dash import set_props
|
||||
import dash
|
||||
from enum import Enum
|
||||
from flask import request
|
||||
|
||||
|
@ -81,12 +82,7 @@ def jwt_encode_save_access_to_session(data: Dict, expires_delta: Optional[timede
|
|||
- NoReturn, 该函数不返回任何值。
|
||||
"""
|
||||
access_token = jwt_encode(data, expires_delta=expires_delta)
|
||||
if session_permanent:
|
||||
set_props('global-cookie-authorization-permanent', {'value': f'Bearer {access_token}'})
|
||||
set_props('global-cookie-authorization-session', {'value': '""'})
|
||||
else:
|
||||
set_props('global-cookie-authorization-permanent', {'value': '""'})
|
||||
set_props('global-cookie-authorization-session', {'value': f'Bearer {access_token}'})
|
||||
dash.ctx.response.set_cookie('access_token', f'Bearer {access_token}', max_age=3600 * 24 * 365 if session_permanent else None)
|
||||
|
||||
|
||||
def jwt_decode_from_session(verify_exp: bool = True) -> Union[Dict, AccessFailType]:
|
||||
|
@ -132,5 +128,4 @@ def clear_access_token_from_session() -> None:
|
|||
返回:
|
||||
- None, 该函数不返回任何值。
|
||||
"""
|
||||
set_props('global-cookie-authorization-permanent', {'value': '""'})
|
||||
set_props('global-cookie-authorization-session', {'value': '""'})
|
||||
dash.ctx.response.set_cookie('access_token', '', expires=0)
|
||||
|
|
|
@ -6,7 +6,7 @@ from common.utilities.util_logger import Log
|
|||
from common.exception import global_exception_handler
|
||||
from common.utilities.util_dash import CustomDash
|
||||
from common.constant import HttpStatusConstant
|
||||
from datetime import datetime, timedelta,timezone
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from i18n import t__other
|
||||
|
||||
|
||||
|
@ -20,6 +20,18 @@ app = CustomDash(
|
|||
update_title=None,
|
||||
serve_locally=CommonConf.DASH_SERVE_LOCALLY,
|
||||
extra_hot_reload_paths=[],
|
||||
hooks={
|
||||
'request_pre': """
|
||||
(payload) => {
|
||||
// 尝试获取键名为access_token的cookie,用于生成请求头令牌
|
||||
let access_token = document.cookie.match(/access_token=([^;]+)/)
|
||||
// 为来自dash的请求添加请求头
|
||||
if (access_token){
|
||||
store.getState().config.fetch.headers['Authorization'] = access_token[1].replace(/"/g, '')
|
||||
}
|
||||
}
|
||||
"""
|
||||
},
|
||||
on_error=global_exception_handler,
|
||||
)
|
||||
app.server.config['COMPRESS_ALGORITHM'] = FlaskConf.COMPRESS_ALGORITHM
|
||||
|
@ -230,7 +242,7 @@ def userinfo():
|
|||
|
||||
token = current_token()
|
||||
user_name = jwt_decode(token.token)['user_name']
|
||||
if user_name != token.user_name: # 不改数据库不可能发生
|
||||
if user_name != token.user_name: # 不改数据库不可能发生
|
||||
abort(HttpStatusConstant.ERROR)
|
||||
user = get_user_info(user_names=[token.user_name])[0]
|
||||
access_metas = MenuAccess(token.user_name).all_access_metas
|
||||
|
|
Loading…
Reference in New Issue