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,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 }
);
}
}