公众号解锁添加黄名单功能

This commit is contained in:
tangly1024
2025-01-19 16:40:14 +08:00
parent 9ba0fe1b3c
commit 5f3c1daeab

View File

@@ -22,8 +22,10 @@ const OpenWrite = () => {
)
// 验证一次后的有效时长,单位小时
const cookieAge = siteConfig('OPEN_WRITE_VALIDITY_DURATION', 1)
// 白名单
// 白名单,想要放行的页面
const whiteList = siteConfig('OPEN_WRITE_WHITE_LIST', '')
// 黄名单,优先级最高,设置后只有这里的路径会被上锁,其他页面自动全部放行
const yellowList = siteConfig('OPEN_WRITE_YELLOW_LIST', '')
// 登录信息
const { isLoaded, isSignedIn } = useGlobal()
@@ -71,30 +73,38 @@ const OpenWrite = () => {
}
}
useEffect(() => {
const existWhite = existedWhiteList(router.asPath, whiteList)
// 白名单中,免检
if (existWhite) {
const isInYellowList = isPathInList(router.asPath, yellowList)
const isInWhiteList = isPathInList(router.asPath, whiteList)
// 优先判断黄名单
if (yellowList && yellowList.length > 0) {
if (!isInYellowList) {
console.log('当前路径不在黄名单中,放行')
return
}
} else if (isInWhiteList) {
// 白名单中,免检
console.log('当前路径在白名单中,放行')
return
}
if (isSignedIn) {
// 用户已登录免检
console.log('用户已登录')
console.log('用户已登录,放行')
return
}
// 开发环境免检
if (process.env.NODE_ENV === 'development') {
// 开发环境免检
console.log('开发环境:屏蔽OpenWrite')
return
}
if (isBrowser && blogId && !isSignedIn) {
toggleTocItems(true) // 禁止目录项的点击
// Check if the element with id 'read-more-wrap' already exists
// 检查是否已加载
const readMoreWrap = document.getElementById('read-more-wrap')
// Only load the script if the element doesn't exist
if (!readMoreWrap) {
loadOpenWrite()
}
@@ -121,34 +131,27 @@ const toggleTocItems = disable => {
}
/**
* 检查名单
* 检查路径是否在名单
* @param {*} path 当前url的字符串
* @param {*} whiteListStr 名单字符串
* @param {*} listStr 名单字符串,逗号分隔
*/
function existedWhiteList(path, whiteListStr) {
// 参数检查
if (!path || !whiteListStr) {
return true
function isPathInList(path, listStr) {
if (!path || !listStr) {
return false
}
// 提取 path 最后一个斜杠后的内容,去掉前面的斜杆
// 移除查询参数(从 '?' 开始的部分)和 `.html` 后缀
// 提取 path 最后一个斜杠后的内容,并移除查询参数和 .html 后缀
const processedPath = path
.replace(/\?.*$/, '') // 移除查询参数
.replace(/.*\/([^/]+)(?:\.html)?$/, '$1') // 去掉前面的路径和 .html
.replace(/.*\/([^/]+)(?:\.html)?$/, '$1') // 提取最后部分
// 严格检查白名单字符串中是否包含处理后的 path
// const whiteListArray = whiteListStr.split(',')
// return whiteListArray.includes(processedPath)
const isInList = listStr.includes(processedPath)
// 放宽判断
const isWhite = whiteListStr.includes(processedPath)
if (isWhite) {
console.log('OpenWrite白名单', processedPath)
if (isInList) {
// console.log(`当前路径在名单中: ${processedPath}`)
}
return isWhite
return isInList
}
export default OpenWrite