Added auth, environment brief, docker for db_migrations,frontend,backend.

This commit is contained in:
2025-12-15 23:40:34 +01:00
parent 3ab81fad8c
commit 1a5bef277d
36 changed files with 1059 additions and 132 deletions

13
frontend/.dockerignore Normal file
View File

@@ -0,0 +1,13 @@
node_modules
dist
.env
.env.local
.env.*.local
npm-debug.log*
.DS_Store
.vscode
.idea
*.swp
*.swo
*.log
coverage

22
frontend/Dockerfile Normal file
View File

@@ -0,0 +1,22 @@
FROM node:22-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

View File

@@ -1,73 +1,111 @@
# React + TypeScript + Vite
# IoT Dashboard Frontend
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
React-based dashboard for visualizing IoT telemetry data with customizable widgets.
Currently, two official plugins are available:
## Technology Stack
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
| Technology | Purpose |
|------------|---------|
| React 19 | UI framework |
| Vite | Build tool and dev server |
| TypeScript | Type safety |
| DaisyUI | Component library |
| Tailwind CSS | Styling |
| React Query | Data fetching and caching |
| Recharts | Data visualization |
| React Grid Layout | Drag-and-drop widget layout |
## React Compiler
## Features
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
- Customizable widget-based dashboard
- Drag-and-drop layout editing
- Multiple widget types (weather, charts, calendar, AI briefings)
- Responsive design
- Dark/light theme support
## Expanding the ESLint configuration
## Widget Types
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
| Widget | Description |
|--------|-------------|
| WeatherWidget | Current weather and forecast |
| AirQualityWidget | PM2.5, PM10 levels from pulse.eco |
| ComfortIndexWidget | Indoor comfort based on temperature/humidity |
| RunSuitabilityWidget | Outdoor running conditions analysis |
| CalendarWidget | iCal calendar integration |
| DailyBriefingWidget | AI-generated daily summary |
| HealthStatsWidget | Health metrics from wearables |
| TelemetryChartWidget | Time-series data visualization |
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
## Project Structure
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
frontend/
├── src/
│ ├── api/ # API client functions
│ ├── components/ # React components
├── widgets/ # Widget components
│ │ └── ...
├── hooks/ # Custom React hooks
│ ├── types/ # TypeScript type definitions
│ ├── utils/ # Utility functions
│ ├── App.tsx # Main application component
└── main.tsx # Entry point
├── public/ # Static assets
├── package.json # Dependencies
└── vite.config.ts # Vite configuration
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
## Running
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```bash
cd frontend
npm install
npm run dev
```
Development server runs at http://localhost:5173
## Configuration
The frontend connects to the Django API. Configure the API URL in `vite.config.ts`:
```typescript
proxy: {
'/api': {
target: 'http://localhost:8000',
changeOrigin: true,
},
}
```
## Building for Production
```bash
npm run build
```
Output is in the `dist/` directory.
## Key Components
| Component | Purpose |
|-----------|---------|
| Dashboard.tsx | Main dashboard with widget grid |
| WidgetWrapper.tsx | Generic widget container |
| EditWidgetModal.tsx | Widget configuration modal |
| AddWidgetMenu.tsx | Widget type selection |
## API Integration
All API calls are in `src/api/index.ts`. Uses React Query for:
- Automatic caching
- Background refetching
- Loading/error states
Example:
```typescript
const { data, isLoading } = useQuery({
queryKey: ['weather', city],
queryFn: () => fetchWeather(city),
});
```

36
frontend/nginx.conf Normal file
View File

@@ -0,0 +1,36 @@
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
# Gzip compression
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml+rss application/javascript application/json;
# SPA routing - serve index.html for all routes
location / {
try_files $uri $uri/ /index.html;
}
# Proxy API requests to Django backend
location /api/ {
proxy_pass http://django:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
}
# Cache static assets
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}

View File

@@ -24,7 +24,8 @@
"react-hook-form": "^7.66.1",
"react-hot-toast": "^2.6.0",
"react-router-dom": "^7.9.6",
"recharts": "^3.4.1"
"recharts": "^3.4.1",
"tailwind-merge": "^3.4.0"
},
"devDependencies": {
"@eslint/js": "^9.36.0",
@@ -4957,6 +4958,16 @@
"node": ">=8"
}
},
"node_modules/tailwind-merge": {
"version": "3.4.0",
"resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.4.0.tgz",
"integrity": "sha512-uSaO4gnW+b3Y2aWoWfFpX62vn2sR3skfhbjsEnaBI81WD1wBLlHZe5sWf0AqjksNdYTbGBEd0UasQMT3SNV15g==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/dcastil"
}
},
"node_modules/tailwindcss": {
"version": "4.1.17",
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.1.17.tgz",

View File

@@ -26,7 +26,8 @@
"react-hook-form": "^7.66.1",
"react-hot-toast": "^2.6.0",
"react-router-dom": "^7.9.6",
"recharts": "^3.4.1"
"recharts": "^3.4.1",
"tailwind-merge": "^3.4.0"
},
"devDependencies": {
"@eslint/js": "^9.36.0",

View File

@@ -1,16 +1,25 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { BrowserRouter, Routes, Route, Link, NavLink } from 'react-router-dom'
import { BrowserRouter, Routes, Route, Link, NavLink, Navigate } from 'react-router-dom'
import { Toaster } from 'react-hot-toast'
import { WellnessStateProvider } from './hooks/useWellnessState'
import { AuthProvider, useAuth } from './contexts/AuthContext'
import Dashboard from './pages/Dashboard'
import DeviceList from './pages/DeviceList'
import DeviceDetail from './pages/DeviceDetail'
import AddDevice from './pages/AddDevice'
import Login from './pages/Login'
import './App.css'
const queryClient = new QueryClient()
function ProtectedRoute({ children }: { children: React.ReactNode }) {
const { isAuthenticated } = useAuth()
return isAuthenticated ? <>{children}</> : <Navigate to="/login" />
}
function AppLayout({ children }: { children: React.ReactNode }) {
const { logout } = useAuth()
return (
<div className="drawer lg:drawer-open">
<input id="main-drawer" type="checkbox" className="drawer-toggle" />
@@ -27,6 +36,11 @@ function AppLayout({ children }: { children: React.ReactNode }) {
<div className="flex-1">
<span className="text-xl font-bold">IoT Dashboard</span>
</div>
<div className="flex-none">
<button onClick={logout} className="btn btn-ghost btn-sm">
Logout
</button>
</div>
</div>
{/* Page content */}
@@ -38,7 +52,7 @@ function AppLayout({ children }: { children: React.ReactNode }) {
{/* Sidebar */}
<div className="drawer-side">
<label htmlFor="main-drawer" className="drawer-overlay"></label>
<aside className="bg-base-100 w-64 min-h-full">
<aside className="bg-base-100 w-64 min-h-full flex flex-col">
<div className="p-4">
<Link to="/" className="flex items-center gap-2 text-2xl font-bold">
<svg xmlns="http://www.w3.org/2000/svg" className="h-8 w-8" fill="none" viewBox="0 0 24 24" stroke="currentColor">
@@ -73,6 +87,15 @@ function AppLayout({ children }: { children: React.ReactNode }) {
</NavLink>
</li>
</ul>
<div className="mt-auto p-4">
<button onClick={logout} className="btn btn-ghost btn-sm w-full">
<svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
</svg>
Logout
</button>
</div>
</aside>
</div>
</div>
@@ -82,17 +105,21 @@ function AppLayout({ children }: { children: React.ReactNode }) {
function App() {
return (
<QueryClientProvider client={queryClient}>
<WellnessStateProvider>
<BrowserRouter>
<Toaster position="top-right" />
<Routes>
<Route path="/" element={<AppLayout><Dashboard /></AppLayout>} />
<Route path="/devices" element={<AppLayout><DeviceList /></AppLayout>} />
<Route path="/devices/add" element={<AppLayout><AddDevice /></AppLayout>} />
<Route path="/devices/:id" element={<AppLayout><DeviceDetail /></AppLayout>} />
</Routes>
</BrowserRouter>
</WellnessStateProvider>
<AuthProvider>
<WellnessStateProvider>
<BrowserRouter>
<Toaster position="top-right" />
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/" element={<ProtectedRoute><AppLayout><Dashboard /></AppLayout></ProtectedRoute>} />
<Route path="/dashboard" element={<ProtectedRoute><AppLayout><Dashboard /></AppLayout></ProtectedRoute>} />
<Route path="/devices" element={<ProtectedRoute><AppLayout><DeviceList /></AppLayout></ProtectedRoute>} />
<Route path="/devices/add" element={<ProtectedRoute><AppLayout><AddDevice /></AppLayout></ProtectedRoute>} />
<Route path="/devices/:id" element={<ProtectedRoute><AppLayout><DeviceDetail /></AppLayout></ProtectedRoute>} />
</Routes>
</BrowserRouter>
</WellnessStateProvider>
</AuthProvider>
</QueryClientProvider>
)
}

View File

@@ -113,7 +113,7 @@ export default function AddWidgetModal({ isOpen, onClose, onAdd }: AddWidgetModa
defaultTitle = `Run Suitability - ${city}`
} else if (widgetType === 'health-stats') {
const selectedDevice = devices.find(d => d.id === selectedDevices[0])
defaultTitle = `Health StaTts - ${selectedDevice?.name || 'Device'}`
defaultTitle = `Health Stats - ${selectedDevice?.name || 'Device'}`
} else if (widgetType === 'calendar') {
defaultTitle = 'Calendar Agenda'
} else if (widgetType === 'daily-briefing') {

View File

@@ -0,0 +1,50 @@
import { createContext, useContext, useState, useEffect, type ReactNode } from 'react'
import { apiClient } from '../lib/api-client'
interface AuthContextType {
isAuthenticated: boolean
login: (username: string, password: string) => Promise<void>
logout: () => void
}
const AuthContext = createContext<AuthContextType | undefined>(undefined)
export function AuthProvider({ children }: { children: ReactNode }) {
const [token, setToken] = useState<string | null>(
() => localStorage.getItem('access_token')
)
useEffect(() => {
if (token) {
apiClient.defaults.headers.common['Authorization'] = `Bearer ${token}`
} else {
delete apiClient.defaults.headers.common['Authorization']
}
}, [token])
const login = async (username: string, password: string) => {
const response = await apiClient.post('/auth/login/', { username, password })
const { access, refresh } = response.data
localStorage.setItem('access_token', access)
localStorage.setItem('refresh_token', refresh)
setToken(access)
}
const logout = () => {
localStorage.removeItem('access_token')
localStorage.removeItem('refresh_token')
setToken(null)
}
return (
<AuthContext.Provider value={{ isAuthenticated: !!token, login, logout }}>
{children}
</AuthContext.Provider>
)
}
export const useAuth = () => {
const context = useContext(AuthContext)
if (!context) throw new Error('useAuth must be used within AuthProvider')
return context
}

View File

@@ -4,7 +4,7 @@ import 'gridstack/dist/gridstack.min.css'
// Define the widget type based on gridstack.js structure
export type GridStackWidget = {
id?: string | number
id?: string
x?: number
y?: number
w?: number
@@ -74,7 +74,7 @@ export function useGridstack(options: UseGridstackOptions = {}) {
// Handle layout change
if (onLayoutChange) {
grid.on('change', (event, items) => {
grid.on('change', () => {
const serialized = grid.save(false) as GridStackWidget[]
onLayoutChange(serialized)
})

View File

@@ -1,4 +1,4 @@
import { createContext, useContext, useState, ReactNode } from 'react'
import { createContext, useContext, useState, type ReactNode } from 'react'
interface WellnessState {
healthDeviceId: string | null

View File

@@ -10,11 +10,47 @@ export const apiClient = axios.create({
},
});
// Add response interceptor for error handling
// Add token from localStorage on initialization
const token = localStorage.getItem('access_token');
if (token) {
apiClient.defaults.headers.common['Authorization'] = `Bearer ${token}`;
}
// Add response interceptor for token refresh on 401
apiClient.interceptors.response.use(
(response) => response,
(error) => {
// Basic error handling - can be extended if needed
async (error) => {
const originalRequest = error.config;
// Handle 401 errors with token refresh
if (error.response?.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
try {
const refreshToken = localStorage.getItem('refresh_token');
if (!refreshToken) {
throw new Error('No refresh token');
}
const response = await axios.post(`${API_BASE_URL}/auth/refresh/`, {
refresh: refreshToken
});
const { access } = response.data;
localStorage.setItem('access_token', access);
apiClient.defaults.headers.common['Authorization'] = `Bearer ${access}`;
originalRequest.headers['Authorization'] = `Bearer ${access}`;
return apiClient(originalRequest);
} catch (refreshError) {
// Refresh failed - clear tokens and redirect to login
localStorage.removeItem('access_token');
localStorage.removeItem('refresh_token');
window.location.href = '/login';
return Promise.reject(refreshError);
}
}
return Promise.reject(error);
}
);

View File

@@ -0,0 +1,71 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '../contexts/AuthContext'
export default function Login() {
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const { login } = useAuth()
const navigate = useNavigate()
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError('')
setLoading(true)
try {
await login(username, password)
navigate('/dashboard')
} catch (err: any) {
setError(err.response?.data?.detail || 'Invalid credentials')
} finally {
setLoading(false)
}
}
return (
<div className="min-h-screen flex items-center justify-center bg-base-200">
<div className="card w-96 bg-base-100 shadow-xl">
<div className="card-body">
<h2 className="card-title text-2xl mb-4">IoT Dashboard Login</h2>
{error && <div className="alert alert-error text-sm">{error}</div>}
<form onSubmit={handleSubmit} className="space-y-4">
<div className="form-control">
<label className="label">
<span className="label-text">Username</span>
</label>
<input
type="text"
className="input input-bordered"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
autoFocus
/>
</div>
<div className="form-control">
<label className="label">
<span className="label-text">Password</span>
</label>
<input
type="password"
className="input input-bordered"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</div>
<button
type="submit"
className="btn btn-primary w-full"
disabled={loading}
>
{loading ? <span className="loading loading-spinner" /> : 'Login'}
</button>
</form>
</div>
</div>
</div>
)
}