Update router connection test to use REST API and default port 443

Adjusted the router connection test to target the MikroTik REST API on port 443 by default, and handle authentication and status codes accordingly.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 7a657272-55ba-4a79-9a2e-f1ed9bc7a528
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Event-Id: 1d0150b7-28d2-4cd9-bb13-5d7a63792aab
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/449cf7c4-c97a-45ae-8234-e5c5b8d6a84f/7a657272-55ba-4a79-9a2e-f1ed9bc7a528/31VdIyL
This commit is contained in:
marco370 2025-11-25 11:05:32 +00:00
parent 7f441ad7e3
commit dd8d38375d
3 changed files with 45 additions and 21 deletions

View File

@ -48,7 +48,7 @@ export default function Routers() {
defaultValues: { defaultValues: {
name: "", name: "",
ipAddress: "", ipAddress: "",
apiPort: 8728, apiPort: 443,
username: "", username: "",
password: "", password: "",
enabled: true, enabled: true,
@ -240,18 +240,18 @@ export default function Routers() {
name="apiPort" name="apiPort"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>Porta API</FormLabel> <FormLabel>Porta REST API</FormLabel>
<FormControl> <FormControl>
<Input <Input
type="number" type="number"
placeholder="8728" placeholder="443"
{...field} {...field}
onChange={(e) => field.onChange(parseInt(e.target.value))} onChange={(e) => field.onChange(parseInt(e.target.value))}
data-testid="input-port" data-testid="input-port"
/> />
</FormControl> </FormControl>
<FormDescription> <FormDescription>
Porta API MikroTik (default: 8728 per API, 8729 per API-SSL) Porta REST API MikroTik (443 HTTPS o 80 HTTP)
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@ -482,16 +482,19 @@ export default function Routers() {
name="apiPort" name="apiPort"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>Porta API</FormLabel> <FormLabel>Porta REST API</FormLabel>
<FormControl> <FormControl>
<Input <Input
type="number" type="number"
placeholder="8728" placeholder="443"
{...field} {...field}
onChange={(e) => field.onChange(parseInt(e.target.value))} onChange={(e) => field.onChange(parseInt(e.target.value))}
data-testid="input-edit-port" data-testid="input-edit-port"
/> />
</FormControl> </FormControl>
<FormDescription>
Porta REST API MikroTik (443 HTTPS o 80 HTTP)
</FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
)} )}

View File

@ -60,33 +60,54 @@ export async function registerRoutes(app: Express): Promise<Server> {
return res.status(404).json({ error: "Router not found" }); return res.status(404).json({ error: "Router not found" });
} }
// Test connessione TCP/HTTP al router // Test connessione REST API MikroTik
const testUrl = `http://${router.ipAddress}:${router.apiPort}`; // Usa HTTPS per porta 443, HTTP per altre
const protocol = router.apiPort === 443 ? 'https' : 'http';
const testUrl = `${protocol}://${router.ipAddress}:${router.apiPort}/rest/system/resource`;
try { try {
// Timeout di 5 secondi per il test // Timeout di 10 secondi per il test
const controller = new AbortController(); const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000); const timeoutId = setTimeout(() => controller.abort(), 10000);
const response = await fetch(testUrl, { const response = await fetch(testUrl, {
method: 'GET', method: 'GET',
signal: controller.signal, signal: controller.signal,
headers: { headers: {
'Authorization': 'Basic ' + Buffer.from(`${router.username}:${router.password}`).toString('base64') 'Authorization': 'Basic ' + Buffer.from(`${router.username}:${router.password}`).toString('base64')
} },
// Ignora errori certificato SSL self-signed (comune in MikroTik)
// @ts-ignore - Node.js fetch options
rejectUnauthorized: false
}); });
clearTimeout(timeoutId); clearTimeout(timeoutId);
// Aggiorna lastSync direttamente (non in InsertRouter schema) // Verifica status: 200 = OK, 401 = credenziali errate ma raggiungibile
await db.update(routers).set({ lastSync: new Date() }).where(eq(routers.id, router.id)); if (response.status === 200) {
// Successo! Aggiorna lastSync
await db.update(routers).set({ lastSync: new Date() }).where(eq(routers.id, router.id));
res.json({ res.json({
success: true, success: true,
message: `Router ${router.name} raggiungibile (HTTP ${response.status})`, message: `Router ${router.name} connesso con successo! REST API funzionante.`,
status: response.status, status: response.status
statusText: response.statusText });
}); } else if (response.status === 401 || response.status === 403) {
// Router raggiungibile ma credenziali errate
res.status(401).json({
error: "Autenticazione fallita",
message: `Router raggiungibile ma le credenziali sono errate. Verifica username e password.`,
status: response.status
});
} else {
// Altro errore HTTP
res.status(response.status).json({
error: `Errore HTTP ${response.status}`,
message: `Il router risponde ma con stato ${response.status}: ${response.statusText}`,
status: response.status
});
}
} catch (fetchError: any) { } catch (fetchError: any) {
console.error('[Router TEST] Connection failed:', fetchError.message); console.error('[Router TEST] Connection failed:', fetchError.message);

View File

@ -8,7 +8,7 @@ export const routers = pgTable("routers", {
id: varchar("id").primaryKey().default(sql`gen_random_uuid()`), id: varchar("id").primaryKey().default(sql`gen_random_uuid()`),
name: text("name").notNull(), name: text("name").notNull(),
ipAddress: text("ip_address").notNull().unique(), ipAddress: text("ip_address").notNull().unique(),
apiPort: integer("api_port").notNull().default(8728), apiPort: integer("api_port").notNull().default(443),
username: text("username").notNull(), username: text("username").notNull(),
password: text("password").notNull(), password: text("password").notNull(),
enabled: boolean("enabled").notNull().default(true), enabled: boolean("enabled").notNull().default(true),