Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#1036] feat(UI): Add refresh token and a logout option in the webUI (#1037)

CHEYNEb79cc47fd5c2
diff --git a/web/.env b/web/.env
index 3a837392a8..d4ad65dac0 100644
--- a/web/.env
+++ b/web/.env
@@ -6,5 +6,5 @@
OUTPUT_MODE=standalone
# Development ENV
NEXT_PUBLIC_API_URL=http://localhost:8090
-NEXT_PUBLIC_OAUTH_URI=http://localhost:9010
+NEXT_PUBLIC_OAUTH_URI=http://localhost:9000
NEXT_PUBLIC_OAUTH_PATH=/oauth2/token
diff --git a/web/.env.analyze b/web/.env.analyze
index 7735165d33..3f6a76c667 100644
--- a/web/.env.analyze
+++ b/web/.env.analyze
@@ -7,5 +7,5 @@ ANALYZE=true
OUTPUT_MODE=export
# Development ENV
NEXT_PUBLIC_API_URL=http://localhost:8090
-NEXT_PUBLIC_OAUTH_URI=http://localhost:9010
+NEXT_PUBLIC_OAUTH_URI=http://localhost:9000
NEXT_PUBLIC_OAUTH_PATH=/oauth2/token
diff --git a/web/.env.static b/web/.env.static
index d15fb523d6..bcb257614e 100644
--- a/web/.env.static
+++ b/web/.env.static
@@ -6,5 +6,5 @@
OUTPUT_MODE=export
# Development ENV
NEXT_PUBLIC_API_URL=http://localhost:8090
-NEXT_PUBLIC_OAUTH_URI=http://localhost:9010
+NEXT_PUBLIC_OAUTH_URI=http://localhost:9000
NEXT_PUBLIC_OAUTH_PATH=/oauth2/token
diff --git a/web/app/(home)/page.js b/web/app/(home)/page.js
index 6fc3543dcd..f3e0686963 100644
--- a/web/app/(home)/page.js
+++ b/web/app/(home)/page.js
@@ -3,6 +3,8 @@
* This software is licensed under the Apache License version 2.
*/
+'use client'
+
import MetalakesView from './MetalakesView'
const HomePage = props => {
diff --git a/web/app/layout.js b/web/app/layout.js
index 67dcab6dda..4b22a53d28 100644
--- a/web/app/layout.js
+++ b/web/app/layout.js
@@ -5,6 +5,10 @@
import '@/lib/styles/globals.css'
+import { Suspense } from 'react'
+
+import { NavigationEvents } from '@/lib/layout/navigation-events'
+
import Provider from '@/lib/provider'
import Layout from '@/lib/layout/Layout'
@@ -13,13 +17,22 @@ export const metadata = {
description: 'A high-performance, geo-distributed and federated metadata lake.'
}
+import Loading from '@/lib/layout/Loading'
+
const RootLayout = props => {
const { children } = props
return (
<html lang='en' suppressHydrationWarning>
<body>
- <Provider>{<Layout>{children}</Layout>}</Provider>
+ <Provider>
+ {
+ <Suspense fallback={<Loading />}>
+ <NavigationEvents />
+ <Layout>{children}</Layout>
+ </Suspense>
+ }
+ </Provider>
</body>
</html>
)
diff --git a/web/app/login/page.js b/web/app/login/page.js
index a21cc9dd8e..e242984cac 100644
--- a/web/app/login/page.js
+++ b/web/app/login/page.js
@@ -5,10 +5,7 @@
'use client'
-import { useEffect } from 'react'
-
import Image from 'next/image'
-import { useRouter, usePathname } from 'next/navigation'
import { Box, Card, Grid, Button, CardContent, Typography, TextField, FormControl, FormHelperText } from '@mui/material'
@@ -16,9 +13,6 @@ import * as yup from 'yup'
import { useForm, Controller } from 'react-hook-form'
import { yupResolver } from '@hookform/resolvers/yup'
import { useAuth } from '@/lib/provider/session'
-import { useLocalStorage } from 'react-use'
-
-import { useAppSelector } from '@/lib/hooks/useStore'
const defaultValues = {
grant_type: 'client_credentials',
@@ -36,12 +30,6 @@ const schema = yup.object().shape({
const LoginPage = () => {
const auth = useAuth()
- const router = useRouter()
- const pathname = usePathname()
-
- const [version] = useLocalStorage('version')
-
- const authStore = useAppSelector(state => state.auth)
const {
control,
@@ -57,18 +45,6 @@ const LoginPage = () => {
auth.login(data)
}
- useEffect(() => {
- if (authStore.authType === 'simple') {
- router.push('/')
- } else {
- const check = version && pathname === '/login'
- if (check) {
- router.push('/')
- }
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [])
-
return (
<Grid container spacing={2} sx={{ justifyContent: 'center', alignItems: 'center', height: '100%' }}>
<Box>
diff --git a/web/lib/api/index.js b/web/lib/api/index.js
index 520131dd87..2e44164578 100644
--- a/web/lib/api/index.js
+++ b/web/lib/api/index.js
@@ -15,6 +15,9 @@ const defHttp = axios.create({
})
defHttp.interceptors.request.use(config => {
+ if (config.url.includes('/oauth2/token')) {
+ return config
+ }
const accessToken = typeof window !== 'undefined' ? window.localStorage.getItem('accessToken') : null
if (accessToken) {
diff --git a/web/lib/layout/AppBar.js b/web/lib/layout/AppBar.js
index 0d97f72931..e1e68d967a 100644
--- a/web/lib/layout/AppBar.js
+++ b/web/lib/layout/AppBar.js
@@ -11,6 +11,7 @@ import Image from 'next/image'
import { Box, AppBar as MuiAppBar, Toolbar, Stack, Typography } from '@mui/material'
import VersionView from './VersionView'
+import LogoutButton from './Logout'
const AppBar = props => {
return (
@@ -38,6 +39,7 @@ const AppBar = props => {
<Box className={'app-bar-content-right twc-flex twc-items-center'}>
<Stack direction='row' spacing={2} alignItems='center'>
<VersionView />
+ <LogoutButton />
</Stack>
</Box>
</Box>
diff --git a/web/lib/layout/Layout.js b/web/lib/layout/Layout.js
index 49b8e348c9..84fd85262c 100644
--- a/web/lib/layout/Layout.js
+++ b/web/lib/layout/Layout.js
@@ -17,14 +17,6 @@ import MainContent from './MainContent'
import ScrollToTop from './ScrollToTop'
import { NavigationEvents } from './navigation-events'
-const Loading = () => {
- return (
- <Box className={`twc-h-[100vh] twc-flex twc-items-center twc-flex-col twc-justify-center`}>
- <CircularProgress disableShrink sx={{ mt: 6 }} />
- </Box>
- )
-}
-
const Layout = ({ children, scrollToTop }) => {
return (
<div className={'layout-wrapper twc-h-full twc-flex twc-overflow-clip'}>
@@ -35,10 +27,7 @@ const Layout = ({ children, scrollToTop }) => {
}
/>
<AppBar />
- <Suspense fallback={<Loading />}>
- <NavigationEvents />
- <MainContent>{children}</MainContent>
- </Suspense>
+ <MainContent>{children}</MainContent>
<Footer />
{scrollToTop ? (
scrollToTop(props)
diff --git a/web/lib/layout/Loading.js b/web/lib/layout/Loading.js
new file mode 100644
index 0000000000..ddf21783ea
--- /dev/null
+++ b/web/lib/layout/Loading.js
@@ -0,0 +1,18 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+
+'use client'
+
+import { Box, CircularProgress } from '@mui/material'
+
+const Loading = () => {
+ return (
+ <Box className={`twc-h-[100vh] twc-flex twc-items-center twc-flex-col twc-justify-center`}>
+ <CircularProgress disableShrink sx={{ mt: 6 }} />
+ </Box>
+ )
+}
+
+export default Loading
diff --git a/web/lib/layout/Logout.js b/web/lib/layout/Logout.js
new file mode 100644
index 0000000000..2f492a956e
--- /dev/null
+++ b/web/lib/layout/Logout.js
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+
+'use client'
+
+import { Box, IconButton } from '@mui/material'
+
+import Icon from '@/components/Icon'
+import { useAuth } from '../provider/session'
+import { useAppSelector } from '../hooks/useStore'
+
+const LogoutButton = () => {
+ const auth = useAuth()
+ const authStore = useAppSelector(state => state.auth)
+
+ return (
+ <Box>
+ {authStore.authToken ? (
+ <IconButton onClick={() => auth.logout()}>
+ <Icon icon={'bx:exit'} />
+ </IconButton>
+ ) : null}
+ </Box>
+ )
+}
+
+export default LogoutButton
diff --git a/web/lib/layout/navigation-events.js b/web/lib/layout/navigation-events.js
index 94fe4429ff..99dddd02f2 100644
--- a/web/lib/layout/navigation-events.js
+++ b/web/lib/layout/navigation-events.js
@@ -6,6 +6,7 @@
'use client'
import { useEffect } from 'react'
+
import { usePathname, useSearchParams } from 'next/navigation'
export function NavigationEvents() {
@@ -15,8 +16,9 @@ export function NavigationEvents() {
useEffect(() => {
const url = `${pathname}?${searchParams}`
console.log(url)
+
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [])
+ }, [pathname, searchParams])
return null
}
diff --git a/web/lib/provider/session.js b/web/lib/provider/session.js
index 417bdbc48d..c48af2ebbd 100644
--- a/web/lib/provider/session.js
+++ b/web/lib/provider/session.js
@@ -17,13 +17,13 @@ import { useLocalStorage } from 'react-use'
import { getVersionApi } from '@/lib/api/version'
import { loginApi } from '@/lib/api/auth'
-import { isProdEnv, to } from '../utils'
-import { getAuthConfigs } from '../store/auth'
+import { isProdEnv, to, loggerVersion } from '../utils'
+import { getAuthConfigs, setAuthParams, setAuthToken, setExpiredIn, refreshToken } from '../store/auth'
const devOauthUrl = process.env.NEXT_PUBLIC_OAUTH_PATH
const authProvider = {
- version: null,
+ version: '',
loading: true,
setLoading: () => Boolean,
login: () => Promise.resolve(),
@@ -37,7 +37,9 @@ export const useAuth = () => useContext(AuthContext)
const AuthProvider = ({ children }) => {
const router = useRouter()
const [loading, setLoading] = useState(authProvider.loading)
- const [token, setToken] = useLocalStorage('accessToken', null, { raw: true })
+ const [authParams, setLocalAuthParams] = useLocalStorage('authParams', '', { raw: true })
+ const [localExpiredIn, setLocalExpiredIn] = useLocalStorage('expiredIn', '', { raw: true })
+ const [token, setToken] = useLocalStorage('accessToken', '', { raw: true })
const [version, setVersion] = useLocalStorage('version', authProvider.version, { raw: false })
const authStore = useAppSelector(state => state.auth)
const dispatch = useAppDispatch()
@@ -45,71 +47,79 @@ const AuthProvider = ({ children }) => {
const handleLogin = async params => {
let oauthUrl = authStore.oauthUrl
- try {
- const response = await loginApi(isProdEnv ? oauthUrl : devOauthUrl, params)
-
- const { access_token } = response.data
-
- if (access_token) {
- setToken(access_token)
-
- getVersionApi()
- .then(async res => {
- const { version } = res.data
- console.log(
- `Gravitino Version: %c${version.version}`,
- `color: white; background-color: #6062E0; padding: 2px; border-radius: 4px;`
- )
- setVersion(version)
- dispatch(setStoreVersion(version.version))
- router.replace('/')
- })
- .catch(error => {
- console.error(error)
- })
+ dispatch(setAuthParams(params))
+ setLocalAuthParams(params)
+
+ const getTokenAction = new Promise(async resolve => {
+ const url = isProdEnv ? oauthUrl : devOauthUrl
+ const [err, res] = await to(loginApi(url, params))
+
+ if (err || !res) {
+ throw new Error(err)
}
- } catch (e) {
- throw new Error(e)
- }
+
+ const { access_token, expires_in } = res.data
+
+ setToken(access_token)
+ dispatch(setAuthToken(access_token))
+ setLocalExpiredIn(expires_in)
+ dispatch(setExpiredIn(expires_in))
+ resolve(access_token)
+ })
+
+ getTokenAction.then(async token => {
+ if (!token) {
+ throw new Error('Token not found')
+ }
+ const [verErr, resVer] = await to(getVersionApi())
+
+ const { version } = resVer.data
+
+ loggerVersion(version.version)
+ setVersion(version)
+ dispatch(setStoreVersion(version.version))
+ dispatch(refreshToken())
+ router.replace('/')
+ })
}
const handleLogout = () => {
- setVersion(null)
- setToken(null)
+ setVersion('')
+ dispatch(setStoreVersion(''))
+ setToken('')
+ dispatch(setAuthToken(''))
router.push('/login')
}
useEffect(() => {
const initAuth = async () => {
+ // ** the expired time obtained from the backend is in seconds, default value is 299 seconds
+ const expired = (authStore.expiredIn ?? Number(localExpiredIn)) * (2 / 3) * 1000
+ const defaultExpired = 299 * (2 / 3) * 1000
+
+ let intervalId = null
+
const [authConfigsErr, resAuthConfigs] = await to(dispatch(getAuthConfigs()))
const { authType, oauthUrl } = resAuthConfigs.payload
- if (authType !== 'simple') {
+ if (authType === 'simple') {
+ dispatch(initialVersion())
+ router.replace('/')
+ } else {
if (token) {
- getVersionApi()
- .then(res => {
- setLoading(false)
- const { version } = res.data
- console.log(
- `Gravitino Version: %c${version.version}`,
- `color: white; background-color: #6062E0; padding: 2px; border-radius: 4px;`
- )
- setVersion(version)
- dispatch(setStoreVersion(version.version))
- })
- .catch(() => {
- localStorage.removeItem('version')
- localStorage.removeItem('accessToken')
- setLoading(false)
-
- router.replace('/login')
- })
+ intervalId = setInterval(() => {
+ dispatch(refreshToken())
+ }, expired || defaultExpired)
+
+ dispatch(setAuthToken(token))
+ dispatch(initialVersion())
} else {
- setLoading(false)
router.replace('/login')
}
- } else {
- dispatch(initialVersion())
+ }
+
+ return () => {
+ clearInterval(intervalId)
}
}
diff --git a/web/lib/store/auth/index.js b/web/lib/store/auth/index.js
index 132128fdbf..1c0f922b5b 100644
--- a/web/lib/store/auth/index.js
+++ b/web/lib/store/auth/index.js
@@ -5,9 +5,11 @@
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
-import { to } from '@/lib/utils'
+import { to, isProdEnv } from '@/lib/utils'
-import { getAuthConfigsApi } from '@/lib/api/auth'
+import { getAuthConfigsApi, loginApi } from '@/lib/api/auth'
+
+const devOauthUrl = process.env.NEXT_PUBLIC_OAUTH_PATH
export const getAuthConfigs = createAsyncThunk('sys/getAuthConfigs', async () => {
let oauthUrl = null
@@ -16,25 +18,62 @@ export const getAuthConfigs = createAsyncThunk('sys/getAuthConfigs', async () =>
if (!err && res) {
oauthUrl = `${res.data['gravitino.authenticator.oauth.serverUri']}${res.data['gravitino.authenticator.oauth.tokenPath']}`
+
authType = res.data['gravitino.authenticator']
}
return { oauthUrl, authType }
})
+export const refreshToken = createAsyncThunk('sys/refreshToken', async (data, { getState, dispatch }) => {
+ const authParams = getState().auth.authParams || window.localStorage.getItem('authParams')
+ let params = typeof authParams === 'string' ? JSON.parse(authParams) : authParams
+
+ const url = isProdEnv ? getState().auth.oauthUrl : devOauthUrl
+
+ const [err, res] = await to(loginApi(url, params))
+
+ if (err || !res) {
+ throw new Error(err)
+ }
+
+ const { access_token, expires_in } = res.data
+
+ return { token: access_token, expiredIn: expires_in }
+})
+
export const authSlice = createSlice({
name: 'auth',
initialState: {
oauthUrl: null,
- authType: null
+ authType: null,
+ authToken: '',
+ authParams: null,
+ expiredIn: null
+ },
+ reducers: {
+ setAuthToken(state, action) {
+ state.authToken = action.payload
+ },
+ setAuthParams(state, action) {
+ state.authParams = action.payload
+ },
+ setExpiredIn(state, action) {
+ state.expiredIn = action.payload
+ }
},
- reducers: {},
extraReducers: builder => {
builder.addCase(getAuthConfigs.fulfilled, (state, action) => {
state.oauthUrl = action.payload.oauthUrl
state.authType = action.payload.authType
})
+ builder.addCase(refreshToken.fulfilled, (state, action) => {
+ state.authToken = action.payload.token
+ state.expiredIn = action.payload.expiredIn
+ })
}
})
+export const { setAuthToken, setAuthParams, setExpiredIn } = authSlice.actions
+
export default authSlice.reducer
diff --git a/web/lib/store/sys/index.js b/web/lib/store/sys/index.js
index 87fc88556a..37f19734bf 100644
--- a/web/lib/store/sys/index.js
+++ b/web/lib/store/sys/index.js
@@ -5,7 +5,7 @@
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
-import { to } from '@/lib/utils'
+import { loggerVersion, to } from '@/lib/utils'
import { getVersionApi } from '@/lib/api/version'
@@ -17,10 +17,7 @@ export const initialVersion = createAsyncThunk('sys/fetchVersion', async (params
version = res.data.version
typeof window !== 'undefined' && window.localStorage.setItem('version', JSON.stringify(version))
- console.log(
- `Gravitino Version: %c${version.version}`,
- `color: white; background-color: #6062E0; padding: 2px; border-radius: 4px;`
- )
+ loggerVersion(version.version)
}
return version
@@ -29,7 +26,7 @@ export const initialVersion = createAsyncThunk('sys/fetchVersion', async (params
export const sysSlice = createSlice({
name: 'sys',
initialState: {
- version: null
+ version: ''
},
reducers: {
setVersion(state, action) {
diff --git a/web/lib/utils/index.js b/web/lib/utils/index.js
index e2544f30c6..9fb057de40 100644
--- a/web/lib/utils/index.js
+++ b/web/lib/utils/index.js
@@ -21,6 +21,13 @@ export const to = (promise, errExt) => {
})
}
+export const loggerVersion = version => {
+ console.log(
+ `Gravitino Version: %c${version}`,
+ `color: white; background-color: #6062E0; padding: 2px; border-radius: 4px;`
+ )
+}
+
export const genUpdates = (originalData, newData) => {
const updates = []