fixing login
Deploy / deploy (push) Successful in 38s

This commit is contained in:
2026-05-07 19:54:10 +02:00
parent 9638f782c9
commit 68ab026f97
6 changed files with 171 additions and 163 deletions
+84
View File
@@ -40,6 +40,12 @@ try {
case 'settings':
handleSettings($method, $db);
break;
case 'login':
handleLogin($method, $db);
break;
case 'logout':
handleLogout();
break;
case 'teams':
handleTeams($method, $id, $db);
break;
@@ -69,6 +75,10 @@ try {
function handleSession($method, $db) {
$loggedin = isset($_SESSION['neptune_loggedin']) && $_SESSION['neptune_loggedin'] === true;
if (!$loggedin && $method === 'GET') {
echo json_encode(['loggedin' => false]);
return;
}
if ($loggedin) {
$role = $_SESSION['neptune_role'] ?? 'user';
$stmt = $db->prepare("SELECT COUNT(*) as c FROM neptune_users WHERE role='admin'");
@@ -85,6 +95,80 @@ function handleSession($method, $db) {
}
}
function handleLogin($method, $db) {
if ($method !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'POST required']);
return;
}
$data = json_decode(file_get_contents('php://input'), true);
$auth_token = $data['auth_token'] ?? '';
if (!$auth_token) {
http_response_code(400);
echo json_encode(['error' => 'auth_token required']);
return;
}
$check_url = "https://auth.jakach.ch/api/auth/check_auth_key.php?auth_token=" . urlencode($auth_token);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $check_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http_code !== 200 || !$response) {
http_response_code(502);
echo json_encode(['error' => 'Failed to contact auth server']);
return;
}
$info = json_decode($response, true);
if (!isset($info['status']) || $info['status'] !== 'success') {
http_response_code(401);
echo json_encode(['error' => $info['msg'] ?? 'Auth failed']);
return;
}
$user_token = $info['user_token'];
$username = $info['username'];
$email = $info['email'] ?? '';
$stmt = $db->prepare("SELECT * FROM neptune_users WHERE user_token = ?");
$stmt->execute([$user_token]);
$user = $stmt->fetch();
if ($user) {
$_SESSION['neptune_loggedin'] = true;
$_SESSION['neptune_user_token'] = $user['user_token'];
$_SESSION['neptune_username'] = $user['username'];
$_SESSION['neptune_role'] = $user['role'];
} else {
$count = $db->query("SELECT COUNT(*) as c FROM neptune_users")->fetch()['c'];
$role = ($count == 0) ? 'admin' : 'user';
$stmt = $db->prepare("INSERT INTO neptune_users (user_token, username, email, role) VALUES (?, ?, ?, ?)");
$stmt->execute([$user_token, $username, $email, $role]);
$_SESSION['neptune_loggedin'] = true;
$_SESSION['neptune_user_token'] = $user_token;
$_SESSION['neptune_username'] = $username;
$_SESSION['neptune_role'] = $role;
}
echo json_encode([
'status' => 'success',
'username' => $_SESSION['neptune_username'],
'role' => $_SESSION['neptune_role']
]);
}
function handleLogout() {
$_SESSION = array();
session_destroy();
echo json_encode(['status' => 'success']);
}
function handleSettings($method, $db) {
$role = $_SESSION['neptune_role'] ?? 'user';
if ($method === 'GET') {
-114
View File
@@ -1,114 +0,0 @@
<?php
session_start();
if (isset($_SESSION['neptune_loggedin']) && $_SESSION['neptune_loggedin'] === true) {
header('Location: /');
exit;
}
$error = '';
$success = '';
// Detect the correct callback URL
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost:8080';
// If no port in host and not standard port, add it
if (strpos($host, ':') === false && !in_array($_SERVER['SERVER_PORT'] ?? 80, [80, 443])) {
$host .= ':' . $_SERVER['SERVER_PORT'];
}
$callbackUrl = "$scheme://$host/login.php";
if (isset($_GET['auth'])) {
$auth_token = $_GET['auth'];
$check_url = "https://auth.jakach.ch/api/auth/check_auth_key.php?auth_token=" . urlencode($auth_token);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $check_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http_code !== 200 || !$response) {
$error = 'Failed to contact authentication server.';
} else {
$data = json_decode($response, true);
if (isset($data['status']) && $data['status'] === 'success') {
$user_token = $data['user_token'];
$username = $data['username'];
$email = $data['email'] ?? '';
require_once __DIR__ . '/config/database.php';
$db = getDbConnection();
// Check if user exists in our db
$stmt = $db->prepare("SELECT * FROM neptune_users WHERE user_token = ?");
$stmt->execute([$user_token]);
$user = $stmt->fetch();
if ($user) {
$_SESSION['neptune_loggedin'] = true;
$_SESSION['neptune_user_token'] = $user['user_token'];
$_SESSION['neptune_username'] = $user['username'];
$_SESSION['neptune_role'] = $user['role'];
header('Location: /');
exit;
} else {
// First user becomes admin
$count = $db->query("SELECT COUNT(*) as c FROM neptune_users")->fetch()['c'];
$role = ($count == 0) ? 'admin' : 'user';
$stmt = $db->prepare("INSERT INTO neptune_users (user_token, username, email, role) VALUES (?, ?, ?, ?)");
$stmt->execute([$user_token, $username, $email, $role]);
$_SESSION['neptune_loggedin'] = true;
$_SESSION['neptune_user_token'] = $user_token;
$_SESSION['neptune_username'] = $username;
$_SESSION['neptune_role'] = $role;
header('Location: /');
exit;
}
} else {
$error = 'Authentication failed: ' . ($data['msg'] ?? 'unknown error');
}
}
}
?>
<!DOCTYPE html>
<html lang="en" data-bs-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Neptune - Login</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.1/css/all.min.css" rel="stylesheet">
<style>
body { background: #0a0e1a; display: flex; align-items: center; justify-content: center; min-height: 100vh; }
.login-card { background: #131a2b; border: 1px solid #1e2a45; border-radius: .75rem; padding: 2.5rem; max-width: 420px; width: 100%; }
.login-card h1 { font-size: 1.5rem; }
.login-card p { color: #64748b; font-size: .9rem; }
.btn-jakach { background: #3b82f6; color: #fff; }
.btn-jakach:hover { background: #2563eb; color: #fff; }
</style>
</head>
<body>
<div class="login-card text-center">
<i class="fas fa-globe text-primary mb-3" style="font-size: 2.5rem;"></i>
<h1 class="fw-bold mb-1">Neptune</h1>
<p class="mb-4">Cybersecurity Incident Journal</p>
<?php if ($error): ?>
<div class="alert alert-danger py-2 small"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>
<?php if ($success): ?>
<div class="alert alert-success py-2 small"><?= htmlspecialchars($success) ?></div>
<?php endif; ?>
<a href="https://auth.jakach.ch/?send_to=<?= urlencode($callbackUrl) ?>" class="btn btn-jakach w-100 py-2 mb-2">
<i class="fas fa-right-to-bracket me-2"></i>Log in with Jakach Auth
</a>
<small class="text-secondary">First user automatically becomes admin</small>
</div>
</body>
</html>
-6
View File
@@ -1,6 +0,0 @@
<?php
session_start();
$_SESSION = array();
session_destroy();
header('Location: /');
exit;
-18
View File
@@ -14,24 +14,6 @@ server {
include fastcgi_params;
}
location /login.php {
fastcgi_pass php:9000;
fastcgi_param SCRIPT_FILENAME /var/www/backend/login.php;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
include fastcgi_params;
}
location /logout.php {
fastcgi_pass php:9000;
fastcgi_param SCRIPT_FILENAME /var/www/backend/logout.php;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
include fastcgi_params;
}
location / {
try_files $uri $uri/ /index.html;
}
+71 -24
View File
@@ -43,6 +43,7 @@ document.addEventListener('DOMContentLoaded', () => {
document.getElementById('saveLink').addEventListener('click', saveLink);
document.getElementById('saveShape').addEventListener('click', saveShape);
document.getElementById('addUserBtn').addEventListener('click', addUser);
document.getElementById('logoutBtn').addEventListener('click', logout);
document.getElementById('teamFilter').addEventListener('change', renderTimeline);
document.getElementById('searchEvents').addEventListener('input', renderTimeline);
document.getElementById('shapeOpacity').addEventListener('input', (e) => {
@@ -892,43 +893,89 @@ let currentRole = null;
async function checkSession() {
try {
const res = await fetch('/api/session');
if (res.redirected || !res.ok) {
window.location.replace('/login.php');
return;
}
const data = await res.json();
if (data.loggedin) {
currentUser = data.username;
currentRole = data.role;
document.getElementById('userDisplay').textContent = data.username;
if (data.role === 'admin' || data.admin_count === 0) {
if (data.role === 'admin') {
document.getElementById('settingsBtn').classList.remove('d-none');
}
document.getElementById('loginOverlay').style.display = 'none';
return;
}
} catch (_) {}
// Show login overlay
document.getElementById('loginOverlay').style.display = 'flex';
}
async function performLogin(authToken) {
const errEl = document.getElementById('loginError');
const sucEl = document.getElementById('loginSuccess');
errEl.style.display = 'none';
sucEl.style.display = 'none';
try {
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ auth_token: authToken })
});
const data = await res.json();
if (data.status === 'success') {
currentUser = data.username;
currentRole = data.role;
document.getElementById('userDisplay').textContent = data.username;
if (data.role === 'admin') document.getElementById('settingsBtn').classList.remove('d-none');
document.getElementById('loginOverlay').style.display = 'none';
// Clean URL
window.history.replaceState({}, '', '/');
// Reload data
loadTeams().then(() => loadEvents());
loadNetworkData();
} else {
window.location.replace('/login.php');
errEl.textContent = data.error || 'Login failed';
errEl.style.display = 'block';
}
} catch (e) {
// Retry once after a brief delay in case of transient network issue
setTimeout(async () => {
try {
const res = await fetch('/api/session');
if (!res.ok || res.redirected) throw new Error();
const data = await res.json();
if (data.loggedin) {
currentUser = data.username;
currentRole = data.role;
document.getElementById('userDisplay').textContent = data.username;
if (data.role === 'admin' || data.admin_count === 0) {
document.getElementById('settingsBtn').classList.remove('d-none');
}
return;
}
} catch (_) {}
window.location.replace('/login.php');
}, 500);
errEl.textContent = 'Connection error';
errEl.style.display = 'block';
}
}
async function logout() {
await apiFetch('logout', { method: 'POST' });
currentUser = null;
currentRole = null;
document.getElementById('settingsBtn').classList.add('d-none');
document.getElementById('userDisplay').textContent = '';
document.getElementById('loginOverlay').style.display = 'flex';
}
// Check for auth token in URL on page load
document.addEventListener('DOMContentLoaded', () => {
const params = new URLSearchParams(window.location.search);
const authToken = params.get('auth');
if (authToken) {
// Show a loading state on overlay
document.getElementById('loginOverlay').style.display = 'flex';
document.querySelector('#loginOverlay .btn').textContent = 'Authenticating...';
performLogin(authToken);
}
checkSession().then(() => {
// Init canvas and load data
canvas = document.getElementById('networkCanvas');
ctx = canvas.getContext('2d');
resizeCanvas();
loadTeams().then(() => loadEvents());
loadNetworkData();
document.getElementById('loginBtn').addEventListener('click', () => {
const callbackUrl = window.location.origin + '/?auth_callback=1';
window.location.href = 'https://auth.jakach.ch/?send_to=' + encodeURIComponent(callbackUrl);
});
async function loadUsers() {
const list = document.getElementById('userList');
try {
+16 -1
View File
@@ -36,7 +36,7 @@
<div class="ms-auto d-flex align-items-center">
<span class="text-secondary small me-2" id="userDisplay"></span>
<button class="btn btn-outline-secondary btn-sm me-2 d-none" id="settingsBtn" data-bs-toggle="modal" data-bs-target="#settingsModal" title="Settings"><i class="fas fa-cog"></i></button>
<a href="/logout.php" class="btn btn-outline-secondary btn-sm"><i class="fas fa-sign-out-alt"></i></a>
<button class="btn btn-outline-secondary btn-sm" id="logoutBtn"><i class="fas fa-sign-out-alt"></i></button>
</div>
</div>
</div>
@@ -375,6 +375,21 @@
</div>
</div>
<!-- ==================== LOGIN OVERLAY ==================== -->
<div id="loginOverlay" style="position:fixed;top:0;left:0;width:100%;height:100%;background:#0a0e1a;z-index:9999;display:flex;align-items:center;justify-content:center;">
<div style="text-align:center;max-width:400px;padding:2rem;">
<i class="fas fa-globe text-primary mb-3" style="font-size:2.5rem;"></i>
<h1 class="fw-bold mb-1">Neptune</h1>
<p class="text-secondary mb-4">Cybersecurity Incident Journal</p>
<div id="loginError" class="alert alert-danger py-2 small" style="display:none;"></div>
<div id="loginSuccess" class="alert alert-success py-2 small" style="display:none;"></div>
<button id="loginBtn" class="btn btn-primary w-100 py-2 mb-2">
<i class="fas fa-right-to-bracket me-2"></i>Log in with Jakach Auth
</button>
<small class="text-secondary">First user automatically becomes admin</small>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="assets/js/app.js"></script>
</body>