# Feuerwehr Dashboard

A modern, secure web application for managing fire department operations with integrated Authentik SSO authentication.

## Overview

The Feuerwehr Dashboard is a full-stack web application designed specifically for fire departments (Feuerwehr) to manage operations, personnel, and administrative tasks. Built with modern technologies and security best practices, it provides a robust platform for fire service management.

## Features

### Authentication & Security
- OAuth 2.0 / OpenID Connect integration with Authentik
- Secure JWT-based session management
- Role-based access control (RBAC)
- Automatic token refresh
- Rate limiting and security headers (Helmet.js)
- CORS protection

### Dashboard & User Management
- Modern, responsive Material-UI interface
- Real-time user profile management
- Secure user session handling
- Multi-device support
- Dark mode ready

### Service Management
- Extensible service architecture
- Database-backed operations
- RESTful API design
- Health monitoring endpoints

## Tech Stack

### Frontend
- **React 18** - Modern UI library
- **TypeScript** - Type-safe development
- **Material-UI (MUI)** - Component library
- **React Router** - Client-side routing
- **Axios** - HTTP client
- **Vite** - Build tool and dev server
- **Nginx** - Production web server

### Backend
- **Node.js 18+** - Runtime environment
- **Express 5** - Web framework
- **TypeScript** - Type-safe development
- **PostgreSQL 16** - Database
- **jsonwebtoken** - JWT handling
- **Helmet** - Security middleware
- **Winston** - Logging
- **Zod** - Schema validation

### Infrastructure
- **Docker & Docker Compose** - Containerization
- **PostgreSQL 16 Alpine** - Production database
- **Nginx Alpine** - Frontend serving
- **Health checks** - Service monitoring

## Prerequisites

- **Docker** 20.10+ and **Docker Compose** 2.0+
- **Authentik** instance (self-hosted or cloud)
- **Node.js 18+** (for local development)
- **Git**

## Quick Start

Get the dashboard running in 3 simple steps:

### 1. Clone and Configure

```bash
git clone <your-repository-url>
cd feuerwehr_dashboard
cp .env.example .env
```

Edit `.env` with your configuration (see [Environment Variables](#environment-variables) section).

### 2. Configure Authentik

Follow the [Authentik Setup Guide](AUTHENTIK_SETUP.md) to create and configure your OAuth application.

### 3. Deploy

```bash
make prod
# or
./deploy.sh production
```

The dashboard will be available at `http://localhost` (or your configured domain).

## Project Structure

```
feuerwehr_dashboard/
├── backend/                    # Node.js/Express backend
│   ├── src/
│   │   ├── config/            # Configuration files
│   │   ├── controllers/       # Request handlers
│   │   ├── database/          # Database setup and migrations
│   │   ├── middleware/        # Express middleware
│   │   ├── models/            # Data models
│   │   ├── routes/            # API routes
│   │   ├── services/          # Business logic
│   │   ├── types/             # TypeScript types
│   │   ├── utils/             # Utility functions
│   │   ├── app.ts             # Express app setup
│   │   └── server.ts          # Server entry point
│   ├── Dockerfile             # Backend container
│   └── package.json
├── frontend/                   # React/TypeScript frontend
│   ├── src/
│   │   ├── components/        # Reusable components
│   │   ├── contexts/          # React contexts
│   │   ├── pages/             # Page components
│   │   ├── services/          # API services
│   │   ├── theme/             # MUI theme
│   │   ├── types/             # TypeScript types
│   │   ├── utils/             # Utility functions
│   │   ├── App.tsx            # Main app component
│   │   └── main.tsx           # Entry point
│   ├── Dockerfile             # Frontend container
│   ├── nginx.conf             # Nginx configuration
│   └── package.json
├── docker-compose.yml          # Production deployment
├── docker-compose.dev.yml      # Development database
├── .env.example               # Environment template
├── deploy.sh                  # Deployment script
├── Makefile                   # Make commands
├── README.md                  # This file
├── DEPLOYMENT.md              # Deployment guide
├── DEVELOPMENT.md             # Developer guide
├── AUTHENTIK_SETUP.md         # Authentik configuration
├── API_DOCUMENTATION.md       # API reference
├── ARCHITECTURE.md            # System architecture
├── SECURITY.md                # Security guidelines
├── CONTRIBUTING.md            # Contribution guide
└── CHANGELOG.md               # Version history
```

## Development Setup

For local development without Docker, follow these steps:

### 1. Start Development Database

```bash
make dev
# or
./deploy.sh local
```

This starts a PostgreSQL container with development credentials.

### 2. Install Dependencies

```bash
make install
# or manually:
cd backend && npm install
cd ../frontend && npm install
```

### 3. Configure Environment

Backend `.env` (in `backend/.env`):
```bash
DATABASE_URL=postgresql://dev_user:dev_password@localhost:5432/feuerwehr_dev
JWT_SECRET=your_development_secret
NODE_ENV=development
PORT=3000
```

Frontend `.env` (in `frontend/.env`):
```bash
VITE_API_URL=http://localhost:3000
```

### 4. Run Services

Terminal 1 - Backend:
```bash
cd backend
npm run dev
```

Terminal 2 - Frontend:
```bash
cd frontend
npm run dev
```

Access the app at `http://localhost:5173` (Vite dev server).

For more details, see [DEVELOPMENT.md](DEVELOPMENT.md).

## Production Deployment

For complete production deployment instructions, see [DEPLOYMENT.md](DEPLOYMENT.md).

### Quick Production Setup

1. **Configure environment variables** in `.env`:
   - Set strong `POSTGRES_PASSWORD`
   - Generate secure `JWT_SECRET` (use `openssl rand -base64 32`)
   - Configure `CORS_ORIGIN` to match your frontend URL
   - Set Authentik credentials

2. **Deploy all services**:
   ```bash
   make prod
   ```

3. **Verify deployment**:
   ```bash
   docker-compose ps
   make logs-prod
   ```

## Environment Variables

### Required Variables

| Variable | Description | Example |
|----------|-------------|---------|
| `POSTGRES_PASSWORD` | Database password (production) | `SecureP@ssw0rd!` |
| `JWT_SECRET` | JWT signing secret | `openssl rand -base64 32` |
| `AUTHENTIK_CLIENT_ID` | OAuth client ID from Authentik | `abc123...` |
| `AUTHENTIK_CLIENT_SECRET` | OAuth client secret | `xyz789...` |
| `AUTHENTIK_ISSUER` | Authentik issuer URL | `https://auth.example.com/application/o/feuerwehr/` |

### Optional Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `POSTGRES_DB` | Database name | `feuerwehr_prod` |
| `POSTGRES_USER` | Database user | `prod_user` |
| `POSTGRES_PORT` | Database port | `5432` |
| `BACKEND_PORT` | Backend API port | `3000` |
| `FRONTEND_PORT` | Frontend port | `80` |
| `NODE_ENV` | Node environment | `production` |
| `CORS_ORIGIN` | Allowed frontend origin | `http://localhost:80` |
| `VITE_API_URL` | Frontend API URL | `http://localhost:3000` |

For complete documentation, see [.env.example](.env.example).

## Available Commands

### Using Make (Recommended)

```bash
# Development
make dev          # Start local development database
make logs-dev     # Show development logs
make rebuild-dev  # Rebuild development services

# Production
make prod         # Deploy production environment
make logs-prod    # Show production logs
make rebuild      # Rebuild production services

# General
make stop         # Stop all services
make clean        # Remove all containers, volumes, and images
make install      # Install all dependencies
make test         # Run tests
make help         # Show all available commands
```

### Using Deploy Script

```bash
./deploy.sh production    # Deploy production
./deploy.sh local         # Start local dev database
./deploy.sh stop          # Stop all services
./deploy.sh logs          # Show production logs
./deploy.sh rebuild       # Rebuild services
./deploy.sh clean         # Clean up everything
```

## Troubleshooting

### Database Connection Failed

**Symptoms**: Backend logs show database connection errors

**Solutions**:
```bash
# Check if database is running
docker-compose ps

# View database logs
make logs-dev  # or logs-prod

# Restart database
docker-compose restart postgres

# Verify credentials in .env match docker-compose.yml
```

### Authentication Not Working

**Symptoms**: Login redirects fail or return errors

**Solutions**:
1. Verify Authentik configuration (see [AUTHENTIK_SETUP.md](AUTHENTIK_SETUP.md))
2. Check redirect URIs match exactly
3. Verify `AUTHENTIK_CLIENT_ID` and `AUTHENTIK_CLIENT_SECRET` in `.env`
4. Check browser console for CORS errors
5. Ensure `CORS_ORIGIN` matches your frontend URL

### Port Already in Use

**Symptoms**: Docker fails to start with "port already allocated"

**Solutions**:
```bash
# Find what's using the port
lsof -i :3000  # or :80, :5432

# Change ports in .env
BACKEND_PORT=3001
FRONTEND_PORT=8080
POSTGRES_PORT=5433
```

### Frontend Can't Reach Backend

**Symptoms**: API calls fail with network errors

**Solutions**:
1. Verify `VITE_API_URL` in `.env` matches backend URL
2. Check `CORS_ORIGIN` in backend allows frontend URL
3. Ensure backend is running: `curl http://localhost:3000/health`
4. Check network connectivity between containers

### Complete Reset

If all else fails:
```bash
make clean  # Removes everything
make prod   # Fresh deployment
```

For more issues, see [DEVELOPMENT.md](DEVELOPMENT.md#common-issues).

## API Documentation

See [API_DOCUMENTATION.md](API_DOCUMENTATION.md) for complete API reference.

### Quick API Overview

- `POST /api/auth/callback` - Handle OAuth callback
- `POST /api/auth/refresh` - Refresh access token
- `POST /api/auth/logout` - Logout user
- `GET /api/user/me` - Get current user
- `GET /health` - Health check endpoint

## Security

This application implements security best practices:

- OAuth 2.0 / OpenID Connect authentication
- JWT-based stateless sessions
- HTTP security headers (Helmet.js)
- CORS protection
- Rate limiting
- SQL injection protection (parameterized queries)
- XSS protection
- Secure password handling (delegated to Authentik)

For security guidelines and reporting vulnerabilities, see [SECURITY.md](SECURITY.md).

## Contributing

We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for:

- Code style guidelines
- Development workflow
- Pull request process
- Issue reporting

## Architecture

For system architecture, component diagrams, and data flow, see [ARCHITECTURE.md](ARCHITECTURE.md).

## Changelog

See [CHANGELOG.md](CHANGELOG.md) for version history and release notes.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Support

For questions or issues:

1. Check [Troubleshooting](#troubleshooting) section
2. Review relevant documentation files
3. Search existing issues
4. Create a new issue with detailed information

## Acknowledgments

- Built with modern open-source technologies
- Designed for fire department operations management
- Inspired by the need for secure, user-friendly emergency services software
