Add frontend authentication with Google OAuth
- Create AuthContext and AuthProvider for auth state management - Create useAuth hook for easy access to auth state - Create ProtectedRoute component to guard authenticated routes - Create Login page with Google sign-in button and error handling - Create useActivityTracker hook for frontend activity logging - Update App.jsx to protect all routes and add user display/logout - Update main.jsx to wrap app with AuthProvider - Add credentials: 'include' to all API fetch calls
This commit is contained in:
60
src/App.jsx
60
src/App.jsx
@ -1,11 +1,15 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Routes, Route, Link, useLocation, Navigate } from 'react-router-dom';
|
||||
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell, Area, AreaChart, ScatterChart, Scatter, ComposedChart, ReferenceLine } from 'recharts';
|
||||
import { TrendingUp, TrendingDown, Home, DollarSign, Calendar, MapPin, Activity, AlertCircle, Star, RefreshCw, Wifi, WifiOff, Bell, Target, Filter, Search, ArrowUp, ArrowDown, Zap, Clock, Eye, LayoutGrid, List } from 'lucide-react';
|
||||
import { TrendingUp, TrendingDown, Home, DollarSign, Calendar, MapPin, Activity, AlertCircle, Star, RefreshCw, Wifi, WifiOff, Bell, Target, Filter, Search, ArrowUp, ArrowDown, Zap, Clock, Eye, LayoutGrid, List, LogOut, User } from 'lucide-react';
|
||||
import useAuth from './hooks/useAuth';
|
||||
import ProtectedRoute from './components/ProtectedRoute';
|
||||
import Login from './pages/Login';
|
||||
|
||||
const ApartmentDashboard = () => {
|
||||
// Router
|
||||
const location = useLocation();
|
||||
const { user, logout } = useAuth();
|
||||
|
||||
// Basic state
|
||||
const [selectedUnit, setSelectedUnit] = useState(null);
|
||||
@ -54,11 +58,11 @@ const ApartmentDashboard = () => {
|
||||
|
||||
// Fetch core endpoints that we know work
|
||||
const coreRequests = [
|
||||
fetch(`${API_BASE}/daily-summary`),
|
||||
fetch(`${API_BASE}/price-history`),
|
||||
fetch(`${API_BASE}/available-units`),
|
||||
fetch(`${API_BASE}/recent-activity`),
|
||||
fetch(`${API_BASE}/plan-stats`)
|
||||
fetch(`${API_BASE}/daily-summary`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/price-history`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/available-units`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/recent-activity`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/plan-stats`, { credentials: 'include' })
|
||||
];
|
||||
|
||||
const [
|
||||
@ -96,11 +100,11 @@ const ApartmentDashboard = () => {
|
||||
// Try to fetch enhanced endpoints (won't break if they don't exist)
|
||||
try {
|
||||
const enhancedRequests = [
|
||||
fetch(`${API_BASE}/best-deals?limit=5`),
|
||||
fetch(`${API_BASE}/price-drops?limit=5`),
|
||||
fetch(`${API_BASE}/stale-inventory?limit=5`),
|
||||
fetch(`${API_BASE}/market-insights`),
|
||||
fetch(`${API_BASE}/last-scrape`)
|
||||
fetch(`${API_BASE}/best-deals?limit=5`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/price-drops?limit=5`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/stale-inventory?limit=5`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/market-insights`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/last-scrape`, { credentials: 'include' })
|
||||
];
|
||||
|
||||
const enhancedResponses = await Promise.all(enhancedRequests);
|
||||
@ -290,7 +294,7 @@ const ApartmentDashboard = () => {
|
||||
const fetchUnitPriceHistory = async (unitCode) => {
|
||||
setLoadingPriceHistory(true);
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/unit/${unitCode}/price-history`);
|
||||
const response = await fetch(`${API_BASE}/unit/${unitCode}/price-history`, { credentials: 'include' });
|
||||
if (response.ok) {
|
||||
const history = await response.json();
|
||||
setUnitPriceHistory(history);
|
||||
@ -319,7 +323,7 @@ const ApartmentDashboard = () => {
|
||||
if (analyticsData) return; // Already fetched
|
||||
setLoadingAnalytics(true);
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/analytics`);
|
||||
const response = await fetch(`${API_BASE}/analytics`, { credentials: 'include' });
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setAnalyticsData(data);
|
||||
@ -475,12 +479,34 @@ const ApartmentDashboard = () => {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center space-x-4">
|
||||
{priceDrops.length > 0 && (
|
||||
<div className="flex items-center space-x-2 bg-yellow-100 text-yellow-800 px-3 py-1 rounded-full text-sm">
|
||||
<Bell className="w-4 h-4" />
|
||||
<span>{priceDrops.length} price drops</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{user && (
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="flex items-center space-x-2">
|
||||
{user.picture ? (
|
||||
<img src={user.picture} alt={user.name} className="w-8 h-8 rounded-full" />
|
||||
) : (
|
||||
<User className="w-8 h-8 text-gray-400" />
|
||||
)}
|
||||
<span className="text-sm text-gray-700">{user.name}</span>
|
||||
</div>
|
||||
<button
|
||||
onClick={logout}
|
||||
className="flex items-center space-x-1 px-3 py-1 text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-md"
|
||||
>
|
||||
<LogOut className="w-4 h-4" />
|
||||
<span>Logout</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-4 mt-4">
|
||||
@ -506,8 +532,11 @@ const ApartmentDashboard = () => {
|
||||
</div>
|
||||
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
|
||||
{/* Overview Page */}
|
||||
<Route path="/" element={
|
||||
<ProtectedRoute>
|
||||
<>
|
||||
{/* Key Metrics */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
|
||||
@ -659,10 +688,12 @@ const ApartmentDashboard = () => {
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
{/* Units Page */}
|
||||
<Route path="/units" element={
|
||||
<ProtectedRoute>
|
||||
<div className="space-y-6">
|
||||
{/* Filters */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
@ -897,10 +928,12 @@ const ApartmentDashboard = () => {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
{/* Analytics Page */}
|
||||
<Route path="/analytics" element={
|
||||
<ProtectedRoute>
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<h2 className="text-xl font-semibold">Market Analytics</h2>
|
||||
@ -1104,6 +1137,7 @@ const ApartmentDashboard = () => {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
{/* Catch-all redirect to overview */}
|
||||
|
||||
23
src/components/ProtectedRoute.jsx
Normal file
23
src/components/ProtectedRoute.jsx
Normal file
@ -0,0 +1,23 @@
|
||||
import { Navigate, useLocation } from 'react-router-dom';
|
||||
import useAuth from '../hooks/useAuth';
|
||||
|
||||
const ProtectedRoute = ({ children }) => {
|
||||
const { user, loading } = useAuth();
|
||||
const location = useLocation();
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return <Navigate to="/login" state={{ from: location }} replace />;
|
||||
}
|
||||
|
||||
return children;
|
||||
};
|
||||
|
||||
export default ProtectedRoute;
|
||||
53
src/context/AuthContext.jsx
Normal file
53
src/context/AuthContext.jsx
Normal file
@ -0,0 +1,53 @@
|
||||
import React, { createContext, useState, useEffect, useCallback } from 'react';
|
||||
|
||||
const API_BASE = 'https://apartments.maverickapplications.com/api';
|
||||
|
||||
export const AuthContext = createContext(null);
|
||||
|
||||
export const AuthProvider = ({ children }) => {
|
||||
const [user, setUser] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const checkAuth = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/auth/me`, { credentials: 'include' });
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setUser(data.user);
|
||||
} else {
|
||||
setUser(null);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Auth check failed:', err);
|
||||
setUser(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
checkAuth();
|
||||
}, [checkAuth]);
|
||||
|
||||
const login = () => {
|
||||
window.location.href = `${API_BASE}/auth/google`;
|
||||
};
|
||||
|
||||
const logout = async () => {
|
||||
try {
|
||||
await fetch(`${API_BASE}/auth/logout`, {
|
||||
method: 'POST',
|
||||
credentials: 'include'
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Logout error:', err);
|
||||
}
|
||||
setUser(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, loading, login, logout, checkAuth }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
53
src/hooks/useActivityTracker.js
Normal file
53
src/hooks/useActivityTracker.js
Normal file
@ -0,0 +1,53 @@
|
||||
import { useEffect, useCallback, useRef } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import useAuth from './useAuth';
|
||||
|
||||
const API_BASE = 'https://apartments.maverickapplications.com/api';
|
||||
|
||||
const useActivityTracker = () => {
|
||||
const { user } = useAuth();
|
||||
const location = useLocation();
|
||||
const lastActivity = useRef({ action: null, timestamp: 0 });
|
||||
|
||||
const trackActivity = useCallback(async (action, metadata = {}) => {
|
||||
// Only track if user is authenticated
|
||||
if (!user) return;
|
||||
|
||||
// Debounce: skip if same action within 300ms
|
||||
const now = Date.now();
|
||||
if (lastActivity.current.action === action &&
|
||||
now - lastActivity.current.timestamp < 300) {
|
||||
return;
|
||||
}
|
||||
lastActivity.current = { action, timestamp: now };
|
||||
|
||||
try {
|
||||
await fetch(`${API_BASE}/activity/log`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({
|
||||
action,
|
||||
metadata: {
|
||||
...metadata,
|
||||
page: location.pathname
|
||||
}
|
||||
})
|
||||
});
|
||||
} catch (err) {
|
||||
// Silently fail - activity logging shouldn't break the app
|
||||
console.error('Activity tracking error:', err);
|
||||
}
|
||||
}, [user, location.pathname]);
|
||||
|
||||
// Track page views on route changes
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
trackActivity('page_view', { path: location.pathname });
|
||||
}
|
||||
}, [location.pathname, user, trackActivity]);
|
||||
|
||||
return { trackActivity };
|
||||
};
|
||||
|
||||
export default useActivityTracker;
|
||||
14
src/hooks/useAuth.js
Normal file
14
src/hooks/useAuth.js
Normal file
@ -0,0 +1,14 @@
|
||||
import { useContext } from 'react';
|
||||
import { AuthContext } from '../context/AuthContext';
|
||||
|
||||
const useAuth = () => {
|
||||
const context = useContext(AuthContext);
|
||||
|
||||
if (context === null) {
|
||||
throw new Error('useAuth must be used within an AuthProvider');
|
||||
}
|
||||
|
||||
return context;
|
||||
};
|
||||
|
||||
export default useAuth;
|
||||
@ -1,13 +1,16 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import { AuthProvider } from './context/AuthContext'
|
||||
import './index.css'
|
||||
import App from './App.jsx'
|
||||
|
||||
createRoot(document.getElementById('root')).render(
|
||||
<StrictMode>
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<App />
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
</StrictMode>,
|
||||
)
|
||||
|
||||
91
src/pages/Login.jsx
Normal file
91
src/pages/Login.jsx
Normal file
@ -0,0 +1,91 @@
|
||||
import { Navigate, useLocation, useSearchParams } from 'react-router-dom';
|
||||
import useAuth from '../hooks/useAuth';
|
||||
|
||||
const Login = () => {
|
||||
const { user, loading, login } = useAuth();
|
||||
const location = useLocation();
|
||||
const [searchParams] = useSearchParams();
|
||||
const error = searchParams.get('error');
|
||||
const from = location.state?.from?.pathname || '/';
|
||||
|
||||
// Error messages based on AUTH.md
|
||||
const errorMessages = {
|
||||
cancelled: 'Sign in was cancelled.',
|
||||
unverified: 'Please verify your Google email address first.',
|
||||
invalid_state: 'Session expired. Please try again.',
|
||||
provider_error: 'Google sign in is temporarily unavailable.',
|
||||
auth_failed: 'Authentication failed. Please try again.'
|
||||
};
|
||||
|
||||
// If already authenticated, redirect to intended destination
|
||||
if (!loading && user) {
|
||||
return <Navigate to={from} replace />;
|
||||
}
|
||||
|
||||
// Loading state
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
|
||||
<p className="mt-4 text-gray-600">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="bg-white p-8 rounded-lg shadow-md max-w-md w-full">
|
||||
<div className="text-center mb-8">
|
||||
<h1 className="text-2xl font-bold text-gray-800">Apartment Dashboard</h1>
|
||||
<p className="text-gray-600 mt-2">Sign in to view rental analytics</p>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 p-3 bg-red-50 border border-red-200 text-red-700 rounded-md text-sm">
|
||||
{errorMessages[error] || 'An error occurred. Please try again.'}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={login}
|
||||
className="w-full flex items-center justify-center gap-3 px-4 py-3 border border-gray-300 rounded-md shadow-sm bg-white hover:bg-gray-50 transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
|
||||
>
|
||||
<svg
|
||||
width="18"
|
||||
height="18"
|
||||
viewBox="0 0 18 18"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<g fill="none" fillRule="evenodd">
|
||||
<path
|
||||
d="M17.64 9.205c0-.639-.057-1.252-.164-1.841H9v3.481h4.844a4.14 4.14 0 01-1.796 2.716v2.259h2.908c1.702-1.567 2.684-3.875 2.684-6.615z"
|
||||
fill="#4285F4"
|
||||
/>
|
||||
<path
|
||||
d="M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 009 18z"
|
||||
fill="#34A853"
|
||||
/>
|
||||
<path
|
||||
d="M3.964 10.71A5.41 5.41 0 013.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 000 9c0 1.452.348 2.827.957 4.042l3.007-2.332z"
|
||||
fill="#FBBC05"
|
||||
/>
|
||||
<path
|
||||
d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 00.957 4.958L3.964 7.29C4.672 5.163 6.656 3.58 9 3.58z"
|
||||
fill="#EA4335"
|
||||
/>
|
||||
</g>
|
||||
</svg>
|
||||
<span className="text-gray-700 font-medium">Sign in with Google</span>
|
||||
</button>
|
||||
|
||||
<div className="mt-6 text-center text-xs text-gray-500">
|
||||
<p>By signing in, you agree to access apartment rental analytics</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Login;
|
||||
Reference in New Issue
Block a user