initial commit

master
bjarne 3 months ago
commit 2280abae90

@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}

36
.gitignore vendored

@ -0,0 +1,36 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

5
.idea/.gitignore vendored

@ -0,0 +1,5 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptLibraryMappings">
<includedPredefinedLibrary name="Node.js Core" />
</component>
</project>

@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.js`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.

@ -0,0 +1,29 @@
import { NextResponse } from 'next/server';
import fs from 'fs';
import { exec } from 'child_process';
const dhcpConfigPath = '/etc/dhcp/dhcpd.conf'; // Make sure this path is correct for your system
export async function GET() {
try {
const config = fs.readFileSync(dhcpConfigPath, 'utf8');
return NextResponse.json({ config });
} catch (error) {
return NextResponse.json({ error: 'Failed to read DHCP configuration' }, { status: 500 });
}
}
export async function POST(request) {
try {
const { config } = await request.json();
fs.writeFileSync(dhcpConfigPath, config, 'utf8');
exec('sudo systemctl restart isc-dhcp-server', (error, stdout, stderr) => {
if (error) {
throw new Error(`Failed to restart DHCP server: ${stderr}`);
}
});
return NextResponse.json({ success: true });
} catch (error) {
return NextResponse.json({ error: 'Failed to write DHCP configuration or restart server' }, { status: 500 });
}
}

@ -0,0 +1,25 @@
import { NextResponse } from 'next/server';
import { exec } from 'child_process';
const dhcpConfigPath = '/etc/dhcp/dhcpd.conf';
export async function POST(request) {
const { username, password } = await request.json();
try {
const command = `
echo '${password}' | sudo -S visudo -c &&
echo '${username} ALL=(ALL) NOPASSWD: /bin/systemctl restart isc-dhcp-server' | sudo tee -a /etc/sudoers &&
echo '${password}' | sudo -S chown ${username}:${username} ${dhcpConfigPath}
`;
exec(command, (error, stdout, stderr) => {
if (error) {
throw new Error(stderr);
}
});
return NextResponse.json({ success: true });
} catch (error) {
return NextResponse.json({ error: 'Failed to grant sudo rights or set file permissions' }, { status: 500 });
}
}

@ -0,0 +1,17 @@
import Link from 'next/link';
const Card = ({ title, text, url }) => {
return (
<div className="col-md-6 mb-4">
<div className="card">
<div className="card-body text-center">
<h5 className="card-title">{title}</h5>
<p className="card-text">{text}</p>
<Link href={url} className="btn btn-primary">Go to {title}</Link>
</div>
</div>
</div>
);
};
export default Card;

@ -0,0 +1,29 @@
import Link from 'next/link';
const Navbar = () => {
return (
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<div className="container">
<Link href="/" className="navbar-brand">DHCP Server Control</Link>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarNav">
<ul className="navbar-nav ml-auto">
<li className="nav-item">
<Link href="/" className="nav-link">Home</Link>
</li>
<li className="nav-item">
<Link href="/leases" className="nav-link">Leases</Link>
</li>
<li className="nav-item">
<Link href="/configure" className="nav-link">Configure Options</Link>
</li>
</ul>
</div>
</div>
</nav>
);
};
export default Navbar;

@ -0,0 +1,30 @@
'use client';
import { useNotification } from '../context/NotificationContext';
const Notification = () => {
const { notification, clearNotification } = useNotification();
if (!notification) return null;
const notificationTypeClass = {
success: 'alert-success',
error: 'alert-danger',
warning: 'alert-warning',
info: 'alert-info',
}[notification.type] || 'alert-info';
return (
<div className={`alert ${notificationTypeClass} alert-dismissible fade show`} role="alert">
{notification.message}
<button
type="button"
className="btn-close"
aria-label="Close"
onClick={clearNotification}
></button>
</div>
);
};
export default Notification;

@ -0,0 +1,153 @@
'use client';
import { useState, useEffect } from 'react';
import { useNotification } from '@/app/context/NotificationContext';
export default function ConfigurePage() {
const [config, setConfig] = useState('');
const { showNotification } = useNotification();
const [showDialog, setShowDialog] = useState(false);
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
// Function to fetch the DHCP configuration
const fetchConfig = async () => {
try {
const response = await fetch('/api/dhcp/config');
const data = await response.json();
if (response.ok) {
setConfig(data.config);
showNotification('DHCP configuration loaded successfully.', 'success');
} else {
showNotification(data.error, 'error');
}
} catch (error) {
showNotification('Error loading DHCP configuration', 'error');
}
};
useEffect(() => {
// Initial load of the DHCP configuration
fetchConfig();
}, []);
const handleConfigChange = (event) => {
setConfig(event.target.value);
};
const handleSave = async () => {
try {
const response = await fetch('/api/dhcp/config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ config }),
});
const data = await response.json();
if (response.ok) {
showNotification('DHCP configuration updated and server restarted successfully.', 'success');
} else {
showNotification(data.error, 'error');
}
} catch (error) {
showNotification('Error updating configuration or restarting server', 'error');
}
};
// automatically add webserver to sudo
const openDialog = () => {
setShowDialog(true);
};
const closeDialog = () => {
setShowDialog(false);
};
const handleGrantSudoRights = async () => {
try {
const response = await fetch('/api/grant-sudo', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
const data = await response.json();
if (response.ok) {
showNotification('Sudo rights granted successfully.', 'success');
} else {
showNotification(data.error, 'error');
}
closeDialog();
} catch (error) {
showNotification('Error granting sudo rights', 'error');
}
};
return (
<div className="container mt-5">
<h1 className="mb-4">Configure DHCP Options</h1>
<div className="form-group">
<label htmlFor="dhcpConfig">DHCP Configuration</label>
<textarea
id="dhcpConfig"
className="form-control"
rows="20"
value={config}
onChange={handleConfigChange}
/>
</div>
<button className="btn btn-secondary mt-3 mr-2" onClick={fetchConfig}>
Refresh
</button>
<button className="btn btn-primary mt-3" onClick={handleSave}>
Save and Restart DHCP Server
</button>
<button className="btn btn-warning mt-3 ml-2" onClick={openDialog}>
Grant Sudo Rights
</button>
{showDialog && (
<div className="modal show" style={{display: 'block'}}>
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title">Grant Sudo Rights</h5>
<button type="button" className="btn-close" aria-label="Close"
onClick={closeDialog}></button>
</div>
<div className="modal-body">
<div className="form-group">
<label htmlFor="username">Username</label>
<input
type="text"
className="form-control"
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
className="form-control"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" onClick={closeDialog}>
Cancel
</button>
<button type="button" className="btn btn-primary" onClick={handleGrantSudoRights}>
Grant Sudo Rights
</button>
</div>
</div>
</div>
</div>
)}
</div>
);
}

@ -0,0 +1,25 @@
'use client'
import { createContext, useContext, useState } from 'react';
const NotificationContext = createContext();
export const NotificationProvider = ({ children }) => {
const [notification, setNotification] = useState(null);
const showNotification = (message, type = 'info') => {
setNotification({ message, type });
};
const clearNotification = () => {
setNotification(null);
};
return (
<NotificationContext.Provider value={{ notification, showNotification, clearNotification }}>
{children}
</NotificationContext.Provider>
);
};
export const useNotification = () => useContext(NotificationContext);

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

@ -0,0 +1,28 @@
import { Inter } from "next/font/google";
import 'bootstrap/dist/css/bootstrap.min.css';
import "./globals.css";
import Navbar from './components/Navbar';
import Notification from './components/Notification';
import { NotificationProvider } from './context/NotificationContext';
const inter = Inter({ subsets: ["latin"] });
export const metadata = {
title: "AirIT ZTP Server",
description: "Update Firmware and config",
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body className={inter.className}>
<NotificationProvider>
<Navbar />
<Notification />
<main>{children}</main>
</NotificationProvider>
</body>
</html>
);
}

@ -0,0 +1,40 @@
import { parseLeases } from '@/app/lib/parseLeases';
export const metadata = {
title: 'DHCP Leases',
description: 'View current DHCP leases',
};
export default function LeasesPage() {
const leases = parseLeases();
return (
<div className="container mt-5">
<h1 className="mb-4">Current DHCP Leases</h1>
<table className="table table-striped">
<thead>
<tr>
<th scope="col">IP Address</th>
<th scope="col">Start Time</th>
<th scope="col">End Time</th>
<th scope="col">MAC Address</th>
<th scope="col">Hostname</th>
<th scope="col">State</th>
</tr>
</thead>
<tbody>
{leases.map((lease, index) => (
<tr key={index}>
<td>{lease.ip}</td>
<td>{lease.start}</td>
<td>{lease.end}</td>
<td>{lease.mac}</td>
<td>{lease.hostname}</td>
<td>{lease.state}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}

@ -0,0 +1,31 @@
'use client'
import fs from 'fs';
import { exec } from 'child_process';
const dhcpConfigPath = '/etc/dhcp/dhcpd.conf'; // Path to the DHCP server configuration file
export function readDhcpConfig() {
try {
const config = fs.readFileSync(dhcpConfigPath, 'utf8');
return config;
} catch (error) {
throw new Error('Error reading DHCP configuration file: ' + error.message);
}
}
export function writeDhcpConfig(newConfig) {
try {
fs.writeFileSync(dhcpConfigPath, newConfig, 'utf8');
} catch (error) {
throw new Error('Error writing to DHCP configuration file: ' + error.message);
}
}
export function restartDhcpServer() {
exec('sudo systemctl restart isc-dhcp-server', (error, stdout, stderr) => {
if (error) {
throw new Error(`Error restarting DHCP server: ${stderr}`);
}
});
}

@ -0,0 +1,36 @@
import fs from 'fs';
import path from 'path';
export function parseLeases() {
const leaseFilePath = '/var/lib/dhcp/dhcpd.leases';
const fileContent = fs.readFileSync(leaseFilePath, 'utf8');
const leases = [];
const leaseBlocks = fileContent.split('lease ');
leaseBlocks.shift(); // Remove the first empty block
leaseBlocks.forEach(block => {
const lease = {};
const lines = block.split('\n');
lease.ip = lines[0].trim();
lines.forEach(line => {
line = line.trim();
if (line.startsWith('starts')) {
lease.start = line.split(' ')[2] + ' ' + line.split(' ')[3];
} else if (line.startsWith('ends')) {
lease.end = line.split(' ')[2] + ' ' + line.split(' ')[3];
} else if (line.startsWith('binding state')) {
lease.state = line.split(' ')[2];
} else if (line.startsWith('hardware ethernet')) {
lease.mac = line.split(' ')[2].replace(';', '');
} else if (line.startsWith('client-hostname')) {
lease.hostname = line.split(' ')[1].replace(';', '').replace(/"/g, '');
}
});
leases.push(lease);
});
return leases;
}

@ -0,0 +1,14 @@
import Card from '@/app/components/Card';
export default function Home() {
return (
<div className="d-flex justify-content-center align-items-center" style={{ minHeight: '80vh' }}>
<div className="container">
<div className="row">
<Card title="Leases" text="View current DHCP leases." url="/leases" />
<Card title="Configure Options" text="Configure new DHCP options." url="/configure" />
</div>
</div>
</div>
);
}

@ -0,0 +1,230 @@
.main {
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
padding: 6rem;
min-height: 100vh;
}
.description {
display: inherit;
justify-content: inherit;
align-items: inherit;
font-size: 0.85rem;
max-width: var(--max-width);
width: 100%;
z-index: 2;
font-family: var(--font-mono);
}
.description a {
display: flex;
justify-content: center;
align-items: center;
gap: 0.5rem;
}
.description p {
position: relative;
margin: 0;
padding: 1rem;
background-color: rgba(var(--callout-rgb), 0.5);
border: 1px solid rgba(var(--callout-border-rgb), 0.3);
border-radius: var(--border-radius);
}
.code {
font-weight: 700;
font-family: var(--font-mono);
}
.grid {
display: grid;
grid-template-columns: repeat(4, minmax(25%, auto));
max-width: 100%;
width: var(--max-width);
}
.card {
padding: 1rem 1.2rem;
border-radius: var(--border-radius);
background: rgba(var(--card-rgb), 0);
border: 1px solid rgba(var(--card-border-rgb), 0);
transition: background 200ms, border 200ms;
}
.card span {
display: inline-block;
transition: transform 200ms;
}
.card h2 {
font-weight: 600;
margin-bottom: 0.7rem;
}
.card p {
margin: 0;
opacity: 0.6;
font-size: 0.9rem;
line-height: 1.5;
max-width: 30ch;
text-wrap: balance;
}
.center {
display: flex;
justify-content: center;
align-items: center;
position: relative;
padding: 4rem 0;
}
.center::before {
background: var(--secondary-glow);
border-radius: 50%;
width: 480px;
height: 360px;
margin-left: -400px;
}
.center::after {
background: var(--primary-glow);
width: 240px;
height: 180px;
z-index: -1;
}
.center::before,
.center::after {
content: "";
left: 50%;
position: absolute;
filter: blur(45px);
transform: translateZ(0);
}
.logo {
position: relative;
}
/* Enable hover only on non-touch devices */
@media (hover: hover) and (pointer: fine) {
.card:hover {
background: rgba(var(--card-rgb), 0.1);
border: 1px solid rgba(var(--card-border-rgb), 0.15);
}
.card:hover span {
transform: translateX(4px);
}
}
@media (prefers-reduced-motion) {
.card:hover span {
transform: none;
}
}
/* Mobile */
@media (max-width: 700px) {
.content {
padding: 4rem;
}
.grid {
grid-template-columns: 1fr;
margin-bottom: 120px;
max-width: 320px;
text-align: center;
}
.card {
padding: 1rem 2.5rem;
}
.card h2 {
margin-bottom: 0.5rem;
}
.center {
padding: 8rem 0 6rem;
}
.center::before {
transform: none;
height: 300px;
}
.description {
font-size: 0.8rem;
}
.description a {
padding: 1rem;
}
.description p,
.description div {
display: flex;
justify-content: center;
position: fixed;
width: 100%;
}
.description p {
align-items: center;
inset: 0 0 auto;
padding: 2rem 1rem 1.4rem;
border-radius: 0;
border: none;
border-bottom: 1px solid rgba(var(--callout-border-rgb), 0.25);
background: linear-gradient(
to bottom,
rgba(var(--background-start-rgb), 1),
rgba(var(--callout-rgb), 0.5)
);
background-clip: padding-box;
backdrop-filter: blur(24px);
}
.description div {
align-items: flex-end;
pointer-events: none;
inset: auto 0 0;
padding: 2rem;
height: 200px;
background: linear-gradient(
to bottom,
transparent 0%,
rgb(var(--background-end-rgb)) 40%
);
z-index: 1;
}
}
/* Tablet and Smaller Desktop */
@media (min-width: 701px) and (max-width: 1120px) {
.grid {
grid-template-columns: repeat(2, 50%);
}
}
@media (prefers-color-scheme: dark) {
.vercelLogo {
filter: invert(1);
}
.logo {
filter: invert(1) drop-shadow(0 0 0.3rem #ffffff70);
}
}
@keyframes rotate {
from {
transform: rotate(360deg);
}
to {
transform: rotate(0deg);
}
}

@ -0,0 +1,7 @@
{
"compilerOptions": {
"paths": {
"@/*": ["./*"]
}
}
}

@ -0,0 +1,4 @@
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default nextConfig;

4344
package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -0,0 +1,22 @@
{
"name": "ztp-next",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"bootstrap": "^5.3.3",
"fs": "^0.0.1-security",
"next": "14.2.7",
"react": "^18",
"react-dom": "^18"
},
"devDependencies": {
"eslint": "^8",
"eslint-config-next": "14.2.7"
}
}
Loading…
Cancel
Save

Powered by TurnKey Linux.