Compare commits

...

2 Commits

Author SHA1 Message Date
49923adcd2 add 2025-08-21 15:29:34 +02:00
d5f8de1e4c add Keycloak, add better canvas 2025-08-21 15:26:35 +02:00
15 changed files with 1424 additions and 106 deletions

View File

@@ -51,6 +51,12 @@ EXPORT_PATH=./exports/ # Speicherort für SVG-Exports
ENABLE_AUTOMATIC_EVENTS=false # Automatische Events deaktiviert
EVENT_DURATION_MINUTES=30 # Event-Dauer
EVENT_INTERVAL_HOURS=6 # Abstand zwischen Events
# Keycloak Authentifizierung (optional)
ENABLE_KEYCLOAK=false # Keycloak-Authentifizierung
KEYCLOAK_REALM=rplace # Keycloak Realm Name
KEYCLOAK_AUTH_URL=http://localhost:8080 # Keycloak Server URL
KEYCLOAK_CLIENT_ID=rplace-client # Keycloak Client ID Events
```
## Schritt 4: PostgreSQL Datenbank einrichten (optional)

96
KEYCLOAK_SETUP.md Normal file
View File

@@ -0,0 +1,96 @@
# Keycloak Setup für r/place
## Keycloak Installation
### Docker (Empfohlen)
```bash
docker run -d \
--name keycloak \
-p 8080:8080 \
-e KEYCLOAK_ADMIN=admin \
-e KEYCLOAK_ADMIN_PASSWORD=admin \
quay.io/keycloak/keycloak:latest \
start-dev
```
### Standalone Installation
1. Lade Keycloak von https://www.keycloak.org/downloads herunter
2. Entpacke das Archiv
3. Starte Keycloak: `bin/kc.sh start-dev`
## Konfiguration
### 1. Admin Console öffnen
Gehe zu http://localhost:8080/admin und melde dich mit admin/admin an.
### 2. Realm erstellen
1. Klicke auf "Create Realm"
2. Name: `rplace`
3. Klicke "Create"
### 3. Client erstellen
1. Gehe zu "Clients" → "Create client"
2. Client ID: `rplace-client`
3. Client type: `OpenID Connect`
4. Klicke "Next"
5. Client authentication: `OFF` (Public client)
6. Standard flow: `ON`
7. Direct access grants: `ON`
8. Klicke "Save"
### 4. Client Settings
1. Gehe zu deinem Client `rplace-client`
2. Settings Tab:
- Valid redirect URIs: `http://localhost:5000/*`
- Valid post logout redirect URIs: `http://localhost:5000/*`
- Web origins: `http://localhost:5000`
3. Klicke "Save"
### 5. Test User erstellen
1. Gehe zu "Users" → "Add user"
2. Username: `testuser`
3. Klicke "Create"
4. Gehe zum "Credentials" Tab
5. Setze ein Passwort und deaktiviere "Temporary"
## r/place Konfiguration
Bearbeite `config.cfg`:
```ini
ENABLE_KEYCLOAK=true
KEYCLOAK_REALM=rplace
KEYCLOAK_AUTH_URL=http://localhost:8080
KEYCLOAK_CLIENT_ID=rplace-client
```
## Erweiterte Konfiguration
### HTTPS (Produktion)
Für Produktionsumgebungen:
```ini
KEYCLOAK_AUTH_URL=https://dein-keycloak-server.de
```
### Benutzer-Attribute
Du kannst zusätzliche Benutzerattribute in Keycloak konfigurieren:
1. Gehe zu "Client scopes"
2. Bearbeite "profile" scope
3. Füge Mappers für zusätzliche Attribute hinzu
### Sicherheit
- Ändere Admin-Passwort
- Konfiguriere SSL/TLS
- Setze starke Passwort-Richtlinien
- Aktiviere Brute-Force-Schutz
## Fehlerbehebung
### CORS-Probleme
Stelle sicher, dass die Web origins korrekt konfiguriert sind.
### Token-Probleme
Überprüfe die Client-Konfiguration und Redirect-URIs.
### Verbindungsprobleme
Stelle sicher, dass Keycloak erreichbar ist und die URLs korrekt sind.

View File

@@ -0,0 +1,58 @@
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { getAuthStatus, type AuthStatus } from "@/lib/config";
export function AuthBanner() {
const [authStatus, setAuthStatus] = useState<AuthStatus | null>(null);
useEffect(() => {
getAuthStatus().then(setAuthStatus);
}, []);
if (!authStatus?.keycloakEnabled) {
return null;
}
if (authStatus.authenticated) {
return (
<div className="bg-green-50 border-b border-green-200 p-3">
<div className="flex items-center justify-between max-w-7xl mx-auto">
<div className="flex items-center gap-2">
<span className="text-green-700 font-medium">
Angemeldet als {authStatus.user?.username}
</span>
</div>
<Button
variant="outline"
size="sm"
onClick={() => window.location.href = "/logout"}
className="border-green-300 text-green-700 hover:bg-green-100"
>
Abmelden
</Button>
</div>
</div>
);
}
return (
<div className="bg-blue-50 border-b border-blue-200 p-3">
<div className="flex items-center justify-between max-w-7xl mx-auto">
<div className="flex items-center gap-2">
<span className="text-blue-700">
Melde dich an, um Pixel zu platzieren
</span>
</div>
<Button
onClick={() => window.location.href = "/login"}
className="bg-blue-600 hover:bg-blue-700 text-white"
size="sm"
>
Anmelden
</Button>
</div>
</div>
);
}

View File

@@ -1,3 +1,4 @@
import { useEffect, useRef, useState, useCallback } from "react";
import { Pixel } from "@shared/schema";
import { cn } from "@/lib/utils";
@@ -22,9 +23,11 @@ export function OptimizedCanvas({
const canvasRef = useRef<HTMLCanvasElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const [zoom, setZoom] = useState(1);
const [pixelSize, setPixelSize] = useState(8);
const pixelSize = Math.max(2, 8 * zoom);
const [mouseCoords, setMouseCoords] = useState<{x: number, y: number} | null>(null);
const [previewPixel, setPreviewPixel] = useState<{x: number, y: number} | null>(null);
const [isPanning, setIsPanning] = useState(false);
const [lastPanPosition, setLastPanPosition] = useState<{x: number, y: number} | null>(null);
// Create pixel map for O(1) lookup
const pixelMap = new Map<string, string>();
@@ -117,10 +120,6 @@ export function OptimizedCanvas({
drawCanvas();
}, [drawCanvas]);
useEffect(() => {
setPixelSize(Math.max(2, 8 * zoom));
}, [zoom]);
const getPixelCoordinates = (event: React.MouseEvent<HTMLCanvasElement>) => {
const canvas = canvasRef.current;
if (!canvas) return null;
@@ -158,18 +157,114 @@ export function OptimizedCanvas({
const handleCanvasMouseLeave = () => {
setMouseCoords(null);
setPreviewPixel(null);
setIsPanning(false);
setLastPanPosition(null);
};
const handleMouseDown = (e: React.MouseEvent) => {
// Mittlere Maustaste (Button 1)
if (e.button === 1) {
e.preventDefault();
setIsPanning(true);
setLastPanPosition({ x: e.clientX, y: e.clientY });
}
};
const handleMouseUp = (e: React.MouseEvent) => {
if (e.button === 1) {
e.preventDefault();
setIsPanning(false);
setLastPanPosition(null);
}
};
const handleMouseMoveContainer = (e: React.MouseEvent) => {
if (isPanning && lastPanPosition && containerRef.current) {
e.preventDefault();
const deltaX = e.clientX - lastPanPosition.x;
const deltaY = e.clientY - lastPanPosition.y;
const container = containerRef.current;
container.scrollLeft -= deltaX;
container.scrollTop -= deltaY;
setLastPanPosition({ x: e.clientX, y: e.clientY });
}
};
const zoomToPoint = (newZoom: number, mouseX?: number, mouseY?: number) => {
const container = containerRef.current;
if (!container) return;
const clampedZoom = Math.max(0.1, Math.min(newZoom, 5));
if (Math.abs(clampedZoom - zoom) < 0.01) return;
const oldPixelSize = pixelSize;
const newPixelSize = Math.max(2, 8 * clampedZoom);
// Aktuelle Scroll-Position
const currentScrollLeft = container.scrollLeft;
const currentScrollTop = container.scrollTop;
let zoomPointX, zoomPointY;
if (mouseX !== undefined && mouseY !== undefined) {
// Zoomen an Mausposition
const containerRect = container.getBoundingClientRect();
const relativeMouseX = mouseX - containerRect.left;
const relativeMouseY = mouseY - containerRect.top;
// Canvas-Koordinaten der Mausposition
zoomPointX = (currentScrollLeft + relativeMouseX - 32) / oldPixelSize;
zoomPointY = (currentScrollTop + relativeMouseY - 32) / oldPixelSize;
setZoom(clampedZoom);
// Neue Scroll-Position berechnen, damit Mausposition gleich bleibt
requestAnimationFrame(() => {
const newScrollLeft = zoomPointX * newPixelSize + 32 - relativeMouseX;
const newScrollTop = zoomPointY * newPixelSize + 32 - relativeMouseY;
container.scrollTo({
left: Math.max(0, Math.min(newScrollLeft, container.scrollWidth - container.clientWidth)),
top: Math.max(0, Math.min(newScrollTop, container.scrollHeight - container.clientHeight)),
behavior: 'auto'
});
});
} else {
// Zoomen im Center des Viewports
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
zoomPointX = (currentScrollLeft + containerWidth / 2 - 32) / oldPixelSize;
zoomPointY = (currentScrollTop + containerHeight / 2 - 32) / oldPixelSize;
setZoom(clampedZoom);
requestAnimationFrame(() => {
const newScrollLeft = zoomPointX * newPixelSize + 32 - containerWidth / 2;
const newScrollTop = zoomPointY * newPixelSize + 32 - containerHeight / 2;
container.scrollTo({
left: Math.max(0, Math.min(newScrollLeft, container.scrollWidth - container.clientWidth)),
top: Math.max(0, Math.min(newScrollTop, container.scrollHeight - container.clientHeight)),
behavior: 'smooth'
});
});
}
};
const handleZoomIn = () => {
setZoom(prev => Math.min(prev * 1.2, 3));
zoomToPoint(zoom * 1.2);
};
const handleZoomOut = () => {
setZoom(prev => Math.max(prev / 1.2, 0.5));
zoomToPoint(zoom / 1.2);
};
const handleResetZoom = () => {
setZoom(1);
zoomToPoint(1);
};
const handleWheel = (e: React.WheelEvent) => {
@@ -178,23 +273,39 @@ export function OptimizedCanvas({
const zoomFactor = 1.1;
const delta = e.deltaY;
let newZoom;
if (delta < 0) {
setZoom(prev => Math.min(prev * zoomFactor, 3));
newZoom = zoom * zoomFactor;
} else {
setZoom(prev => Math.max(prev / zoomFactor, 0.5));
newZoom = zoom / zoomFactor;
}
zoomToPoint(newZoom, e.clientX, e.clientY);
};
return (
<div className="flex-1 relative bg-canvas-bg overflow-hidden">
<div
ref={containerRef}
className="w-full h-full overflow-auto p-8 scroll-smooth canvas-container"
className={cn(
"w-full h-full overflow-auto p-8 canvas-container",
isPanning && "cursor-grabbing select-none"
)}
onWheel={handleWheel}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
onMouseMove={handleMouseMoveContainer}
onMouseLeave={() => {
setIsPanning(false);
setLastPanPosition(null);
}}
data-testid="canvas-container"
style={{
scrollBehavior: isPanning ? 'auto' : 'auto'
}}
>
{/* Coordinate System Container */}
<div className="relative inline-block canvas-zoom">
<div className="relative inline-block">
{/* Top X-axis coordinates */}
<div className="flex ml-8 mb-1">
{Array.from({ length: Math.ceil(canvasWidth / 10) }, (_, i) => (
@@ -203,7 +314,7 @@ export function OptimizedCanvas({
className="text-xs text-gray-400 text-center"
style={{
width: `${10 * pixelSize}px`,
fontSize: `${Math.max(8, pixelSize * 0.8)}px`
fontSize: `${Math.max(8, Math.min(12, pixelSize * 0.8))}px`
}}
>
{i * 10}
@@ -222,7 +333,7 @@ export function OptimizedCanvas({
style={{
height: `${10 * pixelSize}px`,
width: '24px',
fontSize: `${Math.max(8, pixelSize * 0.8)}px`
fontSize: `${Math.max(8, Math.min(12, pixelSize * 0.8))}px`
}}
>
{i * 10}
@@ -234,12 +345,13 @@ export function OptimizedCanvas({
<canvas
ref={canvasRef}
className={cn(
"border border-gray-400 cursor-pointer",
cooldownActive && "cursor-not-allowed"
"border border-gray-400",
isPanning ? "cursor-grabbing" : cooldownActive ? "cursor-not-allowed" : "cursor-pointer"
)}
onClick={handleCanvasClick}
onMouseMove={handleCanvasMouseMove}
onMouseLeave={handleCanvasMouseLeave}
onContextMenu={(e) => e.preventDefault()} // Verhindert Rechtsklick-Menü
data-testid="pixel-canvas"
/>
</div>
@@ -247,48 +359,63 @@ export function OptimizedCanvas({
</div>
{/* Zoom Controls */}
<div className="absolute top-4 right-4 flex flex-col gap-2 bg-white/80 p-2 rounded shadow">
<div className="absolute top-4 right-4 flex flex-col gap-2 bg-white/90 p-3 rounded-lg shadow-lg">
<button
onClick={handleZoomIn}
className="px-2 py-1 bg-blue-500 text-white rounded text-sm hover:bg-blue-600"
className="px-3 py-2 bg-blue-500 text-white rounded text-sm font-semibold hover:bg-blue-600 transition-colors"
data-testid="button-zoom-in"
disabled={zoom >= 5}
>
+
</button>
<button
onClick={handleZoomOut}
className="px-2 py-1 bg-blue-500 text-white rounded text-sm hover:bg-blue-600"
className="px-3 py-2 bg-blue-500 text-white rounded text-sm font-semibold hover:bg-blue-600 transition-colors"
data-testid="button-zoom-out"
disabled={zoom <= 0.1}
>
-
</button>
<button
onClick={handleResetZoom}
className="px-2 py-1 bg-gray-500 text-white rounded text-xs hover:bg-gray-600"
className="px-2 py-1 bg-gray-500 text-white rounded text-xs font-semibold hover:bg-gray-600 transition-colors"
data-testid="button-zoom-reset"
>
100%
</button>
<div className="text-xs text-gray-600 text-center font-mono">
{Math.round(zoom * 100)}%
</div>
</div>
{/* Info Display */}
<div className="absolute bottom-4 left-4 bg-white/80 p-3 rounded shadow text-sm">
<div className="text-xs text-gray-600">
Canvas: {canvasWidth}x{canvasHeight}
<div className="absolute bottom-4 left-4 bg-white/90 p-3 rounded-lg shadow-lg text-sm">
<div className="text-xs text-gray-600 font-semibold">
Canvas: {canvasWidth}×{canvasHeight}
</div>
<div className="text-xs text-gray-400">
Zoom: {Math.round(zoom * 100)}%
<div className="text-xs text-gray-500 mt-1">
Pixel: {pixelSize}px | Zoom: {Math.round(zoom * 100)}%
</div>
{mouseCoords && (
<div className="text-xs text-green-400 mt-1">
Mouse: ({mouseCoords.x}, {mouseCoords.y})
<div className="text-xs text-green-600 mt-2 font-mono">
Position: ({mouseCoords.x}, {mouseCoords.y})
</div>
)}
{previewPixel && !cooldownActive && (
<div className="text-xs text-blue-400 mt-1">
<div className="text-xs text-blue-600 mt-1">
Vorschau: {selectedColor}
</div>
)}
{cooldownActive && (
<div className="text-xs text-red-500 mt-1 font-semibold">
Cooldown aktiv
</div>
)}
{isPanning && (
<div className="text-xs text-blue-500 mt-1 font-semibold">
Bewege Canvas (Mittlere Maustaste)
</div>
)}
</div>
</div>
);

View File

@@ -131,31 +131,49 @@
100% { background-position: 20px 20px; }
}
/* Smooth scrolling für den gesamten Container */
.scroll-smooth {
scroll-behavior: smooth;
}
/* Canvas zoom transitions */
.canvas-zoom {
transition: transform 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}
/* Geschmeidiges Mausrad-Scrolling */
/* Canvas container optimiert für glattes Zoomen */
.canvas-container {
scroll-behavior: smooth;
scroll-behavior: auto; /* Für präzises Zoom-Verhalten */
}
/* Optimierte Pixel-Hover-Effekte */
.pixel {
transition: transform 0.15s ease-out, box-shadow 0.15s ease-out, opacity 0.1s ease-out;
.canvas-container:not(:hover) {
scroll-behavior: smooth; /* Smooth nur wenn nicht gehovered */
}
.pixel:hover {
transform: scale(1.1);
z-index: 10;
position: relative;
box-shadow: 0 0 8px rgba(255, 255, 255, 0.3);
/* Zoom Controls */
.canvas-container * {
image-rendering: pixelated;
image-rendering: -moz-crisp-edges;
image-rendering: crisp-edges;
}
/* Optimierte Performance für große Canvas */
.canvas-container canvas {
will-change: transform;
backface-visibility: hidden;
}
/* Smooth transitions für UI Elemente */
.zoom-controls {
transition: opacity 0.2s ease, transform 0.2s ease;
}
/* Pixel-perfekte Rendering */
canvas {
image-rendering: pixelated;
image-rendering: -moz-crisp-edges;
image-rendering: crisp-edges;
}
/* Verbesserte Hover-Effekte */
.canvas-container:hover {
cursor: crosshair;
}
/* Info Panel Styling */
.info-panel {
backdrop-filter: blur(8px);
border: 1px solid rgba(255, 255, 255, 0.2);
}
/* Pixel-Vorschau */

View File

@@ -29,7 +29,7 @@ export const COLORS = [
"#ffb470", // Beige
"#000000", // Black
"#515252", // Dark Gray
"#898d90", // Gray
"#898989", // Gray
"#d4d7d9", // Light Gray
"#ffffff", // White
] as const;
@@ -48,3 +48,24 @@ export function generateUserId(): string {
export function getUsername(): string {
return generateUserId();
}
export const API_BASE = "/api";
export interface AuthStatus {
authenticated: boolean;
keycloakEnabled: boolean;
user?: {
userId: string;
username: string;
};
}
export async function getAuthStatus(): Promise<AuthStatus> {
try {
const response = await fetch(`${API_BASE}/auth/status`);
return await response.json();
} catch (error) {
console.error("Failed to get auth status:", error);
return { authenticated: false, keycloakEnabled: false };
}
}

View File

@@ -11,6 +11,7 @@ import { useToast } from "@/hooks/use-toast";
import { DEFAULT_SELECTED_COLOR, generateUserId, getUsername } from "@/lib/config";
import { Pixel, CanvasConfig, InsertPixel, WSMessage } from "@shared/schema";
import { apiRequest } from "@/lib/queryClient";
import { AuthBanner } from "@/components/auth-banner";
export default function CanvasPage() {
const [selectedColor, setSelectedColor] = useState(DEFAULT_SELECTED_COLOR);
@@ -146,6 +147,7 @@ export default function CanvasPage() {
return (
<div className="h-screen flex flex-col bg-canvas-bg text-white">
<AuthBanner />
{/* Header */}
<header className="bg-panel-bg border-b border-gray-700 px-4 py-3 flex items-center justify-between">
<div className="flex items-center space-x-4">

View File

@@ -2,11 +2,11 @@
# Ändere diese Werte um die Canvas-Einstellungen anzupassen
# Canvas Dimensionen
CANVAS_WIDTH=100
CANVAS_HEIGHT=100
CANVAS_WIDTH=500
CANVAS_HEIGHT=200
# Cooldown Einstellungen (in Sekunden)
DEFAULT_COOLDOWN=5
DEFAULT_COOLDOWN=10
# Automatische Events (true/false)
# Wenn aktiviert, gibt es keine Cooldowns
@@ -14,10 +14,16 @@ ENABLE_AUTOMATIC_EVENTS=false
# Event Einstellungen
EVENT_DURATION_MINUTES=30
EVENT_INTERVAL_HOURS=6
EVENT_INTERVAL_HOURS=1
# Grid-Funktionalität wurde entfernt
# Export Einstellungen
AUTO_EXPORT_INTERVAL_SECONDS=60
EXPORT_PATH=./exports/
# Keycloak Einstellungen
ENABLE_KEYCLOAK=false
KEYCLOAK_REALM=rplace
KEYCLOAK_AUTH_URL=http://localhost:8080/auth
KEYCLOAK_CLIENT_ID=rplace-client

861
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -51,9 +51,10 @@
"drizzle-zod": "^0.7.0",
"embla-carousel-react": "^8.6.0",
"express": "^4.21.2",
"express-session": "^1.18.1",
"express-session": "^1.18.2",
"framer-motion": "^11.13.1",
"input-otp": "^1.4.2",
"keycloak-connect": "^26.1.1",
"lucide-react": "^0.453.0",
"memorystore": "^1.6.7",
"nanoid": "^5.1.5",

View File

@@ -11,6 +11,11 @@ interface Config {
autoExportIntervalSeconds: number;
exportPath: string;
enableKeycloak: boolean;
keycloakRealm: string;
keycloakAuthUrl: string;
keycloakClientId: string;
}
function parseConfigFile(): Config {
@@ -54,6 +59,18 @@ function parseConfigFile(): Config {
case "EXPORT_PATH":
config.exportPath = trimmedValue;
break;
case "ENABLE_KEYCLOAK":
config.enableKeycloak = trimmedValue.toLowerCase() === "true";
break;
case "KEYCLOAK_REALM":
config.keycloakRealm = trimmedValue;
break;
case "KEYCLOAK_AUTH_URL":
config.keycloakAuthUrl = trimmedValue;
break;
case "KEYCLOAK_CLIENT_ID":
config.keycloakClientId = trimmedValue;
break;
}
});
@@ -68,6 +85,11 @@ function parseConfigFile(): Config {
autoExportIntervalSeconds: config.autoExportIntervalSeconds || 60,
exportPath: config.exportPath || "./exports/",
enableKeycloak: config.enableKeycloak || false,
keycloakRealm: config.keycloakRealm || "rplace",
keycloakAuthUrl: config.keycloakAuthUrl || "http://localhost:8080/auth",
keycloakClientId: config.keycloakClientId || "rplace-client",
};
} catch (error) {
console.error("Error reading config file, using defaults:", error);
@@ -81,6 +103,11 @@ function parseConfigFile(): Config {
autoExportIntervalSeconds: 60,
exportPath: "./exports/",
enableKeycloak: false,
keycloakRealm: "rplace",
keycloakAuthUrl: "http://localhost:8080/auth",
keycloakClientId: "rplace-client",
};
}
}

View File

@@ -1,11 +1,27 @@
import express, { type Request, Response, NextFunction } from "express";
import { registerRoutes } from "./routes";
import { setupVite, serveStatic, log } from "./vite";
import { setupKeycloak } from "./keycloak";
import { config } from "./config";
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// Keycloak Setup
let keycloak: any = null;
if (config.enableKeycloak) {
// Set environment variables for Keycloak
process.env.KEYCLOAK_REALM = config.keycloakRealm;
process.env.KEYCLOAK_AUTH_URL = config.keycloakAuthUrl;
process.env.KEYCLOAK_CLIENT_ID = config.keycloakClientId;
keycloak = setupKeycloak(app);
log("Keycloak authentication enabled");
} else {
log("Keycloak authentication disabled");
}
app.use((req, res, next) => {
const start = Date.now();
const path = req.path;
@@ -60,7 +76,7 @@ app.use((req, res, next) => {
// Other ports are firewalled. Default to 5000 if not specified.
// this serves both the API and the client.
// It is the only port that is not firewalled.
const port = parseInt(process.env.PORT || '5000', 10);
const port = parseInt(process.env.PORT || '5001', 10);
server.listen({
port,
host: "0.0.0.0",

56
server/keycloak.ts Normal file
View File

@@ -0,0 +1,56 @@
import Keycloak from 'keycloak-connect';
import session from 'express-session';
import { type Express } from 'express';
interface KeycloakConfig {
realm: string;
'auth-server-url': string;
'ssl-required': string;
resource: string;
'public-client': boolean;
'confidential-port': number;
}
// Keycloak Konfiguration aus Umgebungsvariablen oder Standard
const keycloakConfig: KeycloakConfig = {
realm: process.env.KEYCLOAK_REALM || 'rplace',
'auth-server-url': process.env.KEYCLOAK_AUTH_URL || 'http://localhost:8080/auth',
'ssl-required': 'external',
resource: process.env.KEYCLOAK_CLIENT_ID || 'rplace-client',
'public-client': true,
'confidential-port': 0,
};
// Session Store für Keycloak
const memoryStore = session.MemoryStore ? new session.MemoryStore() : undefined;
export function setupKeycloak(app: Express) {
// Session Middleware
const sessionConfig = {
secret: process.env.SESSION_SECRET || 'rplace-secret-key',
resave: false,
saveUninitialized: true,
store: memoryStore,
cookie: {
secure: process.env.NODE_ENV === 'production',
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000, // 24 Stunden
},
};
app.use(session(sessionConfig));
// Keycloak initialisieren
const keycloak = new Keycloak({ store: memoryStore }, keycloakConfig);
// Keycloak Middleware
app.use(keycloak.middleware({
logout: '/logout',
admin: '/',
}));
return keycloak;
}
export { keycloakConfig };

View File

@@ -1,9 +1,42 @@
import type { Express } from "express";
import type { Express, Request, Response, NextFunction } from "express";
import { createServer, type Server } from "http";
import { WebSocketServer, WebSocket } from "ws";
import { storage } from "./storage";
import { insertPixelSchema, insertUserCooldownSchema, type WSMessage } from "@shared/schema";
import { CanvasExporter } from "./export";
import { config } from "./config";
// Authentication middleware
function requireAuth(req: Request, res: Response, next: NextFunction) {
if (!config.enableKeycloak) {
return next();
}
// Check if user is authenticated via Keycloak
if (req.kauth && req.kauth.grant) {
return next();
}
return res.status(401).json({ message: "Authentication required" });
}
// Get user info from Keycloak token
function getUserFromToken(req: Request): { userId: string; username: string } {
if (!config.enableKeycloak || !req.kauth?.grant?.access_token) {
return {
userId: "User",
username: "Anonymous"
};
}
const token = req.kauth.grant.access_token;
const content = token.content;
return {
userId: content.sub || content.preferred_username || "User",
username: content.preferred_username || content.name || "User"
};
}
export async function registerRoutes(app: Express): Promise<Server> {
const httpServer = createServer(app);
@@ -15,6 +48,38 @@ export async function registerRoutes(app: Express): Promise<Server> {
const exporter = new CanvasExporter(storage);
exporter.startAutoExport();
// Authentication Routes
app.get("/api/auth/status", (req, res) => {
if (!config.enableKeycloak) {
return res.json({ authenticated: false, keycloakEnabled: false });
}
const isAuthenticated = req.kauth && req.kauth.grant;
const user = isAuthenticated ? getUserFromToken(req) : null;
res.json({
authenticated: isAuthenticated,
keycloakEnabled: true,
user: user
});
});
// Login redirect
app.get("/login", (req, res) => {
if (config.enableKeycloak && req.kauth) {
return req.kauth.login(req, res);
}
res.redirect("/");
});
// Logout
app.get("/logout", (req, res) => {
if (config.enableKeycloak && req.kauth) {
return req.kauth.logout(req, res);
}
res.redirect("/");
});
// API Routes
app.get("/api/pixels", async (req, res) => {
try {
@@ -37,9 +102,14 @@ export async function registerRoutes(app: Express): Promise<Server> {
// Config is now read-only from file
// Remove the POST endpoint for config updates
app.post("/api/pixels", async (req, res) => {
app.post("/api/pixels", requireAuth, async (req, res) => {
try {
const pixelData = insertPixelSchema.parse(req.body);
const userInfo = getUserFromToken(req);
const pixelData = insertPixelSchema.parse({
...req.body,
userId: userInfo.userId,
username: userInfo.username
});
const config = await storage.getCanvasConfig();
// Validate coordinates
@@ -50,7 +120,7 @@ export async function registerRoutes(app: Express): Promise<Server> {
// Check cooldown unless events are enabled
if (!config.enableAutomaticEvents) {
const cooldown = await storage.getUserCooldown(pixelData.userId);
const cooldown = await storage.getUserCooldown(userInfo.userId);
if (cooldown && cooldown.cooldownEnds > new Date()) {
return res.status(429).json({ message: "Cooldown active" });
}
@@ -58,7 +128,7 @@ export async function registerRoutes(app: Express): Promise<Server> {
// Set new cooldown
const cooldownEnd = new Date(Date.now() + (config.defaultCooldown * 1000));
await storage.setUserCooldown({
userId: pixelData.userId,
userId: userInfo.userId,
cooldownEnds: cooldownEnd,
});
}

21
server/types/keycloak.d.ts vendored Normal file
View File

@@ -0,0 +1,21 @@
import 'express';
declare module 'express' {
interface Request {
kauth?: {
grant?: {
access_token?: {
content?: {
sub?: string;
preferred_username?: string;
name?: string;
email?: string;
};
};
};
login?: (req: Request, res: Response) => void;
logout?: (req: Request, res: Response) => void;
};
}
}