authRedirect.js 4.95 KB
import Taro from '@tarojs/taro'
import { routerStore } from '@/stores/router'
import request from '@/utils/request'

export const getCurrentPageFullPath = () => {
    const pages = getCurrentPages()
    if (!pages || pages.length === 0) return ''

    const current_page = pages[pages.length - 1]
    const route = current_page.route
    const options = current_page.options || {}

    const query_params = Object.keys(options)
        .map((key) => `${key}=${encodeURIComponent(options[key])}`)
        .join('&')

    return query_params ? `${route}?${query_params}` : route
}

export const saveCurrentPagePath = (custom_path) => {
    const router = routerStore()
    const path = custom_path || getCurrentPageFullPath()
    router.add(path)
}

export const needAuth = () => {
    try {
        const sessionid = Taro.getStorageSync('sessionid')
        return !sessionid || sessionid === ''
    } catch (error) {
        console.error('检查授权状态失败:', error)
        return true
    }
}

export const silentAuth = async (on_success, on_error) => {
    try {
        if (!needAuth()) {
            const result = { code: 1, msg: '已授权' }
            if (on_success) on_success(result)
            return result
        }

        Taro.showLoading({
            title: '加载中...',
            mask: true,
        })

        const login_result = await new Promise((resolve, reject) => {
            Taro.login({
                success: resolve,
                fail: reject,
            })
        })

        if (!login_result || !login_result.code) {
            throw new Error('获取微信登录code失败')
        }

        const response = await request.post('/srv/?a=openid', {
            code: login_result.code,
        })

        Taro.hideLoading()

        if (!response?.data || response.data.code !== 1) {
            const error_msg = response?.data?.msg || '授权失败'
            if (on_error) on_error(error_msg)
            throw new Error(error_msg)
        }

        let cookie =
            (response.cookies && response.cookies[0]) ||
            response.header?.['Set-Cookie'] ||
            response.header?.['set-cookie']

        if (Array.isArray(cookie)) cookie = cookie[0]

        if (!cookie) {
            const error_msg = '授权失败:没有获取到有效的会话信息'
            if (on_error) on_error(error_msg)
            throw new Error(error_msg)
        }

        Taro.setStorageSync('sessionid', cookie)

        if (request?.defaults?.headers) {
            request.defaults.headers.cookie = cookie
        }

        if (on_success) on_success(response.data)
        return response.data
    } catch (error) {
        Taro.hideLoading()
        const error_msg = error?.message || '授权失败,请稍后重试'
        if (on_error) on_error(error_msg)
        throw error
    }
}

export const navigateToAuth = (return_path) => {
    if (return_path) {
        saveCurrentPagePath(return_path)
    } else {
        saveCurrentPagePath()
    }

    Taro.navigateTo({
        url: '/pages/auth/index',
    })
}

export const returnToOriginalPage = async (default_path = '/pages/index/index') => {
    const router = routerStore()
    const saved_path = router.url

    try {
        router.remove()

        const pages = Taro.getCurrentPages()
        const current_page = pages[pages.length - 1]
        const current_route = current_page?.route

        let target_path = default_path
        if (saved_path && saved_path !== '') {
            target_path = saved_path.startsWith('/') ? saved_path : `/${saved_path}`
        }

        const target_route = target_path.split('?')[0].replace(/^\//, '')

        if (current_route === target_route) {
            return
        }

        try {
            await Taro.redirectTo({ url: target_path })
        } catch (error) {
            await Taro.reLaunch({ url: target_path })
        }
    } catch (error) {
        console.error('returnToOriginalPage 执行出错:', error)
        try {
            await Taro.reLaunch({ url: default_path })
        } catch (final_error) {
            console.error('最终降级方案也失败了:', final_error)
        }
    }
}

export const isFromShare = (options) => {
    return options && (options.from_share === '1' || options.scene)
}

export const handleSharePageAuth = async (options, callback) => {
    if (!needAuth()) {
        if (typeof callback === 'function') callback()
        return true
    }

    if (isFromShare(options)) {
        saveCurrentPagePath()
    }

    try {
        await silentAuth(
            () => {
                if (typeof callback === 'function') callback()
            },
            () => {
                Taro.navigateTo({ url: '/pages/auth/index' })
            }
        )
        return true
    } catch (error) {
        Taro.navigateTo({ url: '/pages/auth/index' })
        return false
    }
}

export const addShareFlag = (path) => {
    const separator = path.includes('?') ? '&' : '?'
    return `${path}${separator}from_share=1`
}