first commit

This commit is contained in:
2025-11-24 16:30:37 +00:00
commit 843e93a274
114 changed files with 25585 additions and 0 deletions

View File

@@ -0,0 +1,146 @@
// API Route für einzelne ACL Regel
import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/lib/auth';
import { mqttAclRuleDb } from '@/lib/mqtt-db';
import { deviceDb } from '@/lib/db';
/**
* PATCH /api/mqtt/acl/[id]
* Aktualisiere eine ACL Regel
*/
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await auth();
if (!session?.user || (session.user as any).role !== 'ADMIN') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { id: idParam } = await params;
const id = parseInt(idParam);
if (isNaN(id)) {
return NextResponse.json(
{ error: 'Invalid ACL rule ID' },
{ status: 400 }
);
}
const body = await request.json();
const { topic_pattern, permission } = body;
// Validation
if (permission && !['read', 'write', 'readwrite'].includes(permission)) {
return NextResponse.json(
{ error: 'Permission must be read, write, or readwrite' },
{ status: 400 }
);
}
// Get current ACL rule to check device ownership
const userId = (session.user as any).id;
const currentRule = mqttAclRuleDb.findByDeviceId(''); // We need to get by ID first
const aclRules = mqttAclRuleDb.findAll();
const rule = aclRules.find(r => r.id === id);
if (!rule) {
return NextResponse.json(
{ error: 'ACL rule not found' },
{ status: 404 }
);
}
// Check if device belongs to user
const device = deviceDb.findById(rule.device_id);
if (!device || device.ownerId !== userId) {
return NextResponse.json(
{ error: 'Access denied' },
{ status: 403 }
);
}
const updated = mqttAclRuleDb.update(id, {
topic_pattern,
permission
});
if (!updated) {
return NextResponse.json(
{ error: 'Failed to update ACL rule' },
{ status: 500 }
);
}
return NextResponse.json(updated);
} catch (error) {
console.error('Failed to update ACL rule:', error);
return NextResponse.json(
{ error: 'Failed to update ACL rule' },
{ status: 500 }
);
}
}
/**
* DELETE /api/mqtt/acl/[id]
* Lösche eine ACL Regel
*/
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await auth();
if (!session?.user || (session.user as any).role !== 'ADMIN') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { id: idParam } = await params;
const id = parseInt(idParam);
if (isNaN(id)) {
return NextResponse.json(
{ error: 'Invalid ACL rule ID' },
{ status: 400 }
);
}
// Get current ACL rule to check device ownership
const userId = (session.user as any).id;
const aclRules = mqttAclRuleDb.findAll();
const rule = aclRules.find(r => r.id === id);
if (!rule) {
return NextResponse.json(
{ error: 'ACL rule not found' },
{ status: 404 }
);
}
// Check if device belongs to user
const device = deviceDb.findById(rule.device_id);
if (!device || device.ownerId !== userId) {
return NextResponse.json(
{ error: 'Access denied' },
{ status: 403 }
);
}
const deleted = mqttAclRuleDb.delete(id);
if (!deleted) {
return NextResponse.json(
{ error: 'Failed to delete ACL rule' },
{ status: 500 }
);
}
return NextResponse.json({ success: true });
} catch (error) {
console.error('Failed to delete ACL rule:', error);
return NextResponse.json(
{ error: 'Failed to delete ACL rule' },
{ status: 500 }
);
}
}

104
app/api/mqtt/acl/route.ts Normal file
View File

@@ -0,0 +1,104 @@
// API Route für MQTT ACL Management
import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/lib/auth';
import { mqttAclRuleDb } from '@/lib/mqtt-db';
import { deviceDb } from '@/lib/db';
/**
* GET /api/mqtt/acl?device_id=xxx
* Hole ACL Regeln für ein Device
*/
export async function GET(request: NextRequest) {
try {
const session = await auth();
if (!session?.user || (session.user as any).role !== 'ADMIN') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const searchParams = request.nextUrl.searchParams;
const device_id = searchParams.get('device_id');
if (!device_id) {
return NextResponse.json(
{ error: 'device_id query parameter is required' },
{ status: 400 }
);
}
// Check if device belongs to user
const userId = (session.user as any).id;
const device = deviceDb.findById(device_id);
if (!device || device.ownerId !== userId) {
return NextResponse.json(
{ error: 'Device not found or access denied' },
{ status: 404 }
);
}
const rules = mqttAclRuleDb.findByDeviceId(device_id);
return NextResponse.json(rules);
} catch (error) {
console.error('Failed to fetch ACL rules:', error);
return NextResponse.json(
{ error: 'Failed to fetch ACL rules' },
{ status: 500 }
);
}
}
/**
* POST /api/mqtt/acl
* Erstelle neue ACL Regel
*/
export async function POST(request: NextRequest) {
try {
const session = await auth();
if (!session?.user || (session.user as any).role !== 'ADMIN') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const body = await request.json();
const { device_id, topic_pattern, permission } = body;
// Validierung
if (!device_id || !topic_pattern || !permission) {
return NextResponse.json(
{ error: 'device_id, topic_pattern, and permission are required' },
{ status: 400 }
);
}
if (!['read', 'write', 'readwrite'].includes(permission)) {
return NextResponse.json(
{ error: 'permission must be one of: read, write, readwrite' },
{ status: 400 }
);
}
// Check if device belongs to user
const userId = (session.user as any).id;
const device = deviceDb.findById(device_id);
if (!device || device.ownerId !== userId) {
return NextResponse.json(
{ error: 'Device not found or access denied' },
{ status: 404 }
);
}
const rule = mqttAclRuleDb.create({
device_id,
topic_pattern,
permission
});
return NextResponse.json(rule, { status: 201 });
} catch (error) {
console.error('Failed to create ACL rule:', error);
return NextResponse.json(
{ error: 'Failed to create ACL rule' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,143 @@
// API Route für einzelne MQTT Credentials
import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/lib/auth';
import { mqttCredentialDb, mqttAclRuleDb } from '@/lib/mqtt-db';
import { hashPassword } from '@/lib/mosquitto-sync';
import { randomBytes } from 'crypto';
/**
* GET /api/mqtt/credentials/[device_id]
* Hole MQTT Credentials für ein Device
*/
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ device_id: string }> }
) {
const { device_id } = await params;
try {
const session = await auth();
if (!session?.user || (session.user as any).role !== 'ADMIN') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const credential = mqttCredentialDb.findByDeviceId(device_id);
if (!credential) {
return NextResponse.json(
{ error: 'Credentials not found' },
{ status: 404 }
);
}
return NextResponse.json(credential);
} catch (error) {
console.error('Failed to fetch MQTT credentials:', error);
return NextResponse.json(
{ error: 'Failed to fetch credentials' },
{ status: 500 }
);
}
}
/**
* PATCH /api/mqtt/credentials/[device_id]
* Aktualisiere MQTT Credentials
*/
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ device_id: string }> }
) {
const { device_id } = await params;
try {
const session = await auth();
if (!session?.user || (session.user as any).role !== 'ADMIN') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const body = await request.json();
const { regenerate_password, enabled } = body;
const credential = mqttCredentialDb.findByDeviceId(device_id);
if (!credential) {
return NextResponse.json(
{ error: 'Credentials not found' },
{ status: 404 }
);
}
let newPassword: string | undefined;
let updateData: any = {};
// Regeneriere Passwort wenn angefordert
if (regenerate_password) {
newPassword = randomBytes(16).toString('base64');
const password_hash = await hashPassword(newPassword);
updateData.mqtt_password_hash = password_hash;
}
// Update enabled Status
if (enabled !== undefined) {
updateData.enabled = enabled ? 1 : 0;
}
// Update Credentials
const updated = mqttCredentialDb.update(device_id, updateData);
if (!updated) {
return NextResponse.json(
{ error: 'Failed to update credentials' },
{ status: 500 }
);
}
return NextResponse.json({
...updated,
// Sende neues Passwort nur wenn regeneriert
...(newPassword && { mqtt_password: newPassword })
});
} catch (error) {
console.error('Failed to update MQTT credentials:', error);
return NextResponse.json(
{ error: 'Failed to update credentials' },
{ status: 500 }
);
}
}
/**
* DELETE /api/mqtt/credentials/[device_id]
* Lösche MQTT Credentials für ein Device
*/
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ device_id: string }> }
) {
const { device_id } = await params;
try {
const session = await auth();
if (!session?.user || (session.user as any).role !== 'ADMIN') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Lösche zuerst alle ACL Regeln
mqttAclRuleDb.deleteByDeviceId(device_id);
// Dann lösche Credentials
const deleted = mqttCredentialDb.delete(device_id);
if (!deleted) {
return NextResponse.json(
{ error: 'Credentials not found' },
{ status: 404 }
);
}
return NextResponse.json({ success: true });
} catch (error) {
console.error('Failed to delete MQTT credentials:', error);
return NextResponse.json(
{ error: 'Failed to delete credentials' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,126 @@
// API Route für MQTT Credentials Management
import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/lib/auth';
import { mqttCredentialDb, mqttAclRuleDb } from '@/lib/mqtt-db';
import { deviceDb } from '@/lib/db';
import { hashPassword } from '@/lib/mosquitto-sync';
import { randomBytes } from 'crypto';
/**
* GET /api/mqtt/credentials
* Liste alle MQTT Credentials
*/
export async function GET() {
try {
const session = await auth();
if (!session?.user || (session.user as any).role !== 'ADMIN') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const userId = (session.user as any).id;
const credentials = mqttCredentialDb.findAll();
// Filter credentials to only show user's devices
const credentialsWithDevices = credentials
.map(cred => {
const device = deviceDb.findById(cred.device_id);
return {
...cred,
device_name: device?.name || 'Unknown Device',
device_owner: device?.ownerId
};
})
.filter(cred => cred.device_owner === userId);
return NextResponse.json(credentialsWithDevices);
} catch (error) {
console.error('Failed to fetch MQTT credentials:', error);
return NextResponse.json(
{ error: 'Failed to fetch credentials' },
{ status: 500 }
);
}
}
/**
* POST /api/mqtt/credentials
* Erstelle neue MQTT Credentials für ein Device
*/
export async function POST(request: NextRequest) {
try {
const session = await auth();
if (!session?.user || (session.user as any).role !== 'ADMIN') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const body = await request.json();
const { device_id, mqtt_username, mqtt_password, auto_generate } = body;
// Validierung
if (!device_id) {
return NextResponse.json(
{ error: 'device_id is required' },
{ status: 400 }
);
}
// Prüfe ob Device existiert
const device = deviceDb.findById(device_id);
if (!device) {
return NextResponse.json(
{ error: 'Device not found' },
{ status: 404 }
);
}
// Prüfe ob bereits Credentials existieren
const existing = mqttCredentialDb.findByDeviceId(device_id);
if (existing) {
return NextResponse.json(
{ error: 'MQTT credentials already exist for this device' },
{ status: 409 }
);
}
// Generiere oder verwende übergebene Credentials
let username = mqtt_username;
let password = mqtt_password;
if (auto_generate || !username) {
// Generiere Username: device_[device-id]_[random]
username = `device_${device_id}_${randomBytes(4).toString('hex')}`;
}
if (auto_generate || !password) {
// Generiere sicheres Passwort
password = randomBytes(16).toString('base64');
}
// Hash Passwort
const password_hash = await hashPassword(password);
// Erstelle Credentials
const credential = mqttCredentialDb.create({
device_id,
mqtt_username: username,
mqtt_password_hash: password_hash,
enabled: 1
});
// Erstelle Default ACL Regel
mqttAclRuleDb.createDefaultRule(device_id);
return NextResponse.json({
...credential,
// Sende Plaintext-Passwort nur bei Erstellung zurück
mqtt_password: password,
device_name: device.name
}, { status: 201 });
} catch (error) {
console.error('Failed to create MQTT credentials:', error);
return NextResponse.json(
{ error: 'Failed to create credentials' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,90 @@
import { NextResponse } from 'next/server';
import { auth } from '@/lib/auth';
import { emailService } from '@/lib/email-service';
import { deviceDb, userDb } from '@/lib/db';
// POST /api/mqtt/send-credentials - Send MQTT credentials via email
export async function POST(request: Request) {
try {
const session = await auth();
if (!session?.user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Only admins can send credentials
if ((session.user as any).role !== 'ADMIN') {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const body = await request.json();
const { deviceId, mqttUsername, mqttPassword } = body;
if (!deviceId || !mqttUsername || !mqttPassword) {
return NextResponse.json(
{ error: 'Missing required fields: deviceId, mqttUsername, mqttPassword' },
{ status: 400 }
);
}
// Get device info
const device = deviceDb.findById(deviceId);
if (!device) {
return NextResponse.json({ error: 'Device not found' }, { status: 404 });
}
// Get device owner
if (!device.ownerId) {
return NextResponse.json(
{ error: 'Device has no owner assigned' },
{ status: 400 }
);
}
const owner = userDb.findById(device.ownerId);
if (!owner) {
return NextResponse.json(
{ error: 'Device owner not found' },
{ status: 404 }
);
}
if (!owner.email) {
return NextResponse.json(
{ error: 'Device owner has no email address' },
{ status: 400 }
);
}
// Parse broker URL from environment or use default
const brokerUrl = process.env.MQTT_BROKER_URL || 'mqtt://localhost:1883';
const brokerHost = brokerUrl.replace(/^mqtt:\/\//, '').replace(/:\d+$/, '');
const brokerPortMatch = brokerUrl.match(/:(\d+)$/);
const brokerPort = brokerPortMatch ? brokerPortMatch[1] : '1883';
// Send email
await emailService.sendMqttCredentialsEmail({
email: owner.email,
deviceName: device.name,
deviceId: device.id,
mqttUsername,
mqttPassword,
brokerUrl,
brokerHost,
brokerPort,
});
console.log(`[MQTT] Credentials sent via email to ${owner.email} for device ${device.name}`);
return NextResponse.json({
success: true,
message: `Credentials sent to ${owner.email}`,
});
} catch (error) {
console.error('Error sending MQTT credentials email:', error);
return NextResponse.json(
{ error: error instanceof Error ? error.message : 'Failed to send email' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,50 @@
// API Route für Mosquitto Configuration Sync
import { NextResponse } from 'next/server';
import { auth } from '@/lib/auth';
import { syncMosquittoConfig, getMosquittoSyncStatus } from '@/lib/mosquitto-sync';
/**
* GET /api/mqtt/sync
* Hole den aktuellen Sync Status
*/
export async function GET() {
try {
const session = await auth();
if (!session?.user || (session.user as any).role !== 'ADMIN') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const status = getMosquittoSyncStatus();
return NextResponse.json(status || { pending_changes: 0, last_sync_status: 'unknown' });
} catch (error) {
console.error('Failed to fetch sync status:', error);
return NextResponse.json(
{ error: 'Failed to fetch sync status' },
{ status: 500 }
);
}
}
/**
* POST /api/mqtt/sync
* Trigger Mosquitto Configuration Sync
*/
export async function POST() {
try {
const session = await auth();
if (!session?.user || (session.user as any).role !== 'ADMIN') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const result = await syncMosquittoConfig();
return NextResponse.json(result, {
status: result.success ? 200 : 500
});
} catch (error) {
console.error('Failed to sync Mosquitto config:', error);
return NextResponse.json(
{ error: 'Failed to sync Mosquitto configuration' },
{ status: 500 }
);
}
}