Skip to content

Commit

Permalink
公众号解锁添加黄名单功能
Browse files Browse the repository at this point in the history
  • Loading branch information
tangly1024 committed Jan 19, 2025
1 parent 9ba0fe1 commit 5f3c1da
Showing 1 changed file with 33 additions and 30 deletions.
63 changes: 33 additions & 30 deletions components/OpenWrite.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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()
}
Expand All @@ -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

// 严格检查白名单字符串中是否包含处理后的 path
// const whiteListArray = whiteListStr.split(',')
// return whiteListArray.includes(processedPath)
.replace(/.*\/([^/]+)(?:\.html)?$/, '$1') // 提取最后部分

// 放宽判断
const isWhite = whiteListStr.includes(processedPath)
const isInList = listStr.includes(processedPath)

if (isWhite) {
console.log('OpenWrite白名单', processedPath)
if (isInList) {
// console.log(`当前路径在名单中: ${processedPath}`)
}

return isWhite
return isInList
}

export default OpenWrite

0 comments on commit 5f3c1da

Please sign in to comment.