Merge branch 'local_server' into dev_environment
This commit is contained in:
commit
7df21bd9e0
21 changed files with 496 additions and 88 deletions
61
deploy.sh
Executable file
61
deploy.sh
Executable file
|
|
@ -0,0 +1,61 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
# Load .env.local if it exists
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
ENV_FILE="$SCRIPT_DIR/.env.local"
|
||||||
|
|
||||||
|
if [[ -f "$ENV_FILE" ]]; then
|
||||||
|
# Export only the vars we care about, ignoring comments and blank lines
|
||||||
|
set -o allexport
|
||||||
|
# shellcheck source=/dev/null
|
||||||
|
source <(grep -E '^(DEPLOY_USER|DEPLOY_HOST|DEPLOY_SSH_KEY)=' "$ENV_FILE")
|
||||||
|
set +o allexport
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Prompt for any missing values
|
||||||
|
if [[ -z "${DEPLOY_USER:-}" ]]; then
|
||||||
|
read -rp "SSH username: " DEPLOY_USER
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -z "${DEPLOY_HOST:-}" ]]; then
|
||||||
|
read -rp "Server IP/hostname: " DEPLOY_HOST
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -z "${DEPLOY_SSH_KEY:-}" ]]; then
|
||||||
|
read -rp "SSH key path [~/.ssh/id_ed25519]: " DEPLOY_SSH_KEY
|
||||||
|
DEPLOY_SSH_KEY="${DEPLOY_SSH_KEY:-~/.ssh/id_ed25519}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
SSH_OPTS="-i $DEPLOY_SSH_KEY"
|
||||||
|
|
||||||
|
echo "→ Deploying to $DEPLOY_USER@$DEPLOY_HOST using key $DEPLOY_SSH_KEY"
|
||||||
|
|
||||||
|
# 1. Build frontend for LAN / self-contained hosts (indexLocal.html via vite --mode localnet)
|
||||||
|
(
|
||||||
|
cd "$SCRIPT_DIR"
|
||||||
|
npm run build:local
|
||||||
|
)
|
||||||
|
|
||||||
|
# Fail if the bundle still embeds Crisp (wrong vite mode or stale build/)
|
||||||
|
INDEX_HTML="$SCRIPT_DIR/build/index.html"
|
||||||
|
if [[ ! -f "$INDEX_HTML" ]]; then
|
||||||
|
echo "error: missing $INDEX_HTML after build:local" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 2. Build container image
|
||||||
|
docker build -t webui:local -f Dockerfile .
|
||||||
|
|
||||||
|
# 3. Transfer image
|
||||||
|
docker save webui:local | ssh $SSH_OPTS "$DEPLOY_USER@$DEPLOY_HOST" docker load
|
||||||
|
|
||||||
|
# 4. SCP compose file
|
||||||
|
scp $SSH_OPTS docker-compose.local.yml "$DEPLOY_USER@$DEPLOY_HOST:~/"
|
||||||
|
|
||||||
|
# 5. Deploy — then force service recreate. Swarm often keeps the old task when the tag stays
|
||||||
|
# webui:local after docker load, so without --force you still see the previous HTML/JS.
|
||||||
|
STACK_NAME="${LOCAL_DOCKER_STACK_NAME:-webui}"
|
||||||
|
SERVICE_NAME="${STACK_NAME}_webui"
|
||||||
|
ssh $SSH_OPTS "$DEPLOY_USER@$DEPLOY_HOST" \
|
||||||
|
"docker stack deploy -c docker-compose.local.yml $STACK_NAME && docker service update --force $SERVICE_NAME"
|
||||||
18
docker-compose.local.yml
Normal file
18
docker-compose.local.yml
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
version: "3.6"
|
||||||
|
|
||||||
|
services:
|
||||||
|
webui:
|
||||||
|
image: webui:local
|
||||||
|
ports:
|
||||||
|
- "8080:80"
|
||||||
|
stop_signal: SIGQUIT
|
||||||
|
deploy:
|
||||||
|
replicas: 1
|
||||||
|
update_config:
|
||||||
|
order: start-first
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "curl", "-f", "localhost:80/health"]
|
||||||
|
interval: 1m
|
||||||
|
timeout: 10s
|
||||||
|
retries: 3
|
||||||
|
start_period: 30s
|
||||||
16
indexLocal.html
Normal file
16
indexLocal.html
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
<!-- LAN / self-contained deploy shell: use with `vite --mode localnet` (e.g. build:local, start-local).
|
||||||
|
Minimal HTML, no third-party bootstraps that call the public internet (Crisp, etc.). -->
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/x-icon" id="favicon-link" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title id="title-id">Adaptive Dashboard</title>
|
||||||
|
<link rel="manifest" id="manifest-link" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/app/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
@ -5,7 +5,7 @@
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "VITE_AUTH0_CLIENT_ID=5pUCkl2SfogkWmM244UDcLEUOp8EFdHd VITE_AUTH0_AUDIENCE=api.brandxtech.ca VITE_APP_API_URL=https://api.brandxtech.ca/v1 VITE_APP_WS_URL=ws://api.brandxtech.ca/v1/live vite",
|
"start": "VITE_AUTH0_CLIENT_ID=5pUCkl2SfogkWmM244UDcLEUOp8EFdHd VITE_AUTH0_AUDIENCE=api.brandxtech.ca VITE_APP_API_URL=https://api.brandxtech.ca/v1 VITE_APP_WS_URL=ws://api.brandxtech.ca/v1/live vite",
|
||||||
"start-local": "VITE_AUTH0_CLIENT_ID=dzJTpqIeMA4Rwk4xujtwPbAO3TY32bM1 VITE_AUTH0_AUDIENCE=bxt-dev.api.adaptiveagriculture.ca VITE_APP_API_URL=http://localhost:50052/v1 VITE_APP_WS_URL=ws://localhost:50052/v1/live VITE_APP_BILLING_URL=http://localhost:50053/v1 VITE_APP_RECLUSE_URL=http://localhost:50054/v1 VITE_APP_GITLAB_URL=http://localhost:50055/v1 vite",
|
"start-local": "VITE_AUTH0_CLIENT_ID=dzJTpqIeMA4Rwk4xujtwPbAO3TY32bM1 VITE_AUTH0_AUDIENCE=bxt-dev.api.adaptiveagriculture.ca VITE_APP_API_URL=http://localhost:50052/v1 VITE_APP_WS_URL=ws://localhost:50052/v1/live VITE_APP_BILLING_URL=http://localhost:50053/v1 VITE_APP_RECLUSE_URL=http://localhost:50054/v1 VITE_APP_GITLAB_URL=http://localhost:50055/v1 vite --mode localnet",
|
||||||
"start-dev": "VITE_AUTH0_CLIENT_ID=dzJTpqIeMA4Rwk4xujtwPbAO3TY32bM1 VITE_APP_API_URL=https://bxt-dev.api.adaptiveagriculture.ca/v1 VITE_AUTH0_CLIENT_DOMAIN=brandxtech.auth0.com VITE_AUTH0_AUDIENCE=bxt-dev.api.adaptiveagriculture.ca VITE_AUTH0_DEV_CLIENT_ID=dzJTpqIeMA4Rwk4xujtwPbAO3TY32bM1 vite",
|
"start-dev": "VITE_AUTH0_CLIENT_ID=dzJTpqIeMA4Rwk4xujtwPbAO3TY32bM1 VITE_APP_API_URL=https://bxt-dev.api.adaptiveagriculture.ca/v1 VITE_AUTH0_CLIENT_DOMAIN=brandxtech.auth0.com VITE_AUTH0_AUDIENCE=bxt-dev.api.adaptiveagriculture.ca VITE_AUTH0_DEV_CLIENT_ID=dzJTpqIeMA4Rwk4xujtwPbAO3TY32bM1 vite",
|
||||||
"start-streamline": "VITE_AUTH0_CLIENT_ID=HwUV0hHNdVvU96zuMBTAU8i7nFdwwgIX VITE_APP_API_URL=https://streamline.api.adaptiveagriculture.ca/v1 VITE_AUTH0_CLIENT_DOMAIN=brandxtech.auth0.com VITE_AUTH0_AUDIENCE=streamline.api.adaptiveagriculture.ca vite",
|
"start-streamline": "VITE_AUTH0_CLIENT_ID=HwUV0hHNdVvU96zuMBTAU8i7nFdwwgIX VITE_APP_API_URL=https://streamline.api.adaptiveagriculture.ca/v1 VITE_AUTH0_CLIENT_DOMAIN=brandxtech.auth0.com VITE_AUTH0_AUDIENCE=streamline.api.adaptiveagriculture.ca vite",
|
||||||
"start-staging": "VITE_LOCAL_STAGING=true VITE_AUTH0_CLIENT_ID=3ib460VvLwdeyse5iUSQfxkVdQaUmphP VITE_AUTH0_AUDIENCE=stagingapi.brandxtech.ca VITE_AUTH0_CLIENT_DOMAIN=adaptivestaging.us.auth0.com VITE_APP_API_URL=https://stagingapi.brandxtech.ca/v1 VITE_APP_WS_URL=ws://stagingapi.brandxtech.ca/v1/live VITE_APP_AUTH0_CLIENT_DOMAIN=adaptivestaging.us.auth0.com VITE_APP_AUTH0_AUDIENCE=stagingapi.brandxtech.ca vite",
|
"start-staging": "VITE_LOCAL_STAGING=true VITE_AUTH0_CLIENT_ID=3ib460VvLwdeyse5iUSQfxkVdQaUmphP VITE_AUTH0_AUDIENCE=stagingapi.brandxtech.ca VITE_AUTH0_CLIENT_DOMAIN=adaptivestaging.us.auth0.com VITE_APP_API_URL=https://stagingapi.brandxtech.ca/v1 VITE_APP_WS_URL=ws://stagingapi.brandxtech.ca/v1/live VITE_APP_AUTH0_CLIENT_DOMAIN=adaptivestaging.us.auth0.com VITE_APP_AUTH0_AUDIENCE=stagingapi.brandxtech.ca vite",
|
||||||
|
|
@ -16,6 +16,7 @@
|
||||||
"build:development": "VITE_CRISP_WEBSITE_ID={CRISP_WEBSITE_ID} VITE_AUTH0_CLIENT_ID=dzJTpqIeMA4Rwk4xujtwPbAO3TY32bM1 VITE_AUTH0_AUDIENCE=bxt-dev.api.adaptiveagriculture.ca VITE_APP_API_URL=https://bxt-dev.api.adaptiveagriculture.ca/v1 NODE_OPTIONS=--max_old_space_size=4096 VITE_APP_GOOGLE_API_KEY=${GOOGLE_API_KEY} VITE_APP_STRIPE_PUBLIC_KEY=${STRIPE_PUBLIC_KEY_DEVELOPMENT} VITE_MAPBOX_ACCESS_TOKEN=${MAPBOX_ACCESS_TOKEN} VITE_CNHI_CLIENT_ID=${CNHI_CLIENT_ID} VITE_CNHI_AUTHORIZE_URL=${CNHI_AUTHORIZE_URL} VITE_CNHI_REDIRECT_URI=${CNHI_REDIRECT_URI} VITE_CNHI_SCOPES=${CNHI_SCOPES} VITE_CNHI_CONNECTION=${CNHI_CONNECTION} VITE_CNHI_AUDIENCE=${CNHI_AUDIENCE} VITE_APP_IMAGE4IO_USERNAME=${IMAGE4IO_USERNAME} VITE_APP_IMAGE4IO_PASSWORD=${IMAGE4IO_PASSWORD} VITE_JD_CLIENT_ID=${JD_CLIENT_ID} VITE_JD_AUTHORIZE_URL=${JD_AUTHORIZE_URL} VITE_JD_REDIRECT_URI=${JD_REDIRECT_URI} VITE_JD_SCOPES=${JD_SCOPES} VITE_JD_STATE=${JD_STATE} VITE_OPEN_WEATHERMAP=${OPEN_WEATHERMAP} vite build",
|
"build:development": "VITE_CRISP_WEBSITE_ID={CRISP_WEBSITE_ID} VITE_AUTH0_CLIENT_ID=dzJTpqIeMA4Rwk4xujtwPbAO3TY32bM1 VITE_AUTH0_AUDIENCE=bxt-dev.api.adaptiveagriculture.ca VITE_APP_API_URL=https://bxt-dev.api.adaptiveagriculture.ca/v1 NODE_OPTIONS=--max_old_space_size=4096 VITE_APP_GOOGLE_API_KEY=${GOOGLE_API_KEY} VITE_APP_STRIPE_PUBLIC_KEY=${STRIPE_PUBLIC_KEY_DEVELOPMENT} VITE_MAPBOX_ACCESS_TOKEN=${MAPBOX_ACCESS_TOKEN} VITE_CNHI_CLIENT_ID=${CNHI_CLIENT_ID} VITE_CNHI_AUTHORIZE_URL=${CNHI_AUTHORIZE_URL} VITE_CNHI_REDIRECT_URI=${CNHI_REDIRECT_URI} VITE_CNHI_SCOPES=${CNHI_SCOPES} VITE_CNHI_CONNECTION=${CNHI_CONNECTION} VITE_CNHI_AUDIENCE=${CNHI_AUDIENCE} VITE_APP_IMAGE4IO_USERNAME=${IMAGE4IO_USERNAME} VITE_APP_IMAGE4IO_PASSWORD=${IMAGE4IO_PASSWORD} VITE_JD_CLIENT_ID=${JD_CLIENT_ID} VITE_JD_AUTHORIZE_URL=${JD_AUTHORIZE_URL} VITE_JD_REDIRECT_URI=${JD_REDIRECT_URI} VITE_JD_SCOPES=${JD_SCOPES} VITE_JD_STATE=${JD_STATE} VITE_OPEN_WEATHERMAP=${OPEN_WEATHERMAP} vite build",
|
||||||
"build:production": "VITE_CRISP_WEBSITE_ID={CRISP_WEBSITE_ID} VITE_AUTH0_CLIENT_ID=5pUCkl2SfogkWmM244UDcLEUOp8EFdHd VITE_AUTH0_CLIENT_DOMAIN=brandxtech.auth0.com VITE_AUTH0_AUDIENCE=api.brandxtech.ca VITE_APP_API_URL=https://api.brandxtech.ca/v1 NODE_OPTIONS=--max_old_space_size=4096 VITE_APP_GOOGLE_API_KEY=${GOOGLE_API_KEY} VITE_APP_STRIPE_PUBLIC_KEY=${STRIPE_PUBLIC_KEY_PRODUCTION} VITE_MAPBOX_ACCESS_TOKEN=${MAPBOX_ACCESS_TOKEN} VITE_CNHI_CLIENT_ID=${CNHI_CLIENT_ID} VITE_CNHI_AUTHORIZE_URL=${CNHI_AUTHORIZE_URL} VITE_CNHI_REDIRECT_URI=${CNHI_REDIRECT_URI} VITE_CNHI_SCOPES=${CNHI_SCOPES} VITE_CNHI_CONNECTION=${CNHI_CONNECTION} VITE_CNHI_AUDIENCE=${CNHI_AUDIENCE} VITE_APP_IMAGE4IO_USERNAME=${IMAGE4IO_USERNAME} VITE_APP_IMAGE4IO_PASSWORD=${IMAGE4IO_PASSWORD} VITE_JD_CLIENT_ID=${JD_CLIENT_ID} VITE_JD_AUTHORIZE_URL=${JD_AUTHORIZE_URL} VITE_JD_REDIRECT_URI=${JD_REDIRECT_URI} VITE_JD_SCOPES=${JD_SCOPES} VITE_JD_STATE=${JD_STATE} VITE_OPEN_WEATHERMAP=${OPEN_WEATHERMAP} vite build",
|
"build:production": "VITE_CRISP_WEBSITE_ID={CRISP_WEBSITE_ID} VITE_AUTH0_CLIENT_ID=5pUCkl2SfogkWmM244UDcLEUOp8EFdHd VITE_AUTH0_CLIENT_DOMAIN=brandxtech.auth0.com VITE_AUTH0_AUDIENCE=api.brandxtech.ca VITE_APP_API_URL=https://api.brandxtech.ca/v1 NODE_OPTIONS=--max_old_space_size=4096 VITE_APP_GOOGLE_API_KEY=${GOOGLE_API_KEY} VITE_APP_STRIPE_PUBLIC_KEY=${STRIPE_PUBLIC_KEY_PRODUCTION} VITE_MAPBOX_ACCESS_TOKEN=${MAPBOX_ACCESS_TOKEN} VITE_CNHI_CLIENT_ID=${CNHI_CLIENT_ID} VITE_CNHI_AUTHORIZE_URL=${CNHI_AUTHORIZE_URL} VITE_CNHI_REDIRECT_URI=${CNHI_REDIRECT_URI} VITE_CNHI_SCOPES=${CNHI_SCOPES} VITE_CNHI_CONNECTION=${CNHI_CONNECTION} VITE_CNHI_AUDIENCE=${CNHI_AUDIENCE} VITE_APP_IMAGE4IO_USERNAME=${IMAGE4IO_USERNAME} VITE_APP_IMAGE4IO_PASSWORD=${IMAGE4IO_PASSWORD} VITE_JD_CLIENT_ID=${JD_CLIENT_ID} VITE_JD_AUTHORIZE_URL=${JD_AUTHORIZE_URL} VITE_JD_REDIRECT_URI=${JD_REDIRECT_URI} VITE_JD_SCOPES=${JD_SCOPES} VITE_JD_STATE=${JD_STATE} VITE_OPEN_WEATHERMAP=${OPEN_WEATHERMAP} vite build",
|
||||||
"build:streamline": "VITE_CRISP_WEBSITE_ID={CRISP_WEBSITE_ID} VITE_AUTH0_CLIENT_ID=HwUV0hHNdVvU96zuMBTAU8i7nFdwwgIX VITE_AUTH0_CLIENT_DOMAIN=brandxtech.auth0.com VITE_AUTH0_AUDIENCE=streamline.api.adaptiveagriculture.ca VITE_APP_API_URL=https://streamline.api.adaptiveagriculture.ca/v1 NODE_OPTIONS=--max_old_space_size=4096 VITE_APP_GOOGLE_API_KEY=${GOOGLE_API_KEY} VITE_APP_STRIPE_PUBLIC_KEY=${STRIPE_PUBLIC_KEY_PRODUCTION} VITE_MAPBOX_ACCESS_TOKEN=${MAPBOX_ACCESS_TOKEN} VITE_CNHI_CLIENT_ID=${CNHI_CLIENT_ID} VITE_CNHI_AUTHORIZE_URL=${CNHI_AUTHORIZE_URL} VITE_CNHI_REDIRECT_URI=${CNHI_REDIRECT_URI} VITE_CNHI_SCOPES=${CNHI_SCOPES} VITE_CNHI_CONNECTION=${CNHI_CONNECTION} VITE_CNHI_AUDIENCE=${CNHI_AUDIENCE} VITE_APP_IMAGE4IO_USERNAME=${IMAGE4IO_USERNAME} VITE_APP_IMAGE4IO_PASSWORD=${IMAGE4IO_PASSWORD} VITE_JD_CLIENT_ID=${JD_CLIENT_ID} VITE_JD_AUTHORIZE_URL=${JD_AUTHORIZE_URL} VITE_JD_REDIRECT_URI=${JD_REDIRECT_URI} VITE_JD_SCOPES=${JD_SCOPES} VITE_JD_STATE=${JD_STATE} VITE_OPEN_WEATHERMAP=${OPEN_WEATHERMAP} vite build",
|
"build:streamline": "VITE_CRISP_WEBSITE_ID={CRISP_WEBSITE_ID} VITE_AUTH0_CLIENT_ID=HwUV0hHNdVvU96zuMBTAU8i7nFdwwgIX VITE_AUTH0_CLIENT_DOMAIN=brandxtech.auth0.com VITE_AUTH0_AUDIENCE=streamline.api.adaptiveagriculture.ca VITE_APP_API_URL=https://streamline.api.adaptiveagriculture.ca/v1 NODE_OPTIONS=--max_old_space_size=4096 VITE_APP_GOOGLE_API_KEY=${GOOGLE_API_KEY} VITE_APP_STRIPE_PUBLIC_KEY=${STRIPE_PUBLIC_KEY_PRODUCTION} VITE_MAPBOX_ACCESS_TOKEN=${MAPBOX_ACCESS_TOKEN} VITE_CNHI_CLIENT_ID=${CNHI_CLIENT_ID} VITE_CNHI_AUTHORIZE_URL=${CNHI_AUTHORIZE_URL} VITE_CNHI_REDIRECT_URI=${CNHI_REDIRECT_URI} VITE_CNHI_SCOPES=${CNHI_SCOPES} VITE_CNHI_CONNECTION=${CNHI_CONNECTION} VITE_CNHI_AUDIENCE=${CNHI_AUDIENCE} VITE_APP_IMAGE4IO_USERNAME=${IMAGE4IO_USERNAME} VITE_APP_IMAGE4IO_PASSWORD=${IMAGE4IO_PASSWORD} VITE_JD_CLIENT_ID=${JD_CLIENT_ID} VITE_JD_AUTHORIZE_URL=${JD_AUTHORIZE_URL} VITE_JD_REDIRECT_URI=${JD_REDIRECT_URI} VITE_JD_SCOPES=${JD_SCOPES} VITE_JD_STATE=${JD_STATE} VITE_OPEN_WEATHERMAP=${OPEN_WEATHERMAP} vite build",
|
||||||
|
"build:local": "VITE_AUTH0_CLIENT_ID=local VITE_AUTH0_AUDIENCE=local VITE_AUTH0_CLIENT_DOMAIN=local VITE_APP_API_URL=http://172.16.1.20:50052/v1 VITE_APP_WS_URL=ws://172.16.1.20:50052/v1/live NODE_OPTIONS=--max_old_space_size=4096 vite build --mode localnet",
|
||||||
"build:offline": "npx env-cmd offline,whitelabel npm run build",
|
"build:offline": "npx env-cmd offline,whitelabel npm run build",
|
||||||
"test": "vitest"
|
"test": "vitest"
|
||||||
},
|
},
|
||||||
|
|
|
||||||
|
|
@ -1,15 +1,20 @@
|
||||||
import { Auth0Provider } from '@auth0/auth0-react'
|
import { Auth0Provider } from '@auth0/auth0-react'
|
||||||
import { or } from '../utils/types'
|
import { or } from '../utils/types'
|
||||||
|
import { isAuth0Configured, isAuth0SpaOriginAllowed, shouldMountAuth0Provider } from '../utils/auth0Config'
|
||||||
import AuthWrapper from '../providers/auth'
|
import AuthWrapper from '../providers/auth'
|
||||||
import HTTPProvider from 'providers/http'
|
import HTTPProvider from 'providers/http'
|
||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import LoadingScreen from './LoadingScreen'
|
import LoadingScreen from './LoadingScreen'
|
||||||
|
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"
|
||||||
|
|
@ -54,6 +59,29 @@ function App() {
|
||||||
"/libracart"
|
"/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 (
|
return (
|
||||||
<AppThemeProvider>
|
<AppThemeProvider>
|
||||||
<Auth0Provider
|
<Auth0Provider
|
||||||
|
|
@ -70,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'
|
||||||
|
|
|
||||||
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 { 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'
|
||||||
|
|
@ -12,9 +11,8 @@ import { makeStyles } from '@mui/styles'
|
||||||
import { CssBaseline, Theme } from '@mui/material'
|
import { CssBaseline, Theme } from '@mui/material'
|
||||||
import { AppThemeProvider } from 'theme/AppThemeProvider'
|
import { AppThemeProvider } from 'theme/AppThemeProvider'
|
||||||
import HTTPProvider from 'providers/http'
|
import HTTPProvider from 'providers/http'
|
||||||
import { Crisp } from "crisp-sdk-web";
|
|
||||||
import { useMobile, useSnackbar } from 'hooks'
|
import { useMobile, useSnackbar } from 'hooks'
|
||||||
import { initCrisp } from '../chat/CrispChat'
|
import { initCrisp, isCrispEnabled } from '../chat/CrispChat'
|
||||||
// import FirmwareLoader from './FirmwareLoader'
|
// import FirmwareLoader from './FirmwareLoader'
|
||||||
|
|
||||||
const reducer = (state: GlobalState, action: GlobalStateAction): GlobalState => {
|
const reducer = (state: GlobalState, action: GlobalStateAction): GlobalState => {
|
||||||
|
|
@ -34,7 +32,7 @@ const useStyles = makeStyles((theme: Theme) => ({
|
||||||
paddingBottom: 0,
|
paddingBottom: 0,
|
||||||
},
|
},
|
||||||
[theme.breakpoints.up("md")]: {
|
[theme.breakpoints.up("md")]: {
|
||||||
paddingLeft: theme.spacing(9)
|
paddingLeft: theme.spacing(8)
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
container: {
|
container: {
|
||||||
|
|
@ -64,16 +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 crispInitialized = useRef(false);
|
const payload = JSON.parse(atob(token.split('.')[1]))
|
||||||
Crisp.configure(import.meta.env.VITE_CRISP_WEBSITE_ID);
|
return or(payload.sub, '')
|
||||||
|
} catch {
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
})()
|
||||||
|
|
||||||
const loadUser = useCallback(() => {
|
const loadUser = useCallback(() => {
|
||||||
if (!userAPI.getUserWithTeam) return;
|
if (!userAPI.getUserWithTeam) return;
|
||||||
|
|
@ -114,15 +115,14 @@ export default function UserWrapper(props: Props) {
|
||||||
}, [setGlobal])
|
}, [setGlobal])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (global?.user) {
|
if (!global?.user || !isCrispEnabled()) return;
|
||||||
initCrisp({
|
initCrisp({
|
||||||
websiteId: import.meta.env.VITE_CRISP_WEBSITE_ID,
|
websiteId: import.meta.env.VITE_CRISP_WEBSITE_ID,
|
||||||
email: global.user.settings.email,
|
email: global.user.settings.email,
|
||||||
nickname: global.user.settings.name || global.user.settings.email,
|
nickname: global.user.settings.name || global.user.settings.email,
|
||||||
phone: global.user.settings.phoneNumber,
|
phone: global.user.settings.phoneNumber,
|
||||||
tokenId: global.user.id(),
|
tokenId: global.user.id(),
|
||||||
});
|
});
|
||||||
}
|
|
||||||
}, [global]);
|
}, [global]);
|
||||||
|
|
||||||
// useEffect(() => {
|
// useEffect(() => {
|
||||||
|
|
@ -150,6 +150,7 @@ export default function UserWrapper(props: Props) {
|
||||||
// }, [isMobile]);
|
// }, [isMobile]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (!isCrispEnabled()) return;
|
||||||
let style = document.getElementById("crisp-offset-override");
|
let style = document.getElementById("crisp-offset-override");
|
||||||
if (!style) {
|
if (!style) {
|
||||||
style = document.createElement("style");
|
style = document.createElement("style");
|
||||||
|
|
|
||||||
|
|
@ -28,6 +28,7 @@ const useStyles = makeStyles((theme: Theme) => {
|
||||||
position: "fixed",
|
position: "fixed",
|
||||||
bottom: theme.spacing(8), //for mobile navigator
|
bottom: theme.spacing(8), //for mobile navigator
|
||||||
right: theme.spacing(2),
|
right: theme.spacing(2),
|
||||||
|
zIndex: theme.zIndex.speedDial,
|
||||||
[theme.breakpoints.up("sm")]: {
|
[theme.breakpoints.up("sm")]: {
|
||||||
bottom: theme.spacing(1.75)
|
bottom: theme.spacing(1.75)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ import Chat from "./Chat";
|
||||||
import { pond } from "protobuf-ts/pond";
|
import { pond } from "protobuf-ts/pond";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { useTeamAPI } from "providers";
|
import { useTeamAPI } from "providers";
|
||||||
import { closeCrispChat, openCrispChat } from './CrispChat';
|
import { closeCrispChat, isCrispEnabled, openCrispChat } from './CrispChat';
|
||||||
import RobotIcon from "products/CommonIcons/robotIcon";
|
import RobotIcon from "products/CommonIcons/robotIcon";
|
||||||
|
|
||||||
const useStyles = makeStyles<Theme>((theme: Theme) => ({
|
const useStyles = makeStyles<Theme>((theme: Theme) => ({
|
||||||
|
|
@ -68,7 +68,7 @@ export function ChatDrawer(props: Props) {
|
||||||
}
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (open) {
|
if (open && isCrispEnabled()) {
|
||||||
closeCrispChat()
|
closeCrispChat()
|
||||||
}
|
}
|
||||||
}, [open])
|
}, [open])
|
||||||
|
|
@ -108,13 +108,15 @@ export function ChatDrawer(props: Props) {
|
||||||
<Avatar src={team.settings.avatar} />
|
<Avatar src={team.settings.avatar} />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
<Tooltip title={"Chat Assistant"} placement="right">
|
{isCrispEnabled() && (
|
||||||
<IconButton
|
<Tooltip title={"Chat Assistant"} placement="right">
|
||||||
onClick={openCrisp}
|
<IconButton
|
||||||
>
|
onClick={openCrisp}
|
||||||
<RobotIcon />
|
>
|
||||||
</IconButton>
|
<RobotIcon />
|
||||||
</Tooltip>
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
<Box width={"100%"} borderBottom={"1px solid grey"} />
|
<Box width={"100%"} borderBottom={"1px solid grey"} />
|
||||||
{teams.map((t, i)=> {
|
{teams.map((t, i)=> {
|
||||||
if (t.settings?.key === team.key()) return null;
|
if (t.settings?.key === team.key()) return null;
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,11 @@ const ANIMATION_DURATION_MS = 300;
|
||||||
|
|
||||||
let initialized = false;
|
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.
|
* Initialize Crisp and immediately hide the default chat button.
|
||||||
* Call this once on app load (e.g., in UserWrapper after user data is ready).
|
* 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;
|
tokenId?: string;
|
||||||
}) {
|
}) {
|
||||||
if (initialized) return;
|
if (initialized) return;
|
||||||
|
if (!opts.websiteId?.trim()) return;
|
||||||
|
|
||||||
Crisp.configure(opts.websiteId);
|
Crisp.configure(opts.websiteId);
|
||||||
Crisp.session.reset();
|
Crisp.session.reset();
|
||||||
|
|
@ -71,6 +77,7 @@ function injectCrispStyles() {
|
||||||
* Safe to call from any onClick handler.
|
* Safe to call from any onClick handler.
|
||||||
*/
|
*/
|
||||||
export function openCrispChat() {
|
export function openCrispChat() {
|
||||||
|
if (!initialized) return;
|
||||||
const chatbox = document.getElementById("crisp-chatbox");
|
const chatbox = document.getElementById("crisp-chatbox");
|
||||||
if (chatbox) {
|
if (chatbox) {
|
||||||
chatbox.classList.add("crisp-visible");
|
chatbox.classList.add("crisp-visible");
|
||||||
|
|
@ -86,6 +93,7 @@ export function openCrispChat() {
|
||||||
* Close the chat window and hide the widget.
|
* Close the chat window and hide the widget.
|
||||||
*/
|
*/
|
||||||
export function closeCrispChat() {
|
export function closeCrispChat() {
|
||||||
|
if (!initialized) return;
|
||||||
Crisp.chat.close();
|
Crisp.chat.close();
|
||||||
hideCrispChatButton();
|
hideCrispChatButton();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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();
|
||||||
|
|
|
||||||
|
|
@ -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>;
|
||||||
|
|
|
||||||
|
|
@ -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";
|
||||||
|
|
@ -53,6 +53,7 @@ import CNHiIcon from "products/CommonIcons/cnhiIcon";
|
||||||
import LibraCartIcon from "products/CommonIcons/libracartIcon";
|
import LibraCartIcon from "products/CommonIcons/libracartIcon";
|
||||||
|
|
||||||
const drawerWidth = 230;
|
const drawerWidth = 230;
|
||||||
|
const closedDrawerWidth = 8;
|
||||||
|
|
||||||
const useStyles = makeStyles((theme: Theme) => ({
|
const useStyles = makeStyles((theme: Theme) => ({
|
||||||
sideMenu: {
|
sideMenu: {
|
||||||
|
|
@ -66,6 +67,8 @@ const useStyles = makeStyles((theme: Theme) => ({
|
||||||
sideMenuOpened: {
|
sideMenuOpened: {
|
||||||
zIndex: theme.zIndex.drawer + 2,
|
zIndex: theme.zIndex.drawer + 2,
|
||||||
width: drawerWidth,
|
width: drawerWidth,
|
||||||
|
minWidth: drawerWidth,
|
||||||
|
maxWidth: drawerWidth,
|
||||||
transition: theme.transitions.create(["width"], {
|
transition: theme.transitions.create(["width"], {
|
||||||
easing: theme.transitions.easing.sharp,
|
easing: theme.transitions.easing.sharp,
|
||||||
duration: theme.transitions.duration.enteringScreen
|
duration: theme.transitions.duration.enteringScreen
|
||||||
|
|
@ -76,12 +79,16 @@ const useStyles = makeStyles((theme: Theme) => ({
|
||||||
easing: theme.transitions.easing.sharp,
|
easing: theme.transitions.easing.sharp,
|
||||||
duration: theme.transitions.duration.leavingScreen
|
duration: theme.transitions.duration.leavingScreen
|
||||||
}),
|
}),
|
||||||
// overflowX: "hidden",
|
overflowX: "hidden",
|
||||||
width: theme.spacing(0),
|
width: theme.spacing(0),
|
||||||
|
minWidth: theme.spacing(0),
|
||||||
|
maxWidth: theme.spacing(0),
|
||||||
// zIndex: theme.zIndex.drawer,
|
// zIndex: theme.zIndex.drawer,
|
||||||
// opacity: 0,
|
// opacity: 0,
|
||||||
[theme.breakpoints.up("md")]: {
|
[theme.breakpoints.up("md")]: {
|
||||||
width: theme.spacing(9.25),
|
width: theme.spacing(closedDrawerWidth),
|
||||||
|
minWidth: theme.spacing(closedDrawerWidth),
|
||||||
|
maxWidth: theme.spacing(closedDrawerWidth),
|
||||||
opacity: 1
|
opacity: 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
@ -130,7 +137,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();
|
||||||
|
|
@ -538,11 +545,16 @@ export default function SideNavigator(props: Props) {
|
||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
sx={{ pointerEvents: isMobile&&!open ? "none" : "auto"}}
|
sx={{ pointerEvents: isMobile&&!open ? "none" : "auto"}}
|
||||||
>
|
>
|
||||||
<Toolbar >
|
<Toolbar>
|
||||||
<Grid container direction="row" justifyContent={"flex-end"}>
|
<Grid container direction="row" justifyContent={"flex-end"}>
|
||||||
<Grid>
|
<Grid>
|
||||||
<IconButton onClick={onClose} aria-label="onClose side menu">
|
<IconButton
|
||||||
{theme.direction === "rtl" ? <ChevronRight /> : <ChevronLeft />}
|
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>
|
</IconButton>
|
||||||
</Grid>
|
</Grid>
|
||||||
</Grid>
|
</Grid>
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,11 @@
|
||||||
import { RedirectLoginOptions, useAuth0 } from "@auth0/auth0-react";
|
import { RedirectLoginOptions } from "@auth0/auth0-react";
|
||||||
// import { useAuth } from "hooks";
|
// import { useAuth } from "hooks";
|
||||||
import queryString from "query-string";
|
import queryString from "query-string";
|
||||||
import { useEffect } from "react";
|
import { useEffect } from "react";
|
||||||
import { useLocation } from "react-router";
|
import { useLocation } from "react-router";
|
||||||
// import Loading from "./Loading";
|
// import Loading from "./Loading";
|
||||||
import LoadingScreen from "app/LoadingScreen";
|
import LoadingScreen from "app/LoadingScreen";
|
||||||
|
import { useAuthContext } from "providers/authContext";
|
||||||
|
|
||||||
// interface Props {
|
// interface Props {
|
||||||
// prevPath?: string;
|
// prevPath?: string;
|
||||||
|
|
@ -13,7 +14,7 @@ import LoadingScreen from "app/LoadingScreen";
|
||||||
export default function Login() {
|
export default function Login() {
|
||||||
// const { prevPath } = props;
|
// const { prevPath } = props;
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const { loginWithRedirect } = useAuth0();
|
const { loginWithRedirect } = useAuthContext();
|
||||||
|
|
||||||
// const setRouteBeforeLogin = useCallback((): Promise<string> => {
|
// const setRouteBeforeLogin = useCallback((): Promise<string> => {
|
||||||
// return new Promise(function(resolve) {
|
// 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 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();
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { useAuth0 } from '@auth0/auth0-react';
|
import { useAuthContext } from './authContext';
|
||||||
|
|
||||||
const LoginButton = () => {
|
const LoginButton = () => {
|
||||||
const { loginWithRedirect } = useAuth0();
|
const { loginWithRedirect } = useAuthContext();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button onClick={() => loginWithRedirect()}>
|
<button onClick={() => loginWithRedirect()}>
|
||||||
|
|
|
||||||
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 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 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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();
|
||||||
|
|
||||||
|
|
|
||||||
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()
|
||||||
|
}
|
||||||
|
|
@ -1,12 +1,58 @@
|
||||||
import { defineConfig } from 'vite'
|
import { defineConfig, type Plugin, type UserConfig } from 'vite'
|
||||||
import react from '@vitejs/plugin-react'
|
import react from '@vitejs/plugin-react'
|
||||||
import tsconfigPaths from 'vite-tsconfig-paths'
|
import tsconfigPaths from 'vite-tsconfig-paths'
|
||||||
import { VitePWA } from 'vite-plugin-pwa';
|
import { VitePWA } from 'vite-plugin-pwa';
|
||||||
import * as path from 'path' // ✅ Import path module
|
import * as path from 'path' // ✅ Import path module
|
||||||
|
import { readFileSync, renameSync, existsSync, unlinkSync } from 'node:fs'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
|
||||||
|
const rootDir = path.dirname(fileURLToPath(import.meta.url))
|
||||||
|
|
||||||
|
const LOCALNET_MODE = 'localnet'
|
||||||
|
|
||||||
|
/** Dev server: serve the minimal LAN shell (indexLocal.html) instead of the full index with third-party bootstraps. */
|
||||||
|
function useLocalnetShellHtml (mode: string, command: string): Plugin {
|
||||||
|
if (mode !== LOCALNET_MODE || command !== 'serve') {
|
||||||
|
return { name: 'localnet-shell-html-noop' }
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
name: 'localnet-shell-html',
|
||||||
|
apply: 'serve',
|
||||||
|
transformIndexHtml: {
|
||||||
|
order: 'pre',
|
||||||
|
handler () {
|
||||||
|
return readFileSync(path.join(rootDir, 'indexLocal.html'), 'utf-8')
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** After build, LAN shell is emitted as indexLocal.html; rename to index.html so nginx and PWA still use /. */
|
||||||
|
function emitLocalnetShellAsIndexHtml (mode: string): Plugin {
|
||||||
|
if (mode !== LOCALNET_MODE) {
|
||||||
|
return { name: 'emit-localnet-shell-as-index-noop' }
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
name: 'emit-localnet-shell-as-index-html',
|
||||||
|
closeBundle () {
|
||||||
|
const outDir = path.join(rootDir, 'build')
|
||||||
|
const from = path.join(outDir, 'indexLocal.html')
|
||||||
|
const to = path.join(outDir, 'index.html')
|
||||||
|
if (existsSync(from)) {
|
||||||
|
if (existsSync(to)) unlinkSync(to)
|
||||||
|
renameSync(from, to)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// https://vitejs.dev/config/
|
// https://vitejs.dev/config/
|
||||||
export default defineConfig({
|
export default defineConfig(({ command, mode }): UserConfig => {
|
||||||
|
const useLocalnetShell = mode === LOCALNET_MODE
|
||||||
|
return {
|
||||||
plugins: [
|
plugins: [
|
||||||
|
useLocalnetShellHtml(mode, command),
|
||||||
|
emitLocalnetShellAsIndexHtml(mode),
|
||||||
react(),
|
react(),
|
||||||
tsconfigPaths(),
|
tsconfigPaths(),
|
||||||
VitePWA({
|
VitePWA({
|
||||||
|
|
@ -53,12 +99,15 @@ export default defineConfig({
|
||||||
target: 'esnext',
|
target: 'esnext',
|
||||||
rollupOptions: {
|
rollupOptions: {
|
||||||
input: {
|
input: {
|
||||||
main: path.resolve(__dirname, 'index.html')
|
main: path.join(
|
||||||
}
|
rootDir,
|
||||||
|
useLocalnetShell ? 'indexLocal.html' : 'index.html'
|
||||||
|
),
|
||||||
|
},
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
esbuild: {
|
esbuild: {
|
||||||
keepNames: true, // Prevent function name mangling
|
keepNames: true, // Prevent function name mangling
|
||||||
},
|
},
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue