local login now functional

This commit is contained in:
Carter 2026-05-06 18:18:57 -06:00
parent 3b62d87d31
commit ae9abaf9fd
9 changed files with 174 additions and 72 deletions

View file

@ -9,9 +9,12 @@ import LocalAuthPlaceholder from './LocalAuthPlaceholder'
import UserWrapper from './UserWrapper' import UserWrapper from './UserWrapper'
import { getWhitelabel } from 'services/whiteLabel' import { getWhitelabel } from 'services/whiteLabel'
import { AppThemeProvider } from 'theme/AppThemeProvider' import { AppThemeProvider } from 'theme/AppThemeProvider'
import { LocalAuthProvider, Auth0AuthBridge } from '../providers/authContext'
function App() { 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 whiteLabel = getWhitelabel()
const manifestPath = "/" + whiteLabel.name.replace(/\s/g, "") + "/manifest.json" const manifestPath = "/" + whiteLabel.name.replace(/\s/g, "") + "/manifest.json"
@ -59,9 +62,22 @@ function App() {
if (!shouldMountAuth0Provider()) { if (!shouldMountAuth0Provider()) {
const placeholderReason = const placeholderReason =
isAuth0Configured() && !isAuth0SpaOriginAllowed() ? 'insecure_origin' : 'unconfigured' isAuth0Configured() && !isAuth0SpaOriginAllowed() ? 'insecure_origin' : 'unconfigured'
if (!token) {
return (
<AppThemeProvider>
<LocalAuthPlaceholder reason={placeholderReason} setToken={setToken} />
</AppThemeProvider>
)
}
return ( return (
<AppThemeProvider> <AppThemeProvider>
<LocalAuthPlaceholder reason={placeholderReason} /> <LocalAuthProvider token={token}>
<HTTPProvider token={token}>
<UserWrapper token={token} />
</HTTPProvider>
</LocalAuthProvider>
</AppThemeProvider> </AppThemeProvider>
) )
} }
@ -82,9 +98,11 @@ function App() {
{/* <CssBaseline /> */} {/* <CssBaseline /> */}
<AuthWrapper setToken={setToken}> <AuthWrapper setToken={setToken}>
{ token ? { token ?
<HTTPProvider token={token}> <Auth0AuthBridge>
<UserWrapper token={token} /> <HTTPProvider token={token}>
</HTTPProvider> <UserWrapper token={token} />
</HTTPProvider>
</Auth0AuthBridge>
: :
<LoadingScreen <LoadingScreen
message='Loading user profile' message='Loading user profile'

View file

@ -1,25 +1,75 @@
import { Box, Button, CssBaseline, Paper, Stack, Typography } from '@mui/material' import { Box, Button, CssBaseline, Paper, Stack, TextField, Typography } from '@mui/material'
import { getName } from 'services/whiteLabel' import { getName } from 'services/whiteLabel'
import { useState } from 'react'
import axios from 'axios'
export type LocalAuthPlaceholderReason = 'unconfigured' | 'insecure_origin' export type LocalAuthPlaceholderReason = 'unconfigured' | 'insecure_origin'
interface Props { interface Props {
/** Why cloud Auth0 was skipped — copy differs when env is set but the page is not a secure context (e.g. http://LAN IP). */
reason?: LocalAuthPlaceholderReason reason?: LocalAuthPlaceholderReason
setToken?: (token: string) => void
} }
/**
* Shown when Auth0 is not used (missing config and/or nonsecure context).
* Replace with backend-driven login once local auth is implemented.
*/
export default function LocalAuthPlaceholder(props: Props) { export default function LocalAuthPlaceholder(props: Props) {
const { reason = 'unconfigured' } = props const { reason = 'unconfigured', setToken } = props
const productName = getName() 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 = const explanation =
reason === 'insecure_origin' reason === 'insecure_origin'
? 'This URL is not a secure context for cloud sign-in (Auth0 requires HTTPS, localhost, or 127.0.0.1). Use local account sign-in here instead once it is connected.' ? 'This URL is not a secure context for cloud sign-in. Use local account sign-in instead.'
: 'Cloud sign-in (Auth0) is not configured for this deployment. Local account sign-in will be available here.' : 'Local account sign-in for this deployment.'
return ( return (
<> <>
@ -35,25 +85,55 @@ export default function LocalAuthPlaceholder(props: Props) {
}} }}
> >
<Paper elevation={2} sx={{ maxWidth: 420, width: '100%', p: 4 }}> <Paper elevation={2} sx={{ maxWidth: 420, width: '100%', p: 4 }}>
<Stack spacing={3} alignItems="stretch"> <form onSubmit={handleSubmit}>
<Typography variant="h5" component="h1"> <Stack spacing={2} alignItems="stretch">
{productName} <Typography variant="h5" component="h1">
</Typography> {productName}
<Typography variant="body2" color="text.secondary"> </Typography>
{explanation} <Typography variant="body2" color="text.secondary">
</Typography> {explanation}
<Stack spacing={1.5}> </Typography>
<Button variant="contained" size="large" disabled> {mode === 'signup' && (
Log in <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>
<Button variant="outlined" size="large" disabled> <Button
Sign up 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> </Button>
</Stack> </Stack>
<Typography variant="caption" color="text.secondary"> </form>
Buttons are placeholders until the backend login flow is wired up.
</Typography>
</Stack>
</Paper> </Paper>
</Box> </Box>
</> </>

View file

@ -1,7 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react' import { useCallback, useEffect, useRef, useState } from 'react'
import './App.css' import './App.css'
import { useUserAPI } from '../providers/pond/userAPI' import { useUserAPI } from '../providers/pond/userAPI'
import { useAuth0 } from '@auth0/auth0-react'
import { or } from '../utils/types' import { or } from '../utils/types'
import LoadingScreen from './LoadingScreen' import LoadingScreen from './LoadingScreen'
import NavigationContainer from '../navigation/NavigationContainer' import NavigationContainer from '../navigation/NavigationContainer'
@ -63,13 +62,19 @@ export default function UserWrapper(props: Props) {
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
const userAPI = useUserAPI(); const userAPI = useUserAPI();
const classes = useStyles(); const classes = useStyles();
const useAuth = useAuth0();
const hasFetched = useRef(false); const hasFetched = useRef(false);
const [global, setGlobal] = useState<undefined | GlobalState>(undefined) const [global, setGlobal] = useState<undefined | GlobalState>(undefined)
const snackbar = useSnackbar() const snackbar = useSnackbar()
const isMobile = useMobile() const isMobile = useMobile()
const user_id = or(useAuth.user?.sub, "") const user_id = (() => {
try {
const payload = JSON.parse(atob(token.split('.')[1]))
return or(payload.sub, '')
} catch {
return ''
}
})()
const loadUser = useCallback(() => { const loadUser = useCallback(() => {
if (!userAPI.getUserWithTeam) return; if (!userAPI.getUserWithTeam) return;

View file

@ -20,7 +20,7 @@ import OmniAirDeviceIcon from "products/AviationIcons/OmniAirDeviceIcon";
import AirportMapIcon from "products/AviationIcons/AirportMapIcon"; import AirportMapIcon from "products/AviationIcons/AirportMapIcon";
import PlaneIcon from "products/AviationIcons/PlaneIcon"; import PlaneIcon from "products/AviationIcons/PlaneIcon";
import JobsiteIcon from "products/Construction/JobSiteIcon"; import JobsiteIcon from "products/Construction/JobSiteIcon";
import { useAuth0 } from "@auth0/auth0-react"; import { useAuthContext } from "providers/authContext";
interface Props { interface Props {
sideIsOpen: boolean; sideIsOpen: boolean;
@ -33,7 +33,7 @@ export default function BottomNavigator(props: Props) {
const navigate = useNavigate(); const navigate = useNavigate();
const location = useLocation(); const location = useLocation();
const prevLocation = usePrevious(location); const prevLocation = usePrevious(location);
const { isAuthenticated } = useAuth0(); const { isAuthenticated } = useAuthContext();
const [{ user }] = useGlobalState(); const [{ user }] = useGlobalState();
const [route, setRoute] = useState(sideIsOpen ? "side" : ""); const [route, setRoute] = useState(sideIsOpen ? "side" : "");
const isAg = IsAdaptiveAgriculture(); const isAg = IsAdaptiveAgriculture();

View file

@ -1,7 +1,7 @@
import { lazy, Suspense } from "react"; import { lazy, Suspense } from "react";
import LoadingScreen from "../app/LoadingScreen"; import LoadingScreen from "../app/LoadingScreen";
import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom"; 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 Header from "app/Header";
import Logout from "pages/Logout"; import Logout from "pages/Logout";
import { ErrorBoundary } from "react-error-boundary"; import { ErrorBoundary } from "react-error-boundary";
@ -57,7 +57,7 @@ export const appendToUrl = (appendage: number | string) => {
export default function Router() { export default function Router() {
const { /*isAuthenticated, loginWithRedirect,*/ isLoading } = useAuth0(); const { isAuthenticated } = useAuthContext();
const whiteLabel = getWhitelabel(); const whiteLabel = getWhitelabel();
const [{ user }] = useGlobalState(); const [{ user }] = useGlobalState();
@ -306,13 +306,7 @@ export default function Router() {
); );
} }
if (isLoading) return null; if (!isAuthenticated) return null;
// if (!isAuthenticated) {
// loginWithRedirect()
// return (
// null
// )
// }
function ErrorFallback({ error }: { error: Error }) { function ErrorFallback({ error }: { error: Error }) {
return <div>Something went wrong: {error.stack}</div>; return <div>Something went wrong: {error.stack}</div>;

View file

@ -35,7 +35,7 @@ import {
IsStreamline, IsStreamline,
} from "services/whiteLabel"; } from "services/whiteLabel";
import MiningIcon from "products/ventilation/MiningIcon"; import MiningIcon from "products/ventilation/MiningIcon";
import { useAuth0 } from "@auth0/auth0-react"; import { useAuthContext } from "providers/authContext";
import FieldsIcon from "products/AgIcons/FieldsIcon"; import FieldsIcon from "products/AgIcons/FieldsIcon";
import PlaneIcon from "products/AviationIcons/PlaneIcon"; import PlaneIcon from "products/AviationIcons/PlaneIcon";
import AirportMapIcon from "products/AviationIcons/AirportMapIcon"; import AirportMapIcon from "products/AviationIcons/AirportMapIcon";
@ -130,7 +130,7 @@ interface Props {
export default function SideNavigator(props: Props) { export default function SideNavigator(props: Props) {
const { open, onOpen, onClose } = props; const { open, onOpen, onClose } = props;
const { isAuthenticated } = useAuth0() const { isAuthenticated } = useAuthContext()
const theme = useTheme(); const theme = useTheme();
const width = useWidth(); const width = useWidth();
const classes = useStyles(); const classes = useStyles();

View file

@ -1,9 +1,9 @@
import { useAuth0 } from "@auth0/auth0-react"; import { useAuthContext } from "providers/authContext";
import LoadingScreen from "app/LoadingScreen"; import LoadingScreen from "app/LoadingScreen";
import { useEffect } from "react"; import { useEffect } from "react";
export default function Logout() { export default function Logout() {
const { logout } = useAuth0(); const { logout } = useAuthContext();
useEffect(() => { useEffect(() => {
logout(); logout();

View file

@ -2,7 +2,7 @@ import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import moment from "moment"; import moment from "moment";
import { createContext, PropsWithChildren, useContext } from "react"; import { createContext, PropsWithChildren, useContext } from "react";
import PondProvider from "./pond/pond"; import PondProvider from "./pond/pond";
import { useAuth0 } from "@auth0/auth0-react"; import { useAuthContext } from "./authContext";
import SnackbarProvider from "./Snackbar"; import SnackbarProvider from "./Snackbar";
interface IHTTPContext { interface IHTTPContext {
@ -30,7 +30,7 @@ export const HTTPContext = createContext<IHTTPContext>({} as IHTTPContext);
export default function HTTPProvider(props: Props) { export default function HTTPProvider(props: Props) {
const { children, token } = props; const { children, token } = props;
const { isAuthenticated, loginWithRedirect } = useAuth0(); const { isAuthenticated, loginWithRedirect } = useAuthContext();
const defaultOptions = (demo: boolean = false) => { const defaultOptions = (demo: boolean = false) => {
if (demo || !isAuthenticated || !token) { if (demo || !isAuthenticated || !token) {
@ -50,31 +50,24 @@ export default function HTTPProvider(props: Props) {
return config; return config;
}; };
function isTokenExpired(token: string): boolean { function isTokenExpired(token: string | undefined): boolean {
if (!token) return true;
try { try {
// Split the token and decode the payload (second part)
const payloadBase64 = token.split('.')[1]; const payloadBase64 = token.split('.')[1];
const decodedPayload = atob(payloadBase64); // Decode base64 const payload = JSON.parse(atob(payloadBase64));
const payload = JSON.parse(decodedPayload);
// Get expiration time (in seconds)
const exp = payload.exp; const exp = payload.exp;
if (!exp) return true;
if (!exp) return true; // No exp field? Treat as expired return Math.floor(Date.now() / 1000) >= exp;
} catch {
// Current time in seconds return true;
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
} }
} }
function get<T>(url: string, spreadOptions?: AxiosRequestConfig): Promise<AxiosResponse<T>> { 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}); return axios.get(url, {...defaultOptions(), ...spreadOptions});
} }
@ -83,6 +76,10 @@ export default function HTTPProvider(props: Props) {
data?: any, data?: any,
spreadOptions?: AxiosRequestConfig spreadOptions?: AxiosRequestConfig
): Promise<AxiosResponse<T>> { ): Promise<AxiosResponse<T>> {
if (isTokenExpired(token)) {
loginWithRedirect();
return Promise.reject(new Error("token expired"));
}
return axios.put(url, data, { ...defaultOptions(), ...spreadOptions }); return axios.put(url, data, { ...defaultOptions(), ...spreadOptions });
} }
@ -91,10 +88,18 @@ export default function HTTPProvider(props: Props) {
data?: any, data?: any,
spreadOptions?: AxiosRequestConfig spreadOptions?: AxiosRequestConfig
): Promise<AxiosResponse<T>> { ): Promise<AxiosResponse<T>> {
if (isTokenExpired(token)) {
loginWithRedirect();
return Promise.reject(new Error("token expired"));
}
return axios.post(url, data, { ...defaultOptions(), ...spreadOptions }); return axios.post(url, data, { ...defaultOptions(), ...spreadOptions });
} }
function del<T>(url: string, spreadOptions?: AxiosRequestConfig): Promise<AxiosResponse<T>> { 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 }); return axios.delete(url, { ...defaultOptions(), ...spreadOptions });
} }

View file

@ -5,7 +5,7 @@ import { makeStyles } from "@mui/styles";
import { LockOpen, Person, Lock, Settings, SupervisedUserCircle as TeamIcon, ExitToApp, PersonAdd } from "@mui/icons-material"; import { LockOpen, Person, Lock, Settings, SupervisedUserCircle as TeamIcon, ExitToApp, PersonAdd } from "@mui/icons-material";
import { useState } from "react"; import { useState } from "react";
import UserTeamName from "./UserTeamName"; import UserTeamName from "./UserTeamName";
import { useAuth0 } from "@auth0/auth0-react"; import { useAuthContext } from "providers/authContext";
import UserSettings from "./UserSettings"; import UserSettings from "./UserSettings";
import UserAvatar from "./UserAvatar"; import UserAvatar from "./UserAvatar";
import { purple } from "@mui/material/colors"; import { purple } from "@mui/material/colors";
@ -77,7 +77,7 @@ export default function UserMenu() {
// const { toggleMode } = useThemeMode() // const { toggleMode } = useThemeMode()
const [{ user, team, as }, dispatch] = useGlobalState(); const [{ user, team, as }, dispatch] = useGlobalState();
const { loginWithRedirect } = useAuth0(); const { loginWithRedirect } = useAuthContext();
const classes = useStyles(); const classes = useStyles();
const theme = useTheme(); const theme = useTheme();