Merge branch 'local_server' into dev_environment
This commit is contained in:
commit
7df21bd9e0
21 changed files with 496 additions and 88 deletions
|
|
@ -1,15 +1,20 @@
|
|||
import { Auth0Provider } from '@auth0/auth0-react'
|
||||
import { or } from '../utils/types'
|
||||
import { isAuth0Configured, isAuth0SpaOriginAllowed, shouldMountAuth0Provider } from '../utils/auth0Config'
|
||||
import AuthWrapper from '../providers/auth'
|
||||
import HTTPProvider from 'providers/http'
|
||||
import { useState } from 'react'
|
||||
import LoadingScreen from './LoadingScreen'
|
||||
import LocalAuthPlaceholder from './LocalAuthPlaceholder'
|
||||
import UserWrapper from './UserWrapper'
|
||||
import { getWhitelabel } from 'services/whiteLabel'
|
||||
import { AppThemeProvider } from 'theme/AppThemeProvider'
|
||||
import { LocalAuthProvider, Auth0AuthBridge } from '../providers/authContext'
|
||||
|
||||
function App() {
|
||||
const [token, setToken] = useState<string | undefined>(undefined)
|
||||
const [token, setToken] = useState<string | undefined>(() => {
|
||||
return localStorage.getItem('local_auth_token') || undefined
|
||||
})
|
||||
|
||||
const whiteLabel = getWhitelabel()
|
||||
const manifestPath = "/" + whiteLabel.name.replace(/\s/g, "") + "/manifest.json"
|
||||
|
|
@ -54,6 +59,29 @@ function App() {
|
|||
"/libracart"
|
||||
]
|
||||
|
||||
if (!shouldMountAuth0Provider()) {
|
||||
const placeholderReason =
|
||||
isAuth0Configured() && !isAuth0SpaOriginAllowed() ? 'insecure_origin' : 'unconfigured'
|
||||
|
||||
if (!token) {
|
||||
return (
|
||||
<AppThemeProvider>
|
||||
<LocalAuthPlaceholder reason={placeholderReason} setToken={setToken} />
|
||||
</AppThemeProvider>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<AppThemeProvider>
|
||||
<LocalAuthProvider token={token}>
|
||||
<HTTPProvider token={token}>
|
||||
<UserWrapper token={token} />
|
||||
</HTTPProvider>
|
||||
</LocalAuthProvider>
|
||||
</AppThemeProvider>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<AppThemeProvider>
|
||||
<Auth0Provider
|
||||
|
|
@ -69,10 +97,12 @@ function App() {
|
|||
>
|
||||
{/* <CssBaseline /> */}
|
||||
<AuthWrapper setToken={setToken}>
|
||||
{ token ?
|
||||
<HTTPProvider token={token}>
|
||||
<UserWrapper token={token} />
|
||||
</HTTPProvider>
|
||||
{ token ?
|
||||
<Auth0AuthBridge>
|
||||
<HTTPProvider token={token}>
|
||||
<UserWrapper token={token} />
|
||||
</HTTPProvider>
|
||||
</Auth0AuthBridge>
|
||||
:
|
||||
<LoadingScreen
|
||||
message='Loading user profile'
|
||||
|
|
|
|||
141
src/app/LocalAuthPlaceholder.tsx
Normal file
141
src/app/LocalAuthPlaceholder.tsx
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
import { Box, Button, CssBaseline, Paper, Stack, TextField, Typography } from '@mui/material'
|
||||
import { getName } from 'services/whiteLabel'
|
||||
import { useState } from 'react'
|
||||
import axios from 'axios'
|
||||
|
||||
export type LocalAuthPlaceholderReason = 'unconfigured' | 'insecure_origin'
|
||||
|
||||
interface Props {
|
||||
reason?: LocalAuthPlaceholderReason
|
||||
setToken?: (token: string) => void
|
||||
}
|
||||
|
||||
export default function LocalAuthPlaceholder(props: Props) {
|
||||
const { reason = 'unconfigured', setToken } = props
|
||||
const productName = getName()
|
||||
|
||||
const [mode, setMode] = useState<'login' | 'signup'>('login')
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [name, setName] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const apiUrl = import.meta.env.VITE_APP_API_URL
|
||||
|
||||
const handleSignup = async () => {
|
||||
setError('')
|
||||
setLoading(true)
|
||||
try {
|
||||
const resp = await axios.post(`${apiUrl}/local-auth/signup`, { email, password, name })
|
||||
const token = resp.data.token
|
||||
if (token && setToken) {
|
||||
localStorage.setItem('local_auth_token', token)
|
||||
setToken(token)
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.error || 'Signup failed')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleLogin = async () => {
|
||||
setError('')
|
||||
setLoading(true)
|
||||
try {
|
||||
const resp = await axios.post(`${apiUrl}/local-auth/login`, { email, password })
|
||||
const token = resp.data.token
|
||||
if (token && setToken) {
|
||||
localStorage.setItem('local_auth_token', token)
|
||||
setToken(token)
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.error || 'Login failed')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (mode === 'signup') {
|
||||
handleSignup()
|
||||
} else {
|
||||
handleLogin()
|
||||
}
|
||||
}
|
||||
|
||||
const explanation =
|
||||
reason === 'insecure_origin'
|
||||
? 'This URL is not a secure context for cloud sign-in. Use local account sign-in instead.'
|
||||
: 'Local account sign-in for this deployment.'
|
||||
|
||||
return (
|
||||
<>
|
||||
<CssBaseline />
|
||||
<Box
|
||||
sx={{
|
||||
minHeight: '100vh',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
bgcolor: 'background.default',
|
||||
p: 2,
|
||||
}}
|
||||
>
|
||||
<Paper elevation={2} sx={{ maxWidth: 420, width: '100%', p: 4 }}>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<Stack spacing={2} alignItems="stretch">
|
||||
<Typography variant="h5" component="h1">
|
||||
{productName}
|
||||
</Typography>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
{explanation}
|
||||
</Typography>
|
||||
{mode === 'signup' && (
|
||||
<TextField
|
||||
label="Name"
|
||||
value={name}
|
||||
onChange={e => setName(e.target.value)}
|
||||
fullWidth
|
||||
/>
|
||||
)}
|
||||
<TextField
|
||||
label="Email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={e => setEmail(e.target.value)}
|
||||
required
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
label="Password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={e => setPassword(e.target.value)}
|
||||
required
|
||||
fullWidth
|
||||
/>
|
||||
{error && (
|
||||
<Typography variant="body2" color="error">
|
||||
{error}
|
||||
</Typography>
|
||||
)}
|
||||
<Button variant="contained" size="large" type="submit" disabled={loading}>
|
||||
{mode === 'signup' ? 'Sign up' : 'Log in'}
|
||||
</Button>
|
||||
<Button
|
||||
variant="text"
|
||||
size="small"
|
||||
onClick={() => { setMode(mode === 'login' ? 'signup' : 'login'); setError('') }}
|
||||
>
|
||||
{mode === 'login' ? 'Need an account? Sign up' : 'Already have an account? Log in'}
|
||||
</Button>
|
||||
</Stack>
|
||||
</form>
|
||||
</Paper>
|
||||
</Box>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,7 +1,6 @@
|
|||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import './App.css'
|
||||
import { useUserAPI } from '../providers/pond/userAPI'
|
||||
import { useAuth0 } from '@auth0/auth0-react'
|
||||
import { or } from '../utils/types'
|
||||
import LoadingScreen from './LoadingScreen'
|
||||
import NavigationContainer from '../navigation/NavigationContainer'
|
||||
|
|
@ -12,9 +11,8 @@ import { makeStyles } from '@mui/styles'
|
|||
import { CssBaseline, Theme } from '@mui/material'
|
||||
import { AppThemeProvider } from 'theme/AppThemeProvider'
|
||||
import HTTPProvider from 'providers/http'
|
||||
import { Crisp } from "crisp-sdk-web";
|
||||
import { useMobile, useSnackbar } from 'hooks'
|
||||
import { initCrisp } from '../chat/CrispChat'
|
||||
import { initCrisp, isCrispEnabled } from '../chat/CrispChat'
|
||||
// import FirmwareLoader from './FirmwareLoader'
|
||||
|
||||
const reducer = (state: GlobalState, action: GlobalStateAction): GlobalState => {
|
||||
|
|
@ -34,7 +32,7 @@ const useStyles = makeStyles((theme: Theme) => ({
|
|||
paddingBottom: 0,
|
||||
},
|
||||
[theme.breakpoints.up("md")]: {
|
||||
paddingLeft: theme.spacing(9)
|
||||
paddingLeft: theme.spacing(8)
|
||||
},
|
||||
},
|
||||
container: {
|
||||
|
|
@ -64,16 +62,19 @@ export default function UserWrapper(props: Props) {
|
|||
const [loading, setLoading] = useState(false)
|
||||
const userAPI = useUserAPI();
|
||||
const classes = useStyles();
|
||||
const useAuth = useAuth0();
|
||||
const hasFetched = useRef(false);
|
||||
const [global, setGlobal] = useState<undefined | GlobalState>(undefined)
|
||||
const snackbar = useSnackbar()
|
||||
const isMobile = useMobile()
|
||||
|
||||
const user_id = or(useAuth.user?.sub, "")
|
||||
|
||||
const crispInitialized = useRef(false);
|
||||
Crisp.configure(import.meta.env.VITE_CRISP_WEBSITE_ID);
|
||||
const user_id = (() => {
|
||||
try {
|
||||
const payload = JSON.parse(atob(token.split('.')[1]))
|
||||
return or(payload.sub, '')
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
})()
|
||||
|
||||
const loadUser = useCallback(() => {
|
||||
if (!userAPI.getUserWithTeam) return;
|
||||
|
|
@ -114,15 +115,14 @@ export default function UserWrapper(props: Props) {
|
|||
}, [setGlobal])
|
||||
|
||||
useEffect(() => {
|
||||
if (global?.user) {
|
||||
initCrisp({
|
||||
websiteId: import.meta.env.VITE_CRISP_WEBSITE_ID,
|
||||
email: global.user.settings.email,
|
||||
nickname: global.user.settings.name || global.user.settings.email,
|
||||
phone: global.user.settings.phoneNumber,
|
||||
tokenId: global.user.id(),
|
||||
});
|
||||
}
|
||||
if (!global?.user || !isCrispEnabled()) return;
|
||||
initCrisp({
|
||||
websiteId: import.meta.env.VITE_CRISP_WEBSITE_ID,
|
||||
email: global.user.settings.email,
|
||||
nickname: global.user.settings.name || global.user.settings.email,
|
||||
phone: global.user.settings.phoneNumber,
|
||||
tokenId: global.user.id(),
|
||||
});
|
||||
}, [global]);
|
||||
|
||||
// useEffect(() => {
|
||||
|
|
@ -150,6 +150,7 @@ export default function UserWrapper(props: Props) {
|
|||
// }, [isMobile]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isCrispEnabled()) return;
|
||||
let style = document.getElementById("crisp-offset-override");
|
||||
if (!style) {
|
||||
style = document.createElement("style");
|
||||
|
|
@ -194,4 +195,4 @@ export default function UserWrapper(props: Props) {
|
|||
</AppThemeProvider>
|
||||
</StateProvider>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ const useStyles = makeStyles((theme: Theme) => {
|
|||
position: "fixed",
|
||||
bottom: theme.spacing(8), //for mobile navigator
|
||||
right: theme.spacing(2),
|
||||
zIndex: theme.zIndex.speedDial,
|
||||
[theme.breakpoints.up("sm")]: {
|
||||
bottom: theme.spacing(1.75)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import Chat from "./Chat";
|
|||
import { pond } from "protobuf-ts/pond";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTeamAPI } from "providers";
|
||||
import { closeCrispChat, openCrispChat } from './CrispChat';
|
||||
import { closeCrispChat, isCrispEnabled, openCrispChat } from './CrispChat';
|
||||
import RobotIcon from "products/CommonIcons/robotIcon";
|
||||
|
||||
const useStyles = makeStyles<Theme>((theme: Theme) => ({
|
||||
|
|
@ -68,7 +68,7 @@ export function ChatDrawer(props: Props) {
|
|||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
if (open && isCrispEnabled()) {
|
||||
closeCrispChat()
|
||||
}
|
||||
}, [open])
|
||||
|
|
@ -108,13 +108,15 @@ export function ChatDrawer(props: Props) {
|
|||
<Avatar src={team.settings.avatar} />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<Tooltip title={"Chat Assistant"} placement="right">
|
||||
<IconButton
|
||||
onClick={openCrisp}
|
||||
>
|
||||
<RobotIcon />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
{isCrispEnabled() && (
|
||||
<Tooltip title={"Chat Assistant"} placement="right">
|
||||
<IconButton
|
||||
onClick={openCrisp}
|
||||
>
|
||||
<RobotIcon />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Box width={"100%"} borderBottom={"1px solid grey"} />
|
||||
{teams.map((t, i)=> {
|
||||
if (t.settings?.key === team.key()) return null;
|
||||
|
|
|
|||
|
|
@ -5,6 +5,11 @@ const ANIMATION_DURATION_MS = 300;
|
|||
|
||||
let initialized = false;
|
||||
|
||||
export function isCrispEnabled(): boolean {
|
||||
const id = import.meta.env.VITE_CRISP_WEBSITE_ID;
|
||||
return typeof id === "string" && id.trim() !== "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize Crisp and immediately hide the default chat button.
|
||||
* Call this once on app load (e.g., in UserWrapper after user data is ready).
|
||||
|
|
@ -17,6 +22,7 @@ export function initCrisp(opts: {
|
|||
tokenId?: string;
|
||||
}) {
|
||||
if (initialized) return;
|
||||
if (!opts.websiteId?.trim()) return;
|
||||
|
||||
Crisp.configure(opts.websiteId);
|
||||
Crisp.session.reset();
|
||||
|
|
@ -71,6 +77,7 @@ function injectCrispStyles() {
|
|||
* Safe to call from any onClick handler.
|
||||
*/
|
||||
export function openCrispChat() {
|
||||
if (!initialized) return;
|
||||
const chatbox = document.getElementById("crisp-chatbox");
|
||||
if (chatbox) {
|
||||
chatbox.classList.add("crisp-visible");
|
||||
|
|
@ -86,6 +93,7 @@ export function openCrispChat() {
|
|||
* Close the chat window and hide the widget.
|
||||
*/
|
||||
export function closeCrispChat() {
|
||||
if (!initialized) return;
|
||||
Crisp.chat.close();
|
||||
hideCrispChatButton();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ import OmniAirDeviceIcon from "products/AviationIcons/OmniAirDeviceIcon";
|
|||
import AirportMapIcon from "products/AviationIcons/AirportMapIcon";
|
||||
import PlaneIcon from "products/AviationIcons/PlaneIcon";
|
||||
import JobsiteIcon from "products/Construction/JobSiteIcon";
|
||||
import { useAuth0 } from "@auth0/auth0-react";
|
||||
import { useAuthContext } from "providers/authContext";
|
||||
|
||||
interface Props {
|
||||
sideIsOpen: boolean;
|
||||
|
|
@ -33,7 +33,7 @@ export default function BottomNavigator(props: Props) {
|
|||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const prevLocation = usePrevious(location);
|
||||
const { isAuthenticated } = useAuth0();
|
||||
const { isAuthenticated } = useAuthContext();
|
||||
const [{ user }] = useGlobalState();
|
||||
const [route, setRoute] = useState(sideIsOpen ? "side" : "");
|
||||
const isAg = IsAdaptiveAgriculture();
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { lazy, Suspense } from "react";
|
||||
import LoadingScreen from "../app/LoadingScreen";
|
||||
import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
|
||||
import { useAuth0 } from "@auth0/auth0-react";
|
||||
import { useAuthContext } from "providers/authContext";
|
||||
import Header from "app/Header";
|
||||
import Logout from "pages/Logout";
|
||||
import { ErrorBoundary } from "react-error-boundary";
|
||||
|
|
@ -57,7 +57,7 @@ export const appendToUrl = (appendage: number | string) => {
|
|||
|
||||
export default function Router() {
|
||||
|
||||
const { /*isAuthenticated, loginWithRedirect,*/ isLoading } = useAuth0();
|
||||
const { isAuthenticated } = useAuthContext();
|
||||
const whiteLabel = getWhitelabel();
|
||||
const [{ user }] = useGlobalState();
|
||||
|
||||
|
|
@ -306,13 +306,7 @@ export default function Router() {
|
|||
);
|
||||
}
|
||||
|
||||
if (isLoading) return null;
|
||||
// if (!isAuthenticated) {
|
||||
// loginWithRedirect()
|
||||
// return (
|
||||
// null
|
||||
// )
|
||||
// }
|
||||
if (!isAuthenticated) return null;
|
||||
|
||||
function ErrorFallback({ error }: { error: Error }) {
|
||||
return <div>Something went wrong: {error.stack}</div>;
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ import {
|
|||
IsStreamline,
|
||||
} from "services/whiteLabel";
|
||||
import MiningIcon from "products/ventilation/MiningIcon";
|
||||
import { useAuth0 } from "@auth0/auth0-react";
|
||||
import { useAuthContext } from "providers/authContext";
|
||||
import FieldsIcon from "products/AgIcons/FieldsIcon";
|
||||
import PlaneIcon from "products/AviationIcons/PlaneIcon";
|
||||
import AirportMapIcon from "products/AviationIcons/AirportMapIcon";
|
||||
|
|
@ -53,6 +53,7 @@ import CNHiIcon from "products/CommonIcons/cnhiIcon";
|
|||
import LibraCartIcon from "products/CommonIcons/libracartIcon";
|
||||
|
||||
const drawerWidth = 230;
|
||||
const closedDrawerWidth = 8;
|
||||
|
||||
const useStyles = makeStyles((theme: Theme) => ({
|
||||
sideMenu: {
|
||||
|
|
@ -66,6 +67,8 @@ const useStyles = makeStyles((theme: Theme) => ({
|
|||
sideMenuOpened: {
|
||||
zIndex: theme.zIndex.drawer + 2,
|
||||
width: drawerWidth,
|
||||
minWidth: drawerWidth,
|
||||
maxWidth: drawerWidth,
|
||||
transition: theme.transitions.create(["width"], {
|
||||
easing: theme.transitions.easing.sharp,
|
||||
duration: theme.transitions.duration.enteringScreen
|
||||
|
|
@ -76,12 +79,16 @@ const useStyles = makeStyles((theme: Theme) => ({
|
|||
easing: theme.transitions.easing.sharp,
|
||||
duration: theme.transitions.duration.leavingScreen
|
||||
}),
|
||||
// overflowX: "hidden",
|
||||
overflowX: "hidden",
|
||||
width: theme.spacing(0),
|
||||
minWidth: theme.spacing(0),
|
||||
maxWidth: theme.spacing(0),
|
||||
// zIndex: theme.zIndex.drawer,
|
||||
// opacity: 0,
|
||||
[theme.breakpoints.up("md")]: {
|
||||
width: theme.spacing(9.25),
|
||||
width: theme.spacing(closedDrawerWidth),
|
||||
minWidth: theme.spacing(closedDrawerWidth),
|
||||
maxWidth: theme.spacing(closedDrawerWidth),
|
||||
opacity: 1
|
||||
}
|
||||
},
|
||||
|
|
@ -130,7 +137,7 @@ interface Props {
|
|||
|
||||
export default function SideNavigator(props: Props) {
|
||||
const { open, onOpen, onClose } = props;
|
||||
const { isAuthenticated } = useAuth0()
|
||||
const { isAuthenticated } = useAuthContext()
|
||||
const theme = useTheme();
|
||||
const width = useWidth();
|
||||
const classes = useStyles();
|
||||
|
|
@ -538,11 +545,16 @@ export default function SideNavigator(props: Props) {
|
|||
onClose={onClose}
|
||||
sx={{ pointerEvents: isMobile&&!open ? "none" : "auto"}}
|
||||
>
|
||||
<Toolbar >
|
||||
<Toolbar>
|
||||
<Grid container direction="row" justifyContent={"flex-end"}>
|
||||
<Grid>
|
||||
<IconButton onClick={onClose} aria-label="onClose side menu">
|
||||
{theme.direction === "rtl" ? <ChevronRight /> : <ChevronLeft />}
|
||||
<IconButton
|
||||
onClick={open ? onClose : onOpen}
|
||||
aria-label={open ? "Close side menu" : "Open side menu"}
|
||||
>
|
||||
{open
|
||||
? theme.direction === "rtl" ? <ChevronRight /> : <ChevronLeft />
|
||||
: theme.direction === "rtl" ? <ChevronLeft /> : <ChevronRight />}
|
||||
</IconButton>
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
|
@ -552,4 +564,4 @@ export default function SideNavigator(props: Props) {
|
|||
{isAuthenticated && authenticatedSideMenu()}
|
||||
</SwipeableDrawer>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,11 @@
|
|||
import { RedirectLoginOptions, useAuth0 } from "@auth0/auth0-react";
|
||||
import { RedirectLoginOptions } from "@auth0/auth0-react";
|
||||
// import { useAuth } from "hooks";
|
||||
import queryString from "query-string";
|
||||
import { useEffect } from "react";
|
||||
import { useLocation } from "react-router";
|
||||
// import Loading from "./Loading";
|
||||
import LoadingScreen from "app/LoadingScreen";
|
||||
import { useAuthContext } from "providers/authContext";
|
||||
|
||||
// interface Props {
|
||||
// prevPath?: string;
|
||||
|
|
@ -13,7 +14,7 @@ import LoadingScreen from "app/LoadingScreen";
|
|||
export default function Login() {
|
||||
// const { prevPath } = props;
|
||||
const location = useLocation();
|
||||
const { loginWithRedirect } = useAuth0();
|
||||
const { loginWithRedirect } = useAuthContext();
|
||||
|
||||
// const setRouteBeforeLogin = useCallback((): Promise<string> => {
|
||||
// return new Promise(function(resolve) {
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import { useAuth0 } from "@auth0/auth0-react";
|
||||
import { useAuthContext } from "providers/authContext";
|
||||
import LoadingScreen from "app/LoadingScreen";
|
||||
import { useEffect } from "react";
|
||||
|
||||
export default function Logout() {
|
||||
const { logout } = useAuth0();
|
||||
const { logout } = useAuthContext();
|
||||
|
||||
useEffect(() => {
|
||||
logout();
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { useAuth0 } from '@auth0/auth0-react';
|
||||
import { useAuthContext } from './authContext';
|
||||
|
||||
const LoginButton = () => {
|
||||
const { loginWithRedirect } = useAuth0();
|
||||
const { loginWithRedirect } = useAuthContext();
|
||||
|
||||
return (
|
||||
<button onClick={() => loginWithRedirect()}>
|
||||
|
|
@ -10,4 +10,4 @@ const LoginButton = () => {
|
|||
);
|
||||
};
|
||||
|
||||
export default LoginButton;
|
||||
export default LoginButton;
|
||||
|
|
|
|||
44
src/providers/authContext.tsx
Normal file
44
src/providers/authContext.tsx
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { RedirectLoginOptions, useAuth0 } from "@auth0/auth0-react"
|
||||
import { createContext, PropsWithChildren, useContext } from "react"
|
||||
|
||||
interface IAuthContext {
|
||||
isAuthenticated: boolean
|
||||
loginWithRedirect: (options?: RedirectLoginOptions) => void | Promise<void>
|
||||
logout: () => void
|
||||
}
|
||||
|
||||
const AuthContext = createContext<IAuthContext>({
|
||||
isAuthenticated: false,
|
||||
loginWithRedirect: () => {},
|
||||
logout: () => {},
|
||||
})
|
||||
|
||||
export function LocalAuthProvider(props: PropsWithChildren<{ token: string }>) {
|
||||
const { children, token } = props
|
||||
const doLogout = () => {
|
||||
localStorage.removeItem('local_auth_token')
|
||||
window.location.href = '/'
|
||||
}
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
isAuthenticated: !!token,
|
||||
loginWithRedirect: doLogout,
|
||||
logout: doLogout,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function Auth0AuthBridge(props: PropsWithChildren<{}>) {
|
||||
const { isAuthenticated, loginWithRedirect, logout } = useAuth0()
|
||||
return (
|
||||
<AuthContext.Provider value={{ isAuthenticated, loginWithRedirect, logout: () => logout({ logoutParams: { returnTo: window.location.origin } }) }}>
|
||||
{props.children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export const useAuthContext = () => useContext(AuthContext)
|
||||
|
|
@ -2,7 +2,7 @@ import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
|
|||
import moment from "moment";
|
||||
import { createContext, PropsWithChildren, useContext } from "react";
|
||||
import PondProvider from "./pond/pond";
|
||||
import { useAuth0 } from "@auth0/auth0-react";
|
||||
import { useAuthContext } from "./authContext";
|
||||
import SnackbarProvider from "./Snackbar";
|
||||
|
||||
interface IHTTPContext {
|
||||
|
|
@ -30,7 +30,7 @@ export const HTTPContext = createContext<IHTTPContext>({} as IHTTPContext);
|
|||
|
||||
export default function HTTPProvider(props: Props) {
|
||||
const { children, token } = props;
|
||||
const { isAuthenticated, loginWithRedirect } = useAuth0();
|
||||
const { isAuthenticated, loginWithRedirect } = useAuthContext();
|
||||
|
||||
const defaultOptions = (demo: boolean = false) => {
|
||||
if (demo || !isAuthenticated || !token) {
|
||||
|
|
@ -42,7 +42,7 @@ export default function HTTPProvider(props: Props) {
|
|||
}
|
||||
|
||||
const config = {
|
||||
headers: {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
|
|
@ -50,31 +50,24 @@ export default function HTTPProvider(props: Props) {
|
|||
return config;
|
||||
};
|
||||
|
||||
function isTokenExpired(token: string): boolean {
|
||||
function isTokenExpired(token: string | undefined): boolean {
|
||||
if (!token) return true;
|
||||
try {
|
||||
// Split the token and decode the payload (second part)
|
||||
const payloadBase64 = token.split('.')[1];
|
||||
const decodedPayload = atob(payloadBase64); // Decode base64
|
||||
const payload = JSON.parse(decodedPayload);
|
||||
|
||||
// Get expiration time (in seconds)
|
||||
const payload = JSON.parse(atob(payloadBase64));
|
||||
const exp = payload.exp;
|
||||
|
||||
if (!exp) return true; // No exp field? Treat as expired
|
||||
|
||||
// Current time in seconds
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
|
||||
// Compare
|
||||
return now >= exp;
|
||||
} catch (error) {
|
||||
console.error("Invalid token format:", error);
|
||||
return true; // Err on the side of caution if decoding fails
|
||||
if (!exp) return true;
|
||||
return Math.floor(Date.now() / 1000) >= exp;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function get<T>(url: string, spreadOptions?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
|
||||
if (isTokenExpired(token)) loginWithRedirect()
|
||||
if (isTokenExpired(token)) {
|
||||
loginWithRedirect();
|
||||
return Promise.reject(new Error("token expired"));
|
||||
}
|
||||
return axios.get(url, {...defaultOptions(), ...spreadOptions});
|
||||
}
|
||||
|
||||
|
|
@ -83,6 +76,10 @@ export default function HTTPProvider(props: Props) {
|
|||
data?: any,
|
||||
spreadOptions?: AxiosRequestConfig
|
||||
): Promise<AxiosResponse<T>> {
|
||||
if (isTokenExpired(token)) {
|
||||
loginWithRedirect();
|
||||
return Promise.reject(new Error("token expired"));
|
||||
}
|
||||
return axios.put(url, data, { ...defaultOptions(), ...spreadOptions });
|
||||
}
|
||||
|
||||
|
|
@ -91,10 +88,18 @@ export default function HTTPProvider(props: Props) {
|
|||
data?: any,
|
||||
spreadOptions?: AxiosRequestConfig
|
||||
): Promise<AxiosResponse<T>> {
|
||||
if (isTokenExpired(token)) {
|
||||
loginWithRedirect();
|
||||
return Promise.reject(new Error("token expired"));
|
||||
}
|
||||
return axios.post(url, data, { ...defaultOptions(), ...spreadOptions });
|
||||
}
|
||||
|
||||
function del<T>(url: string, spreadOptions?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
|
||||
if (isTokenExpired(token)) {
|
||||
loginWithRedirect();
|
||||
return Promise.reject(new Error("token expired"));
|
||||
}
|
||||
return axios.delete(url, { ...defaultOptions(), ...spreadOptions });
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import { makeStyles } from "@mui/styles";
|
|||
import { LockOpen, Person, Lock, Settings, SupervisedUserCircle as TeamIcon, ExitToApp, PersonAdd } from "@mui/icons-material";
|
||||
import { useState } from "react";
|
||||
import UserTeamName from "./UserTeamName";
|
||||
import { useAuth0 } from "@auth0/auth0-react";
|
||||
import { useAuthContext } from "providers/authContext";
|
||||
import UserSettings from "./UserSettings";
|
||||
import UserAvatar from "./UserAvatar";
|
||||
import { purple } from "@mui/material/colors";
|
||||
|
|
@ -77,7 +77,7 @@ export default function UserMenu() {
|
|||
|
||||
// const { toggleMode } = useThemeMode()
|
||||
const [{ user, team, as }, dispatch] = useGlobalState();
|
||||
const { loginWithRedirect } = useAuth0();
|
||||
const { loginWithRedirect } = useAuthContext();
|
||||
const classes = useStyles();
|
||||
const theme = useTheme();
|
||||
|
||||
|
|
|
|||
24
src/utils/auth0Config.ts
Normal file
24
src/utils/auth0Config.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { getWhitelabel } from 'services/whiteLabel'
|
||||
|
||||
/** True when Auth0 env + whitelabel client ID are present; avoids mounting Auth0Provider on offline / local LAN builds. */
|
||||
export function isAuth0Configured(): boolean {
|
||||
const wl = getWhitelabel()
|
||||
const domain = String(import.meta.env.VITE_AUTH0_CLIENT_DOMAIN ?? '').trim()
|
||||
const clientRaw = wl.auth0ClientId ?? import.meta.env.VITE_AUTH0_CLIENT_ID
|
||||
const clientId = String(clientRaw ?? '').trim()
|
||||
return domain.length > 0 && clientId.length > 0
|
||||
}
|
||||
|
||||
/**
|
||||
* auth0-spa-js only runs in a "secure context" (HTTPS, http://localhost, http://127.0.0.1, etc.).
|
||||
* Plain http://192.168.x.x fails — same check as `window.isSecureContext`.
|
||||
*/
|
||||
export function isAuth0SpaOriginAllowed(): boolean {
|
||||
if (typeof window === 'undefined') return true
|
||||
return window.isSecureContext
|
||||
}
|
||||
|
||||
/** Mount Auth0 only when credentials exist and the browser will let the SDK run. */
|
||||
export function shouldMountAuth0Provider(): boolean {
|
||||
return isAuth0Configured() && isAuth0SpaOriginAllowed()
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue