fix: align auth client basePath with server config
fix: align auth client basePath with server config
This commit is contained in:
@@ -11,6 +11,7 @@ node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
.env
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
|
||||
@@ -12,6 +12,7 @@ CartSnitch is a self-hosted grocery price intelligence platform. This repo (`car
|
||||
| Directory | Service | Purpose |
|
||||
|-----------|---------|---------|
|
||||
| `/` (root) | Frontend | React PWA, mobile-first (this directory) |
|
||||
| `auth/` | Auth | Better-Auth Node.js service (session management, email/password, OAuth) |
|
||||
| `api/` | API Gateway | Frontend-facing REST API |
|
||||
| `common/` | Common | Shared Python models, schemas, Alembic migrations |
|
||||
| `receiptwitness/` | ReceiptWitness | Purchase data ingestion via retailer scrapers |
|
||||
@@ -166,9 +167,13 @@ frontend/
|
||||
|
||||
All data comes from the CartSnitch API gateway (`cartsnitch/api`). Base URL configured via environment variable `VITE_API_URL`.
|
||||
|
||||
- JWT auth: store access token in memory (not localStorage), refresh token in httpOnly cookie if possible, or secure storage.
|
||||
- **Authentication via Better-Auth** (`auth/` service). Sessions are managed via httpOnly cookies — no tokens in localStorage or memory.
|
||||
- Auth service URL configured via `VITE_AUTH_URL` (default: `http://localhost:3001`)
|
||||
- Frontend uses `better-auth/react` client for sign-in, sign-up, sign-out, and `useSession()` hook
|
||||
- API gateway validates sessions by querying the shared `sessions` table in Postgres
|
||||
- Both cookie-based and Bearer token auth are supported (cookies for web, Bearer for API clients)
|
||||
- TanStack Query handles caching, background refetching, and optimistic updates.
|
||||
- API client should handle 401 responses by attempting token refresh before retrying.
|
||||
- API client sends `credentials: 'include'` on all requests to forward session cookies.
|
||||
|
||||
## Development Workflow
|
||||
|
||||
|
||||
Generated
+469
-185
File diff suppressed because it is too large
Load Diff
@@ -13,6 +13,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.0.0",
|
||||
"better-auth": "^1.2.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router-dom": "^7.0.0",
|
||||
|
||||
+7
-1
@@ -1,7 +1,13 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import App from './App.tsx'
|
||||
|
||||
vi.mock('./lib/auth-client.ts', () => ({
|
||||
authClient: {
|
||||
useSession: () => ({ data: null, isPending: false }),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('App', () => {
|
||||
it('renders the dashboard on the root route', () => {
|
||||
render(<App />)
|
||||
|
||||
@@ -1,10 +1,25 @@
|
||||
import { useEffect } from 'react'
|
||||
import { Navigate, Outlet } from 'react-router-dom'
|
||||
import { authClient } from '../lib/auth-client.ts'
|
||||
import { useAuthStore } from '../stores/auth.ts'
|
||||
|
||||
export function ProtectedRoute() {
|
||||
const isAuthenticated = useAuthStore((s) => s.isAuthenticated)
|
||||
const { data: session, isPending } = authClient.useSession()
|
||||
const setAuthenticated = useAuthStore((s) => s.setAuthenticated)
|
||||
|
||||
if (!isAuthenticated) {
|
||||
useEffect(() => {
|
||||
setAuthenticated(!!session)
|
||||
}, [session, setAuthenticated])
|
||||
|
||||
if (isPending) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-2 border-brand-blue border-t-transparent" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!session) {
|
||||
return <Navigate to="/login" replace />
|
||||
}
|
||||
|
||||
|
||||
+98
-100
@@ -1,100 +1,98 @@
|
||||
import { useAuthStore } from '../stores/auth.ts'
|
||||
import {
|
||||
mockPurchases,
|
||||
mockProducts,
|
||||
mockCoupons,
|
||||
mockAlerts,
|
||||
getMockPriceHistory,
|
||||
} from './mock-data.ts'
|
||||
|
||||
const API_BASE = import.meta.env.VITE_API_URL ?? '/api/v1'
|
||||
const USE_MOCK = import.meta.env.VITE_MOCK_API === 'true'
|
||||
|
||||
// Mock response lookup table
|
||||
const mockRoutes: Record<string, (path: string) => unknown> = {
|
||||
'/purchases': () => mockPurchases,
|
||||
'/products': () => mockProducts,
|
||||
'/coupons': () => mockCoupons,
|
||||
'/price-alerts': () => mockAlerts,
|
||||
}
|
||||
|
||||
function matchMockRoute<T>(path: string): T | null {
|
||||
// Exact match
|
||||
if (mockRoutes[path]) return mockRoutes[path](path) as T
|
||||
|
||||
// /purchases/:id
|
||||
const purchaseMatch = path.match(/^\/purchases\/(.+)$/)
|
||||
if (purchaseMatch) {
|
||||
const purchase = mockPurchases.find((p) => p.id === purchaseMatch[1])
|
||||
return (purchase ?? null) as T
|
||||
}
|
||||
|
||||
// /products/:id/price-history
|
||||
const priceHistoryMatch = path.match(/^\/products\/(.+)\/price-history$/)
|
||||
if (priceHistoryMatch) {
|
||||
return getMockPriceHistory(priceHistoryMatch[1]) as T
|
||||
}
|
||||
|
||||
// /products?q=search or /products/:id
|
||||
const productMatch = path.match(/^\/products\/(.+)$/)
|
||||
if (productMatch) {
|
||||
const product = mockProducts.find((p) => p.id === productMatch[1])
|
||||
return (product ?? null) as T
|
||||
}
|
||||
|
||||
const productsSearch = path.match(/^\/products\?q=(.+)$/)
|
||||
if (productsSearch) {
|
||||
const q = decodeURIComponent(productsSearch[1]).toLowerCase()
|
||||
return mockProducts.filter(
|
||||
(p) =>
|
||||
p.name.toLowerCase().includes(q) ||
|
||||
p.brand.toLowerCase().includes(q) ||
|
||||
p.category.toLowerCase().includes(q),
|
||||
) as T
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
async function apiFetch<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
// Mock interceptor: return mock data without hitting the network
|
||||
if (USE_MOCK && (!options?.method || options.method === 'GET')) {
|
||||
const mockResult = matchMockRoute<T>(path)
|
||||
if (mockResult !== null) {
|
||||
// Simulate network delay for realistic loading states
|
||||
await new Promise((r) => setTimeout(r, 300))
|
||||
return mockResult
|
||||
}
|
||||
}
|
||||
|
||||
const token = useAuthStore.getState().token
|
||||
|
||||
const res = await fetch(`${API_BASE}${path}`, {
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
...options?.headers,
|
||||
},
|
||||
})
|
||||
|
||||
if (res.status === 401) {
|
||||
useAuthStore.getState().logout()
|
||||
throw new Error('Unauthorized')
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`API error: ${res.status}`)
|
||||
}
|
||||
|
||||
return res.json() as Promise<T>
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: <T>(path: string) => apiFetch<T>(path),
|
||||
post: <T>(path: string, body: unknown) =>
|
||||
apiFetch<T>(path, { method: 'POST', body: JSON.stringify(body) }),
|
||||
put: <T>(path: string, body: unknown) =>
|
||||
apiFetch<T>(path, { method: 'PUT', body: JSON.stringify(body) }),
|
||||
delete: <T>(path: string) => apiFetch<T>(path, { method: 'DELETE' }),
|
||||
}
|
||||
import { useAuthStore } from '../stores/auth.ts'
|
||||
import {
|
||||
mockPurchases,
|
||||
mockProducts,
|
||||
mockCoupons,
|
||||
mockAlerts,
|
||||
getMockPriceHistory,
|
||||
} from './mock-data.ts'
|
||||
|
||||
const API_BASE = import.meta.env.VITE_API_URL ?? '/api/v1'
|
||||
const USE_MOCK = import.meta.env.VITE_MOCK_API === 'true'
|
||||
|
||||
// Mock response lookup table
|
||||
const mockRoutes: Record<string, (path: string) => unknown> = {
|
||||
'/purchases': () => mockPurchases,
|
||||
'/products': () => mockProducts,
|
||||
'/coupons': () => mockCoupons,
|
||||
'/price-alerts': () => mockAlerts,
|
||||
}
|
||||
|
||||
function matchMockRoute<T>(path: string): T | null {
|
||||
// Exact match
|
||||
if (mockRoutes[path]) return mockRoutes[path](path) as T
|
||||
|
||||
// /purchases/:id
|
||||
const purchaseMatch = path.match(/^\/purchases\/(.+)$/)
|
||||
if (purchaseMatch) {
|
||||
const purchase = mockPurchases.find((p) => p.id === purchaseMatch[1])
|
||||
return (purchase ?? null) as T
|
||||
}
|
||||
|
||||
// /products/:id/price-history
|
||||
const priceHistoryMatch = path.match(/^\/products\/(.+)\/price-history$/)
|
||||
if (priceHistoryMatch) {
|
||||
return getMockPriceHistory(priceHistoryMatch[1]) as T
|
||||
}
|
||||
|
||||
// /products/:id
|
||||
const productMatch = path.match(/^\/products\/(.+)$/)
|
||||
if (productMatch) {
|
||||
const product = mockProducts.find((p) => p.id === productMatch[1])
|
||||
return (product ?? null) as T
|
||||
}
|
||||
|
||||
const productsSearch = path.match(/^\/products\?q=(.+)$/)
|
||||
if (productsSearch) {
|
||||
const q = decodeURIComponent(productsSearch[1]).toLowerCase()
|
||||
return mockProducts.filter(
|
||||
(p) =>
|
||||
p.name.toLowerCase().includes(q) ||
|
||||
p.brand.toLowerCase().includes(q) ||
|
||||
p.category.toLowerCase().includes(q),
|
||||
) as T
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
async function apiFetch<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
// Mock interceptor: return mock data without hitting the network
|
||||
if (USE_MOCK && (!options?.method || options.method === 'GET')) {
|
||||
const mockResult = matchMockRoute<T>(path)
|
||||
if (mockResult !== null) {
|
||||
// Simulate network delay for realistic loading states
|
||||
await new Promise((r) => setTimeout(r, 300))
|
||||
return mockResult
|
||||
}
|
||||
}
|
||||
|
||||
const res = await fetch(`${API_BASE}${path}`, {
|
||||
...options,
|
||||
credentials: 'include', // Send Better-Auth session cookie
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options?.headers,
|
||||
},
|
||||
})
|
||||
|
||||
if (res.status === 401) {
|
||||
useAuthStore.getState().setAuthenticated(false)
|
||||
throw new Error('Unauthorized')
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`API error: ${res.status}`)
|
||||
}
|
||||
|
||||
return res.json() as Promise<T>
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: <T>(path: string) => apiFetch<T>(path),
|
||||
post: <T>(path: string, body: unknown) =>
|
||||
apiFetch<T>(path, { method: 'POST', body: JSON.stringify(body) }),
|
||||
put: <T>(path: string, body: unknown) =>
|
||||
apiFetch<T>(path, { method: 'PUT', body: JSON.stringify(body) }),
|
||||
delete: <T>(path: string) => apiFetch<T>(path, { method: 'DELETE' }),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { createAuthClient } from "better-auth/react"
|
||||
|
||||
export const authClient = createAuthClient({
|
||||
baseURL: import.meta.env.VITE_AUTH_URL ?? "http://localhost:3001",
|
||||
basePath: "/auth",
|
||||
})
|
||||
|
||||
export const { useSession, signIn, signUp, signOut } = authClient
|
||||
+200
-197
@@ -1,197 +1,200 @@
|
||||
import React, { Suspense } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { useAuthStore } from '../stores/auth.ts'
|
||||
import { usePurchases, usePriceAlerts, usePriceHistory } from '../hooks/useApi.ts'
|
||||
import { StoreIcon } from '../components/StoreIcon.tsx'
|
||||
|
||||
const LazySparklineCard = React.lazy(() =>
|
||||
import('../components/SparklineChart.tsx').then((mod) => ({ default: mod.SparklineCard }))
|
||||
)
|
||||
|
||||
export function Dashboard() {
|
||||
const user = useAuthStore((s) => s.user)
|
||||
const isAuthenticated = useAuthStore((s) => s.isAuthenticated)
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return (
|
||||
<div className="py-8 text-center">
|
||||
<h1 className="text-2xl font-bold text-gray-900">CartSnitch</h1>
|
||||
<p className="mt-2 text-sm text-gray-500">Track prices. Save money.</p>
|
||||
<div className="mt-8 space-y-3">
|
||||
<Link
|
||||
to="/login"
|
||||
className="block min-h-12 rounded-xl bg-brand-blue px-4 py-3 text-center text-base font-medium text-white active:bg-brand-blue/90"
|
||||
>
|
||||
Sign In
|
||||
</Link>
|
||||
<Link
|
||||
to="/register"
|
||||
className="block min-h-12 rounded-xl border border-gray-200 px-4 py-3 text-center text-base font-medium text-gray-700 active:bg-gray-50"
|
||||
>
|
||||
Create Account
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return <AuthenticatedDashboard userName={user?.name ?? 'there'} />
|
||||
}
|
||||
|
||||
function AuthenticatedDashboard({ userName }: { userName: string }) {
|
||||
const { data: purchases = [], isLoading: purchasesLoading } = usePurchases()
|
||||
const { data: alerts = [], isLoading: alertsLoading } = usePriceAlerts()
|
||||
const { data: eggHistory = [] } = usePriceHistory('prod10')
|
||||
const { data: milkHistory = [] } = usePriceHistory('prod1')
|
||||
|
||||
const triggeredAlerts = alerts.filter((a) => a.triggered)
|
||||
const watchingAlerts = alerts.filter((a) => !a.triggered)
|
||||
const recentPurchases = purchases.slice(0, 3)
|
||||
|
||||
const sparklineData = eggHistory.filter((p) => p.storeId === 'meijer').slice(-8)
|
||||
const milkSparkline = milkHistory.filter((p) => p.storeId === 'kroger').slice(-8)
|
||||
|
||||
const eggCurrent = sparklineData.length > 0 ? `$${sparklineData[sparklineData.length - 1].price.toFixed(2)}` : '—'
|
||||
const milkCurrent = milkSparkline.length > 0 ? `$${milkSparkline[milkSparkline.length - 1].price.toFixed(2)}` : '—'
|
||||
|
||||
if (purchasesLoading || alertsLoading) {
|
||||
return <DashboardSkeleton />
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">
|
||||
Hi, {userName.split(' ')[0]}
|
||||
</h1>
|
||||
|
||||
{/* Triggered alerts banner */}
|
||||
{triggeredAlerts.length > 0 && (
|
||||
<Link
|
||||
to="/alerts"
|
||||
className="mt-4 flex items-center gap-3 rounded-xl bg-green-50 p-4"
|
||||
>
|
||||
<span className="flex h-10 w-10 items-center justify-center rounded-full bg-green-500 text-lg text-white">
|
||||
✓
|
||||
</span>
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-green-800">
|
||||
{triggeredAlerts.length} price {triggeredAlerts.length === 1 ? 'alert' : 'alerts'} triggered!
|
||||
</p>
|
||||
<p className="text-xs text-green-700">
|
||||
{triggeredAlerts.map((a) => a.productName).join(', ')}
|
||||
</p>
|
||||
</div>
|
||||
</Link>
|
||||
)}
|
||||
|
||||
{/* Quick stats */}
|
||||
<div className="mt-4 grid grid-cols-2 gap-3">
|
||||
<div className="rounded-xl bg-white p-4 shadow-sm">
|
||||
<p className="text-xs font-medium text-gray-500">Watching</p>
|
||||
<p className="mt-1 text-2xl font-bold text-gray-900">{watchingAlerts.length}</p>
|
||||
<p className="text-xs text-gray-400">price alerts</p>
|
||||
</div>
|
||||
<div className="rounded-xl bg-white p-4 shadow-sm">
|
||||
<p className="text-xs font-medium text-gray-500">This Month</p>
|
||||
<p className="mt-1 text-2xl font-bold text-gray-900">
|
||||
${recentPurchases.reduce((sum, p) => sum + p.total, 0).toFixed(0)}
|
||||
</p>
|
||||
<p className="text-xs text-gray-400">grocery spend</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Price trend sparklines */}
|
||||
<section className="mt-6">
|
||||
<h2 className="mb-3 text-lg font-semibold text-gray-700">Price Trends</h2>
|
||||
<div className="space-y-3">
|
||||
<Suspense fallback={<SparklinePlaceholder />}>
|
||||
<LazySparklineCard label="Eggs (dozen)" data={sparklineData} current={eggCurrent} />
|
||||
<LazySparklineCard label="Whole Milk (1 gal)" data={milkSparkline} current={milkCurrent} />
|
||||
</Suspense>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Recent purchases */}
|
||||
<section className="mt-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-semibold text-gray-700">Recent Purchases</h2>
|
||||
<Link to="/purchases" className="text-sm text-brand-blue">
|
||||
View all
|
||||
</Link>
|
||||
</div>
|
||||
<div className="mt-3 space-y-3">
|
||||
{recentPurchases.map((purchase) => (
|
||||
<Link
|
||||
key={purchase.id}
|
||||
to={`/purchases/${purchase.id}`}
|
||||
className="flex items-center gap-3 rounded-xl bg-white p-4 shadow-sm active:bg-gray-50"
|
||||
>
|
||||
<StoreIcon storeId={purchase.storeId} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium text-gray-900">{purchase.storeName}</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
{new Date(purchase.date).toLocaleDateString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
})}{' '}
|
||||
· {purchase.items.length} items
|
||||
</p>
|
||||
</div>
|
||||
<span className="text-sm font-semibold text-gray-900">
|
||||
${purchase.total.toFixed(2)}
|
||||
</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Quick actions */}
|
||||
<section className="mt-6 pb-4">
|
||||
<h2 className="mb-3 text-lg font-semibold text-gray-700">Quick Actions</h2>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Link
|
||||
to="/products"
|
||||
className="flex min-h-12 items-center justify-center rounded-xl border border-gray-200 bg-white px-4 py-3 text-sm font-medium text-gray-700 shadow-sm active:bg-gray-50"
|
||||
>
|
||||
Compare Prices
|
||||
</Link>
|
||||
<Link
|
||||
to="/settings"
|
||||
className="flex min-h-12 items-center justify-center rounded-xl border border-gray-200 bg-white px-4 py-3 text-sm font-medium text-gray-700 shadow-sm active:bg-gray-50"
|
||||
>
|
||||
Link a Store
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DashboardSkeleton() {
|
||||
return (
|
||||
<div className="animate-pulse">
|
||||
<div className="h-8 w-40 rounded bg-gray-200" />
|
||||
<div className="mt-4 grid grid-cols-2 gap-3">
|
||||
<div className="h-24 rounded-xl bg-gray-200" />
|
||||
<div className="h-24 rounded-xl bg-gray-200" />
|
||||
</div>
|
||||
<div className="mt-6 h-5 w-28 rounded bg-gray-200" />
|
||||
<div className="mt-3 space-y-3">
|
||||
<div className="h-16 rounded-xl bg-gray-200" />
|
||||
<div className="h-16 rounded-xl bg-gray-200" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SparklinePlaceholder() {
|
||||
return (
|
||||
<div className="flex items-center gap-4 rounded-xl bg-white p-4 shadow-sm animate-pulse">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="h-4 w-24 rounded bg-gray-200" />
|
||||
<div className="mt-2 h-6 w-16 rounded bg-gray-200" />
|
||||
</div>
|
||||
<div className="h-10 w-24 rounded bg-gray-100" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
import React, { Suspense } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { authClient } from '../lib/auth-client.ts'
|
||||
import { usePurchases, usePriceAlerts, usePriceHistory } from '../hooks/useApi.ts'
|
||||
import { StoreIcon } from '../components/StoreIcon.tsx'
|
||||
|
||||
const LazySparklineCard = React.lazy(() =>
|
||||
import('../components/SparklineChart.tsx').then((mod) => ({ default: mod.SparklineCard }))
|
||||
)
|
||||
|
||||
export function Dashboard() {
|
||||
const { data: session, isPending } = authClient.useSession()
|
||||
|
||||
if (isPending) {
|
||||
return <DashboardSkeleton />
|
||||
}
|
||||
|
||||
if (!session) {
|
||||
return (
|
||||
<div className="py-8 text-center">
|
||||
<h1 className="text-2xl font-bold text-gray-900">CartSnitch</h1>
|
||||
<p className="mt-2 text-sm text-gray-500">Track prices. Save money.</p>
|
||||
<div className="mt-8 space-y-3">
|
||||
<Link
|
||||
to="/login"
|
||||
className="block min-h-12 rounded-xl bg-brand-blue px-4 py-3 text-center text-base font-medium text-white active:bg-brand-blue/90"
|
||||
>
|
||||
Sign In
|
||||
</Link>
|
||||
<Link
|
||||
to="/register"
|
||||
className="block min-h-12 rounded-xl border border-gray-200 px-4 py-3 text-center text-base font-medium text-gray-700 active:bg-gray-50"
|
||||
>
|
||||
Create Account
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return <AuthenticatedDashboard userName={session.user?.name ?? 'there'} />
|
||||
}
|
||||
|
||||
function AuthenticatedDashboard({ userName }: { userName: string }) {
|
||||
const { data: purchases = [], isLoading: purchasesLoading } = usePurchases()
|
||||
const { data: alerts = [], isLoading: alertsLoading } = usePriceAlerts()
|
||||
const { data: eggHistory = [] } = usePriceHistory('prod10')
|
||||
const { data: milkHistory = [] } = usePriceHistory('prod1')
|
||||
|
||||
const triggeredAlerts = alerts.filter((a) => a.triggered)
|
||||
const watchingAlerts = alerts.filter((a) => !a.triggered)
|
||||
const recentPurchases = purchases.slice(0, 3)
|
||||
|
||||
const sparklineData = eggHistory.filter((p) => p.storeId === 'meijer').slice(-8)
|
||||
const milkSparkline = milkHistory.filter((p) => p.storeId === 'kroger').slice(-8)
|
||||
|
||||
const eggCurrent = sparklineData.length > 0 ? `$${sparklineData[sparklineData.length - 1].price.toFixed(2)}` : '—'
|
||||
const milkCurrent = milkSparkline.length > 0 ? `$${milkSparkline[milkSparkline.length - 1].price.toFixed(2)}` : '—'
|
||||
|
||||
if (purchasesLoading || alertsLoading) {
|
||||
return <DashboardSkeleton />
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">
|
||||
Hi, {userName.split(' ')[0]}
|
||||
</h1>
|
||||
|
||||
{/* Triggered alerts banner */}
|
||||
{triggeredAlerts.length > 0 && (
|
||||
<Link
|
||||
to="/alerts"
|
||||
className="mt-4 flex items-center gap-3 rounded-xl bg-green-50 p-4"
|
||||
>
|
||||
<span className="flex h-10 w-10 items-center justify-center rounded-full bg-green-500 text-lg text-white">
|
||||
✓
|
||||
</span>
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-green-800">
|
||||
{triggeredAlerts.length} price {triggeredAlerts.length === 1 ? 'alert' : 'alerts'} triggered!
|
||||
</p>
|
||||
<p className="text-xs text-green-700">
|
||||
{triggeredAlerts.map((a) => a.productName).join(', ')}
|
||||
</p>
|
||||
</div>
|
||||
</Link>
|
||||
)}
|
||||
|
||||
{/* Quick stats */}
|
||||
<div className="mt-4 grid grid-cols-2 gap-3">
|
||||
<div className="rounded-xl bg-white p-4 shadow-sm">
|
||||
<p className="text-xs font-medium text-gray-500">Watching</p>
|
||||
<p className="mt-1 text-2xl font-bold text-gray-900">{watchingAlerts.length}</p>
|
||||
<p className="text-xs text-gray-400">price alerts</p>
|
||||
</div>
|
||||
<div className="rounded-xl bg-white p-4 shadow-sm">
|
||||
<p className="text-xs font-medium text-gray-500">This Month</p>
|
||||
<p className="mt-1 text-2xl font-bold text-gray-900">
|
||||
${recentPurchases.reduce((sum, p) => sum + p.total, 0).toFixed(0)}
|
||||
</p>
|
||||
<p className="text-xs text-gray-400">grocery spend</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Price trend sparklines */}
|
||||
<section className="mt-6">
|
||||
<h2 className="mb-3 text-lg font-semibold text-gray-700">Price Trends</h2>
|
||||
<div className="space-y-3">
|
||||
<Suspense fallback={<SparklinePlaceholder />}>
|
||||
<LazySparklineCard label="Eggs (dozen)" data={sparklineData} current={eggCurrent} />
|
||||
<LazySparklineCard label="Whole Milk (1 gal)" data={milkSparkline} current={milkCurrent} />
|
||||
</Suspense>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Recent purchases */}
|
||||
<section className="mt-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-semibold text-gray-700">Recent Purchases</h2>
|
||||
<Link to="/purchases" className="text-sm text-brand-blue">
|
||||
View all
|
||||
</Link>
|
||||
</div>
|
||||
<div className="mt-3 space-y-3">
|
||||
{recentPurchases.map((purchase) => (
|
||||
<Link
|
||||
key={purchase.id}
|
||||
to={`/purchases/${purchase.id}`}
|
||||
className="flex items-center gap-3 rounded-xl bg-white p-4 shadow-sm active:bg-gray-50"
|
||||
>
|
||||
<StoreIcon storeId={purchase.storeId} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium text-gray-900">{purchase.storeName}</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
{new Date(purchase.date).toLocaleDateString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
})}{' '}
|
||||
· {purchase.items.length} items
|
||||
</p>
|
||||
</div>
|
||||
<span className="text-sm font-semibold text-gray-900">
|
||||
${purchase.total.toFixed(2)}
|
||||
</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Quick actions */}
|
||||
<section className="mt-6 pb-4">
|
||||
<h2 className="mb-3 text-lg font-semibold text-gray-700">Quick Actions</h2>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Link
|
||||
to="/products"
|
||||
className="flex min-h-12 items-center justify-center rounded-xl border border-gray-200 bg-white px-4 py-3 text-sm font-medium text-gray-700 shadow-sm active:bg-gray-50"
|
||||
>
|
||||
Compare Prices
|
||||
</Link>
|
||||
<Link
|
||||
to="/settings"
|
||||
className="flex min-h-12 items-center justify-center rounded-xl border border-gray-200 bg-white px-4 py-3 text-sm font-medium text-gray-700 shadow-sm active:bg-gray-50"
|
||||
>
|
||||
Link a Store
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DashboardSkeleton() {
|
||||
return (
|
||||
<div className="animate-pulse">
|
||||
<div className="h-8 w-40 rounded bg-gray-200" />
|
||||
<div className="mt-4 grid grid-cols-2 gap-3">
|
||||
<div className="h-24 rounded-xl bg-gray-200" />
|
||||
<div className="h-24 rounded-xl bg-gray-200" />
|
||||
</div>
|
||||
<div className="mt-6 h-5 w-28 rounded bg-gray-200" />
|
||||
<div className="mt-3 space-y-3">
|
||||
<div className="h-16 rounded-xl bg-gray-200" />
|
||||
<div className="h-16 rounded-xl bg-gray-200" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SparklinePlaceholder() {
|
||||
return (
|
||||
<div className="flex items-center gap-4 rounded-xl bg-white p-4 shadow-sm animate-pulse">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="h-4 w-24 rounded bg-gray-200" />
|
||||
<div className="mt-2 h-6 w-16 rounded bg-gray-200" />
|
||||
</div>
|
||||
<div className="h-10 w-24 rounded bg-gray-100" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
+97
-92
@@ -1,92 +1,97 @@
|
||||
import { useState } from 'react'
|
||||
import { Link, useNavigate } from 'react-router-dom'
|
||||
import { useAuthStore } from '../stores/auth.ts'
|
||||
import { api } from '../lib/api.ts'
|
||||
import { mockUser } from '../lib/mock-data.ts'
|
||||
import type { User } from '../types/api.ts'
|
||||
|
||||
export function Login() {
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const navigate = useNavigate()
|
||||
const setAuth = useAuthStore((s) => s.setAuth)
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
|
||||
if (!email || !password) {
|
||||
setError('Please fill in all fields.')
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await api.post<{ user: User; token: string }>('/auth/login', { email, password })
|
||||
setAuth(res.user, res.token)
|
||||
navigate('/')
|
||||
} catch {
|
||||
if (import.meta.env.VITE_MOCK_AUTH === 'true') {
|
||||
// Fallback to mock auth for demo
|
||||
setAuth(mockUser, 'mock-jwt-token')
|
||||
navigate('/')
|
||||
} else {
|
||||
setError('Invalid email or password. Please try again.')
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center px-4">
|
||||
<h1 className="mb-2 text-3xl font-bold text-gray-900">CartSnitch</h1>
|
||||
<p className="mb-8 text-sm text-gray-500">Track prices. Save money.</p>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 w-full max-w-sm rounded-xl bg-red-50 px-4 py-3 text-sm text-red-700">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form className="w-full max-w-sm space-y-4" onSubmit={handleSubmit}>
|
||||
<input
|
||||
type="email"
|
||||
placeholder="Email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
autoComplete="email"
|
||||
className="min-h-12 w-full rounded-xl border border-gray-200 px-4 text-base focus:border-brand-blue focus:outline-none focus:ring-1 focus:ring-brand-blue"
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
placeholder="Password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
className="min-h-12 w-full rounded-xl border border-gray-200 px-4 text-base focus:border-brand-blue focus:outline-none focus:ring-1 focus:ring-brand-blue"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="min-h-12 w-full rounded-xl bg-brand-blue px-4 py-3 text-base font-medium text-white active:bg-brand-blue/90 disabled:opacity-60"
|
||||
>
|
||||
{loading ? 'Signing in...' : 'Sign In'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<Link to="/forgot-password" className="mt-4 text-sm text-brand-blue">
|
||||
Forgot password?
|
||||
</Link>
|
||||
|
||||
<p className="mt-6 text-sm text-gray-500">
|
||||
Don't have an account?{' '}
|
||||
<Link to="/register" className="text-brand-blue">
|
||||
Sign up
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
import { useState } from 'react'
|
||||
import { Link, useNavigate } from 'react-router-dom'
|
||||
import { authClient } from '../lib/auth-client.ts'
|
||||
import { useAuthStore } from '../stores/auth.ts'
|
||||
|
||||
export function Login() {
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const navigate = useNavigate()
|
||||
const setAuthenticated = useAuthStore((s) => s.setAuthenticated)
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
|
||||
if (!email || !password) {
|
||||
setError('Please fill in all fields.')
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
try {
|
||||
const { error: authError } = await authClient.signIn.email({
|
||||
email,
|
||||
password,
|
||||
})
|
||||
|
||||
if (authError) {
|
||||
throw new Error(authError.message ?? 'Sign in failed')
|
||||
}
|
||||
|
||||
setAuthenticated(true)
|
||||
navigate('/')
|
||||
} catch {
|
||||
if (import.meta.env.VITE_MOCK_AUTH === 'true') {
|
||||
setAuthenticated(true)
|
||||
navigate('/')
|
||||
} else {
|
||||
setError('Invalid email or password. Please try again.')
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center px-4">
|
||||
<h1 className="mb-2 text-3xl font-bold text-gray-900">CartSnitch</h1>
|
||||
<p className="mb-8 text-sm text-gray-500">Track prices. Save money.</p>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 w-full max-w-sm rounded-xl bg-red-50 px-4 py-3 text-sm text-red-700">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form className="w-full max-w-sm space-y-4" onSubmit={handleSubmit}>
|
||||
<input
|
||||
type="email"
|
||||
placeholder="Email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
autoComplete="email"
|
||||
className="min-h-12 w-full rounded-xl border border-gray-200 px-4 text-base focus:border-brand-blue focus:outline-none focus:ring-1 focus:ring-brand-blue"
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
placeholder="Password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
className="min-h-12 w-full rounded-xl border border-gray-200 px-4 text-base focus:border-brand-blue focus:outline-none focus:ring-1 focus:ring-brand-blue"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="min-h-12 w-full rounded-xl bg-brand-blue px-4 py-3 text-base font-medium text-white active:bg-brand-blue/90 disabled:opacity-60"
|
||||
>
|
||||
{loading ? 'Signing in...' : 'Sign In'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<Link to="/forgot-password" className="mt-4 text-sm text-brand-blue">
|
||||
Forgot password?
|
||||
</Link>
|
||||
|
||||
<p className="mt-6 text-sm text-gray-500">
|
||||
Don't have an account?{' '}
|
||||
<Link to="/register" className="text-brand-blue">
|
||||
Sign up
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
+108
-102
@@ -1,102 +1,108 @@
|
||||
import { useState } from 'react'
|
||||
import { Link, useNavigate } from 'react-router-dom'
|
||||
import { useAuthStore } from '../stores/auth.ts'
|
||||
import { api } from '../lib/api.ts'
|
||||
import { mockUser } from '../lib/mock-data.ts'
|
||||
import type { User } from '../types/api.ts'
|
||||
|
||||
export function Register() {
|
||||
const [name, setName] = useState('')
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const navigate = useNavigate()
|
||||
const setAuth = useAuthStore((s) => s.setAuth)
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
|
||||
if (!name || !email || !password) {
|
||||
setError('Please fill in all fields.')
|
||||
return
|
||||
}
|
||||
|
||||
if (password.length < 8) {
|
||||
setError('Password must be at least 8 characters.')
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await api.post<{ user: User; token: string }>('/auth/register', { name, email, password })
|
||||
setAuth(res.user, res.token)
|
||||
navigate('/')
|
||||
} catch {
|
||||
if (import.meta.env.VITE_MOCK_AUTH === 'true') {
|
||||
// Fallback to mock auth for demo
|
||||
setAuth({ ...mockUser, name, email }, 'mock-jwt-token')
|
||||
navigate('/')
|
||||
} else {
|
||||
setError('Registration failed. Please try again.')
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center px-4">
|
||||
<h1 className="mb-2 text-3xl font-bold text-gray-900">Create Account</h1>
|
||||
<p className="mb-8 text-sm text-gray-500">Start tracking your grocery prices.</p>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 w-full max-w-sm rounded-xl bg-red-50 px-4 py-3 text-sm text-red-700">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form className="w-full max-w-sm space-y-4" onSubmit={handleSubmit}>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Full Name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
autoComplete="name"
|
||||
className="min-h-12 w-full rounded-xl border border-gray-200 px-4 text-base focus:border-brand-blue focus:outline-none focus:ring-1 focus:ring-brand-blue"
|
||||
/>
|
||||
<input
|
||||
type="email"
|
||||
placeholder="Email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
autoComplete="email"
|
||||
className="min-h-12 w-full rounded-xl border border-gray-200 px-4 text-base focus:border-brand-blue focus:outline-none focus:ring-1 focus:ring-brand-blue"
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
placeholder="Password (min. 8 characters)"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="new-password"
|
||||
className="min-h-12 w-full rounded-xl border border-gray-200 px-4 text-base focus:border-brand-blue focus:outline-none focus:ring-1 focus:ring-brand-blue"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="min-h-12 w-full rounded-xl bg-brand-blue px-4 py-3 text-base font-medium text-white active:bg-brand-blue/90 disabled:opacity-60"
|
||||
>
|
||||
{loading ? 'Creating account...' : 'Create Account'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p className="mt-6 text-sm text-gray-500">
|
||||
Already have an account?{' '}
|
||||
<Link to="/login" className="text-brand-blue">
|
||||
Sign in
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
import { useState } from 'react'
|
||||
import { Link, useNavigate } from 'react-router-dom'
|
||||
import { authClient } from '../lib/auth-client.ts'
|
||||
import { useAuthStore } from '../stores/auth.ts'
|
||||
|
||||
export function Register() {
|
||||
const [name, setName] = useState('')
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const navigate = useNavigate()
|
||||
const setAuthenticated = useAuthStore((s) => s.setAuthenticated)
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
|
||||
if (!name || !email || !password) {
|
||||
setError('Please fill in all fields.')
|
||||
return
|
||||
}
|
||||
|
||||
if (password.length < 8) {
|
||||
setError('Password must be at least 8 characters.')
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
try {
|
||||
const { error: authError } = await authClient.signUp.email({
|
||||
name,
|
||||
email,
|
||||
password,
|
||||
})
|
||||
|
||||
if (authError) {
|
||||
throw new Error(authError.message ?? 'Registration failed')
|
||||
}
|
||||
|
||||
setAuthenticated(true)
|
||||
navigate('/')
|
||||
} catch {
|
||||
if (import.meta.env.VITE_MOCK_AUTH === 'true') {
|
||||
setAuthenticated(true)
|
||||
navigate('/')
|
||||
} else {
|
||||
setError('Registration failed. Please try again.')
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center px-4">
|
||||
<h1 className="mb-2 text-3xl font-bold text-gray-900">Create Account</h1>
|
||||
<p className="mb-8 text-sm text-gray-500">Start tracking your grocery prices.</p>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 w-full max-w-sm rounded-xl bg-red-50 px-4 py-3 text-sm text-red-700">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form className="w-full max-w-sm space-y-4" onSubmit={handleSubmit}>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Full Name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
autoComplete="name"
|
||||
className="min-h-12 w-full rounded-xl border border-gray-200 px-4 text-base focus:border-brand-blue focus:outline-none focus:ring-1 focus:ring-brand-blue"
|
||||
/>
|
||||
<input
|
||||
type="email"
|
||||
placeholder="Email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
autoComplete="email"
|
||||
className="min-h-12 w-full rounded-xl border border-gray-200 px-4 text-base focus:border-brand-blue focus:outline-none focus:ring-1 focus:ring-brand-blue"
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
placeholder="Password (min. 8 characters)"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="new-password"
|
||||
className="min-h-12 w-full rounded-xl border border-gray-200 px-4 text-base focus:border-brand-blue focus:outline-none focus:ring-1 focus:ring-brand-blue"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="min-h-12 w-full rounded-xl bg-brand-blue px-4 py-3 text-base font-medium text-white active:bg-brand-blue/90 disabled:opacity-60"
|
||||
>
|
||||
{loading ? 'Creating account...' : 'Create Account'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p className="mt-6 text-sm text-gray-500">
|
||||
Already have an account?{' '}
|
||||
<Link to="/login" className="text-brand-blue">
|
||||
Sign in
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
import { Link, useNavigate } from 'react-router-dom'
|
||||
import { authClient } from '../lib/auth-client.ts'
|
||||
import { useAuthStore } from '../stores/auth.ts'
|
||||
import { useThemeStore } from '../stores/theme.ts'
|
||||
import { StoreIcon } from '../components/StoreIcon.tsx'
|
||||
|
||||
export function Settings() {
|
||||
const user = useAuthStore((s) => s.user)
|
||||
const logout = useAuthStore((s) => s.logout)
|
||||
const { data: session } = authClient.useSession()
|
||||
const setAuthenticated = useAuthStore((s) => s.setAuthenticated)
|
||||
const navigate = useNavigate()
|
||||
const { theme, setTheme } = useThemeStore()
|
||||
|
||||
const connectedStores = user?.connectedStores ?? []
|
||||
const user = session?.user
|
||||
const connectedStores: string[] = []
|
||||
|
||||
function handleSignOut() {
|
||||
logout()
|
||||
async function handleSignOut() {
|
||||
await authClient.signOut()
|
||||
setAuthenticated(false)
|
||||
navigate('/login')
|
||||
}
|
||||
|
||||
|
||||
+18
-27
@@ -1,27 +1,18 @@
|
||||
import { create } from 'zustand'
|
||||
import { persist } from 'zustand/middleware'
|
||||
import type { User } from '../types/api.ts'
|
||||
|
||||
interface AuthState {
|
||||
user: User | null
|
||||
token: string | null
|
||||
isAuthenticated: boolean
|
||||
setAuth: (user: User, token: string) => void
|
||||
logout: () => void
|
||||
}
|
||||
|
||||
export const useAuthStore = create<AuthState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
user: null,
|
||||
token: null,
|
||||
isAuthenticated: false,
|
||||
setAuth: (user, token) => set({ user, token, isAuthenticated: true }),
|
||||
logout: () => set({ user: null, token: null, isAuthenticated: false }),
|
||||
}),
|
||||
{
|
||||
name: 'cartsnitch-auth',
|
||||
partialize: (state) => ({ user: state.user, isAuthenticated: state.isAuthenticated }),
|
||||
},
|
||||
),
|
||||
)
|
||||
import { create } from 'zustand'
|
||||
|
||||
/**
|
||||
* Minimal auth state for UI reactivity.
|
||||
*
|
||||
* Session management is handled by Better-Auth via httpOnly cookies.
|
||||
* This store only tracks whether we have an active session for UI
|
||||
* gating (protected routes, nav state). No tokens in memory or localStorage.
|
||||
*/
|
||||
interface AuthState {
|
||||
isAuthenticated: boolean
|
||||
setAuthenticated: (value: boolean) => void
|
||||
}
|
||||
|
||||
export const useAuthStore = create<AuthState>()((set) => ({
|
||||
isAuthenticated: false,
|
||||
setAuthenticated: (value) => set({ isAuthenticated: value }),
|
||||
}))
|
||||
|
||||
Reference in New Issue
Block a user