feat: auth
This commit is contained in:
51
src/components/Auth/index.tsx
Normal file
51
src/components/Auth/index.tsx
Normal file
@@ -0,0 +1,51 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import Taro, { useDidShow } from '@tarojs/taro'
|
||||
import { View } from '@tarojs/components'
|
||||
import { check_login_status } from '@/services/loginService'
|
||||
|
||||
|
||||
|
||||
export function getCurrentFullPath(): string {
|
||||
const pages = Taro.getCurrentPages()
|
||||
const currentPage = pages.at(-1)
|
||||
|
||||
if (currentPage) {
|
||||
const route = currentPage.route
|
||||
const options = currentPage.options || {}
|
||||
|
||||
const query = Object.keys(options)
|
||||
.map(key => `${key}=${options[key]}`)
|
||||
.join('&')
|
||||
|
||||
return query ? `/${route}?${query}` : `/${route}`
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
export default function withAuth<P extends object>(WrappedComponent: React.ComponentType<P>) {
|
||||
const ComponentWithAuth: React.FC<P> = (props: P) => {
|
||||
const [authed, setAuthed] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
const is_login = check_login_status()
|
||||
setAuthed(is_login)
|
||||
|
||||
if (!is_login) {
|
||||
const currentPage = getCurrentFullPath()
|
||||
Taro.redirectTo({
|
||||
url: `/pages/login/index/index${
|
||||
currentPage ? `?redirect=${currentPage}` : ''
|
||||
}`,
|
||||
})
|
||||
}
|
||||
}, [])
|
||||
|
||||
if (!authed) {
|
||||
return <View /> // 空壳,避免 children 渲染出错
|
||||
}
|
||||
|
||||
return <WrappedComponent {...props} />
|
||||
}
|
||||
|
||||
return ComponentWithAuth
|
||||
}
|
||||
@@ -15,15 +15,16 @@ import CommonDialog from './CommonDialog'
|
||||
import PublishMenu from './PublishMenu/PublishMenu'
|
||||
import UploadCover from './UploadCover'
|
||||
import EditModal from './EditModal/index'
|
||||
import withAuth from './Auth'
|
||||
|
||||
export {
|
||||
ActivityTypeSwitch,
|
||||
TextareaTag,
|
||||
export {
|
||||
ActivityTypeSwitch,
|
||||
TextareaTag,
|
||||
FormSwitch,
|
||||
ImageUpload,
|
||||
Range,
|
||||
NumberInterval,
|
||||
TimeSelector,
|
||||
ImageUpload,
|
||||
Range,
|
||||
NumberInterval,
|
||||
TimeSelector,
|
||||
TitleTextarea,
|
||||
CommonPopup,
|
||||
DateTimePicker,
|
||||
@@ -33,6 +34,7 @@ import EditModal from './EditModal/index'
|
||||
CommonDialog,
|
||||
PublishMenu,
|
||||
UploadCover,
|
||||
EditModal
|
||||
EditModal,
|
||||
withAuth,
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user