Refactor fixes and adjustments
This commit is contained in:
@@ -18,6 +18,15 @@
|
||||
|
||||
This refactor improves maintainability, testability, and documentation clarity across all API endpoints.
|
||||
|
||||
### Refactor fixes and adjustments
|
||||
|
||||
- Added fallback checks for disableFormLogin / disableBasicAuth / disableOIDCLogin when coming in either at the top level or under loginOptions.
|
||||
- Updated auth.js to read and store the nested loginOptions booleans correctly in localStorage, then show/hide the Basic‑Auth and OIDC buttons as configured.
|
||||
- Changed the logout controller to header("Location: /index.html?logout=1") so after /api/auth/logout.php it lands on the root index.html, not under /api/auth/.
|
||||
- Switched your share modal code to use a leading slash ("/api/file/share.php") so it generates absolute URLs instead of relative /share.php.
|
||||
- In the shared‑folder gallery, adjusted the client‑side image path to point at /uploads/... instead of /api/folder/uploads/...
|
||||
- Updated both AdminModel defaults and the AuthController to use the exact full path
|
||||
|
||||
---
|
||||
|
||||
## Changes 4/15/2025
|
||||
|
||||
@@ -165,8 +165,8 @@ define('BASE_URL', 'http://yourwebsite/uploads/');
|
||||
if (strpos(BASE_URL, 'yourwebsite') !== false) {
|
||||
$defaultShareUrl = isset($_SERVER['HTTP_HOST'])
|
||||
? "http://" . $_SERVER['HTTP_HOST'] . "/share.php"
|
||||
: "http://localhost/public/api/file/share.php";
|
||||
: "http://localhost/api/file/share.php";
|
||||
} else {
|
||||
$defaultShareUrl = rtrim(BASE_URL, '/') . "api/file/share.php";
|
||||
$defaultShareUrl = rtrim(BASE_URL, '/') . "/api/file/share.php";
|
||||
}
|
||||
define('SHARE_URL', getenv('SHARE_URL') ? getenv('SHARE_URL') : $defaultShareUrl);
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
<link rel="icon" type="image/png" href="/assets/logo.png">
|
||||
<link rel="icon" type="image/svg+xml" href="/assets/logo.svg">
|
||||
<meta name="csrf-token" content="">
|
||||
<meta name="share-url" content="">
|
||||
<meta name="share-url" content="/api/file/share.php">
|
||||
<!-- Google Fonts and Material Icons -->
|
||||
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap" rel="stylesheet" />
|
||||
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
|
||||
@@ -200,7 +200,7 @@
|
||||
</div>
|
||||
<!-- Basic HTTP Login Option -->
|
||||
<div class="text-center mt-3">
|
||||
<a href="/public/api/auth/login_basic.php" class="btn btn-secondary" data-i18n-key="basic_http_login">Use Basic HTTP
|
||||
<a href="/api/auth/login_basic.php" class="btn btn-secondary" data-i18n-key="basic_http_login">Use Basic HTTP
|
||||
Login</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -25,7 +25,7 @@ const currentOIDCConfig = {
|
||||
providerUrl: "https://your-oidc-provider.com",
|
||||
clientId: "YOUR_CLIENT_ID",
|
||||
clientSecret: "YOUR_CLIENT_SECRET",
|
||||
redirectUri: "https://yourdomain.com/auth.php?oidc=callback",
|
||||
redirectUri: "https://yourdomain.com/api/auth/auth.php?oidc=callback",
|
||||
globalOtpauthUrl: ""
|
||||
};
|
||||
window.currentOIDCConfig = currentOIDCConfig;
|
||||
@@ -51,7 +51,7 @@ function openTOTPLoginModal() {
|
||||
const isFormLogin = Boolean(window.__lastLoginData);
|
||||
if (!isFormLogin) {
|
||||
// disable Basic‑Auth link
|
||||
const basicLink = document.querySelector("a[href='api/auth/login_basic.php']");
|
||||
const basicLink = document.querySelector("a[href='/api/auth/login_basic.php']");
|
||||
if (basicLink) {
|
||||
basicLink.style.pointerEvents = 'none';
|
||||
basicLink.style.opacity = '0.5';
|
||||
@@ -80,7 +80,7 @@ function updateLoginOptionsUI({ disableFormLogin, disableBasicAuth, disableOIDCL
|
||||
const authForm = document.getElementById("authForm");
|
||||
|
||||
if (authForm) authForm.style.display = disableFormLogin ? "none" : "block";
|
||||
const basicAuthLink = document.querySelector("a[href='api/auth/login_basic.php']");
|
||||
const basicAuthLink = document.querySelector("a[href='/api/auth/login_basic.php']");
|
||||
if (basicAuthLink) basicAuthLink.style.display = disableBasicAuth ? "none" : "inline-block";
|
||||
const oidcLoginBtn = document.getElementById("oidcLoginBtn");
|
||||
if (oidcLoginBtn) oidcLoginBtn.style.display = disableOIDCLogin ? "none" : "inline-block";
|
||||
@@ -480,7 +480,7 @@ document.addEventListener("DOMContentLoaded", function () {
|
||||
const oidcLoginBtn = document.getElementById("oidcLoginBtn");
|
||||
if (oidcLoginBtn) {
|
||||
oidcLoginBtn.addEventListener("click", () => {
|
||||
window.location.href = "api/auth/auth.php?oidc=initiate";
|
||||
window.location.href = "/api/auth/auth.php?oidc=initiate";
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -97,7 +97,7 @@ export function openTOTPLoginModal() {
|
||||
.then(json => {
|
||||
if (json.status === "ok") {
|
||||
// recovery succeeded → finalize login
|
||||
window.location.href = "index.html";
|
||||
window.location.href = "/index.html";
|
||||
} else {
|
||||
showToast(json.message || t("recovery_code_verification_failed"));
|
||||
}
|
||||
@@ -125,7 +125,7 @@ export function openTOTPLoginModal() {
|
||||
.then(res => res.json())
|
||||
.then(json => {
|
||||
if (json.status === "ok") {
|
||||
window.location.href = "index.html";
|
||||
window.location.href = "/index.html";
|
||||
} else {
|
||||
showToast(json.message || t("totp_verification_failed"));
|
||||
this.value = "";
|
||||
|
||||
@@ -111,7 +111,7 @@ export function confirmSingleDownload() {
|
||||
|
||||
// Build the URL for download.php using GET parameters.
|
||||
const folder = window.currentFolder || "root";
|
||||
const downloadURL = "api/file/download.php?folder=" + encodeURIComponent(folder) +
|
||||
const downloadURL = "/api/file/download.php?folder=" + encodeURIComponent(folder) +
|
||||
"&file=" + encodeURIComponent(window.singleFileToDownload);
|
||||
|
||||
fetch(downloadURL, {
|
||||
|
||||
@@ -197,7 +197,7 @@ export function loadFileList(folderParam) {
|
||||
.then(response => {
|
||||
if (response.status === 401) {
|
||||
showToast("Session expired. Please log in again.");
|
||||
window.location.href = "logout.php";
|
||||
window.location.href = "/api/auth/logout.php";
|
||||
throw new Error("Unauthorized");
|
||||
}
|
||||
return response.json();
|
||||
|
||||
@@ -65,9 +65,7 @@ export function openShareModal(file, folder) {
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.token) {
|
||||
let shareEndpoint = document.querySelector('meta[name="share-url"]')
|
||||
? document.querySelector('meta[name="share-url"]').getAttribute('content')
|
||||
: (window.SHARE_URL || "api/file/share.php");
|
||||
const shareEndpoint = `${window.location.origin}/api/file/share.php`;
|
||||
const shareUrl = `${shareEndpoint}?token=${encodeURIComponent(data.token)}`;
|
||||
const displayDiv = document.getElementById("shareLinkDisplay");
|
||||
const inputField = document.getElementById("shareLinkInput");
|
||||
|
||||
@@ -364,7 +364,7 @@ export async function loadFolderTree(selectedFolder) {
|
||||
if (response.status === 401) {
|
||||
console.error("Unauthorized: Please log in to view folders.");
|
||||
showToast("Session expired. Please log in again.");
|
||||
window.location.href = "logout.php";
|
||||
window.location.href = "/api/auth/logout.php";
|
||||
return;
|
||||
}
|
||||
let folderData = await response.json();
|
||||
|
||||
@@ -405,7 +405,7 @@ const useResumable = true; // Enable resumable for file picker uploads
|
||||
let resumableInstance;
|
||||
function initResumableUpload() {
|
||||
resumableInstance = new Resumable({
|
||||
target: "api/upload/upload.php",
|
||||
target: "/api/upload/upload.php",
|
||||
query: { folder: window.currentFolder || "root", upload_token: window.csrfToken },
|
||||
chunkSize: 1.5 * 1024 * 1024, // 1.5 MB chunks
|
||||
simultaneousUploads: 3,
|
||||
|
||||
@@ -4,12 +4,14 @@
|
||||
require_once __DIR__ . '/../../config/config.php';
|
||||
require_once PROJECT_ROOT . '/src/models/AuthModel.php';
|
||||
require_once PROJECT_ROOT . '/vendor/autoload.php';
|
||||
require_once PROJECT_ROOT . '/src/models/AdminModel.php';
|
||||
|
||||
use RobThree\Auth\Algorithm;
|
||||
use RobThree\Auth\Providers\Qr\GoogleChartsQrCodeProvider;
|
||||
use Jumbojett\OpenIDConnectClient;
|
||||
|
||||
class AuthController {
|
||||
class AuthController
|
||||
{
|
||||
|
||||
/**
|
||||
* @OA\Post(
|
||||
@@ -56,7 +58,8 @@ class AuthController {
|
||||
*
|
||||
* @return void Redirects on success or outputs JSON error.
|
||||
*/
|
||||
public function auth(): void {
|
||||
public function auth(): void
|
||||
{
|
||||
// Global exception handler.
|
||||
set_exception_handler(function ($e) {
|
||||
error_log("Unhandled exception: " . $e->getMessage());
|
||||
@@ -73,20 +76,15 @@ class AuthController {
|
||||
$oidcAction = 'callback';
|
||||
}
|
||||
if ($oidcAction) {
|
||||
// Load admin configuration for OIDC.
|
||||
$adminConfigFile = USERS_DIR . 'adminConfig.json';
|
||||
if (file_exists($adminConfigFile)) {
|
||||
$enc = file_get_contents($adminConfigFile);
|
||||
$dec = decryptData($enc, $encryptionKey);
|
||||
$cfg = ($dec !== false) ? json_decode($dec, true) : [];
|
||||
} else {
|
||||
$cfg = [];
|
||||
}
|
||||
$oidc_provider_url = $cfg['oidc']['providerUrl'] ?? 'https://your-oidc-provider.com';
|
||||
$oidc_client_id = $cfg['oidc']['clientId'] ?? 'YOUR_CLIENT_ID';
|
||||
$oidc_client_secret = $cfg['oidc']['clientSecret'] ?? 'YOUR_CLIENT_SECRET';
|
||||
$oidc_redirect_uri = $cfg['oidc']['redirectUri'] ?? 'https://yourdomain.com/api/auth/auth.php?oidc=callback';
|
||||
// new: delegate to AdminModel
|
||||
$cfg = AdminModel::getConfig();
|
||||
// Optional: log to confirm you loaded the right values
|
||||
error_log("Loaded OIDC config: " . print_r($cfg['oidc'], true));
|
||||
|
||||
$oidc_provider_url = $cfg['oidc']['providerUrl'];
|
||||
$oidc_client_id = $cfg['oidc']['clientId'];
|
||||
$oidc_client_secret = $cfg['oidc']['clientSecret'];
|
||||
$oidc_redirect_uri = $cfg['oidc']['redirectUri'];
|
||||
$oidc = new OpenIDConnectClient($oidc_provider_url, $oidc_client_id, $oidc_client_secret);
|
||||
$oidc->setRedirectURL($oidc_redirect_uri);
|
||||
|
||||
@@ -110,7 +108,7 @@ class AuthController {
|
||||
if ($totp_secret) {
|
||||
$_SESSION['pending_login_user'] = $username;
|
||||
$_SESSION['pending_login_secret'] = $totp_secret;
|
||||
header("Location: index.html?totp_required=1");
|
||||
header("Location: /index.html?totp_required=1");
|
||||
exit();
|
||||
}
|
||||
|
||||
@@ -120,7 +118,7 @@ class AuthController {
|
||||
$_SESSION["username"] = $username;
|
||||
$_SESSION["isAdmin"] = (AuthModel::getUserRole($username) === "1");
|
||||
$_SESSION["folderOnly"] = loadUserPermissions($username);
|
||||
header("Location: index.html");
|
||||
header("Location: /index.html");
|
||||
exit();
|
||||
} catch (Exception $e) {
|
||||
error_log("OIDC authentication error: " . $e->getMessage());
|
||||
@@ -298,7 +296,8 @@ class AuthController {
|
||||
*
|
||||
* @return void Outputs a JSON response with authentication details.
|
||||
*/
|
||||
public function checkAuth(): void {
|
||||
public function checkAuth(): void
|
||||
{
|
||||
header('Content-Type: application/json');
|
||||
|
||||
$usersFile = USERS_DIR . USERS_FILE;
|
||||
@@ -366,7 +365,8 @@ class AuthController {
|
||||
*
|
||||
* @return void Outputs the JSON response.
|
||||
*/
|
||||
public function getToken(): void {
|
||||
public function getToken(): void
|
||||
{
|
||||
header('Content-Type: application/json');
|
||||
echo json_encode([
|
||||
"csrf_token" => $_SESSION['csrf_token'],
|
||||
@@ -400,7 +400,8 @@ class AuthController {
|
||||
*
|
||||
* @return void Redirects on success or sends a 401 header.
|
||||
*/
|
||||
public function loginBasic(): void {
|
||||
public function loginBasic(): void
|
||||
{
|
||||
// Set header for plain-text or JSON as needed.
|
||||
header('Content-Type: application/json');
|
||||
|
||||
@@ -432,7 +433,7 @@ class AuthController {
|
||||
// If TOTP is required, store pending values and redirect to prompt for TOTP.
|
||||
$_SESSION['pending_login_user'] = $username;
|
||||
$_SESSION['pending_login_secret'] = $secret;
|
||||
header("Location: index.html?totp_required=1");
|
||||
header("Location: /index.html?totp_required=1");
|
||||
exit;
|
||||
}
|
||||
// Finalize login.
|
||||
@@ -442,7 +443,7 @@ class AuthController {
|
||||
$_SESSION["isAdmin"] = (AuthModel::getUserRole($username) === "1");
|
||||
$_SESSION["folderOnly"] = AuthModel::loadFolderPermission($username);
|
||||
|
||||
header("Location: index.html");
|
||||
header("Location: /index.html");
|
||||
exit;
|
||||
}
|
||||
// Invalid credentials; prompt again.
|
||||
@@ -473,7 +474,8 @@ class AuthController {
|
||||
*
|
||||
* @return void Redirects to index.html with a logout flag.
|
||||
*/
|
||||
public function logout(): void {
|
||||
public function logout(): void
|
||||
{
|
||||
// Retrieve headers and check CSRF token.
|
||||
$headersArr = array_change_key_case(getallheaders(), CASE_LOWER);
|
||||
$receivedToken = isset($headersArr['x-csrf-token']) ? trim($headersArr['x-csrf-token']) : '';
|
||||
@@ -508,9 +510,14 @@ class AuthController {
|
||||
// Clear the session cookie.
|
||||
if (ini_get("session.use_cookies")) {
|
||||
$params = session_get_cookie_params();
|
||||
setcookie(session_name(), '', time() - 42000,
|
||||
$params["path"], $params["domain"],
|
||||
$params["secure"], $params["httponly"]
|
||||
setcookie(
|
||||
session_name(),
|
||||
'',
|
||||
time() - 42000,
|
||||
$params["path"],
|
||||
$params["domain"],
|
||||
$params["secure"],
|
||||
$params["httponly"]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -518,7 +525,7 @@ class AuthController {
|
||||
session_destroy();
|
||||
|
||||
// Redirect the user to the login page (or index) with a logout flag.
|
||||
header("Location: index.html?logout=1");
|
||||
header("Location: /index.html?logout=1");
|
||||
exit;
|
||||
}
|
||||
}
|
||||
@@ -935,7 +935,7 @@ class FileController {
|
||||
</head>
|
||||
<body>
|
||||
<h2>This file is protected by a password.</h2>
|
||||
<form method="get" action="api/file/share.php">
|
||||
<form method="get" action="/api/file/share.php">
|
||||
<input type="hidden" name="token" value="<?php echo htmlspecialchars($token, ENT_QUOTES, 'UTF-8'); ?>">
|
||||
<label for="pass">Password:</label>
|
||||
<input type="password" name="pass" id="pass" required>
|
||||
|
||||
@@ -437,7 +437,7 @@ class FolderController {
|
||||
<div class="container">
|
||||
<h2>Folder Protected</h2>
|
||||
<p>This folder is protected by a password. Please enter the password to view its contents.</p>
|
||||
<form method="get" action="api/folder/shareFolder.php">
|
||||
<form method="get" action="/api/folder/shareFolder.php">
|
||||
<input type="hidden" name="token" value="<?php echo htmlspecialchars($token, ENT_QUOTES, 'UTF-8'); ?>">
|
||||
<label for="pass">Password:</label>
|
||||
<input type="password" name="pass" id="pass" required>
|
||||
@@ -534,7 +534,7 @@ class FolderController {
|
||||
foreach ($files as $file):
|
||||
$filePath = $data['realFolderPath'] . DIRECTORY_SEPARATOR . $file;
|
||||
$fileSize = file_exists($filePath) ? formatBytes(filesize($filePath)) : "Unknown";
|
||||
$downloadLink = "api/folder/downloadSharedFile.php?token=" . urlencode($token) . "&file=" . urlencode($file);
|
||||
$downloadLink = "/api/folder/downloadSharedFile.php?token=" . urlencode($token) . "&file=" . urlencode($file);
|
||||
?>
|
||||
<tr>
|
||||
<td>
|
||||
@@ -557,7 +557,7 @@ class FolderController {
|
||||
<!-- Pagination Controls -->
|
||||
<div class="pagination">
|
||||
<?php if ($currentPage > 1): ?>
|
||||
<a href="api/folder/shareFolder.php?token=<?php echo urlencode($token); ?>&page=<?php echo $currentPage - 1; ?><?php echo !empty($providedPass) ? "&pass=" . urlencode($providedPass) : ""; ?>">Prev</a>
|
||||
<a href="/api/folder/shareFolder.php?token=<?php echo urlencode($token); ?>&page=<?php echo $currentPage - 1; ?><?php echo !empty($providedPass) ? "&pass=" . urlencode($providedPass) : ""; ?>">Prev</a>
|
||||
<?php else: ?>
|
||||
<span>Prev</span>
|
||||
<?php endif; ?>
|
||||
@@ -569,12 +569,12 @@ class FolderController {
|
||||
<?php if ($i == $currentPage): ?>
|
||||
<span class="current"><?php echo $i; ?></span>
|
||||
<?php else: ?>
|
||||
<a href="api/folder/shareFolder.php?token=<?php echo urlencode($token); ?>&page=<?php echo $i; ?><?php echo !empty($providedPass) ? "&pass=" . urlencode($providedPass) : ""; ?>"><?php echo $i; ?></a>
|
||||
<a href="/api/folder/shareFolder.php?token=<?php echo urlencode($token); ?>&page=<?php echo $i; ?><?php echo !empty($providedPass) ? "&pass=" . urlencode($providedPass) : ""; ?>"><?php echo $i; ?></a>
|
||||
<?php endif; ?>
|
||||
<?php endfor; ?>
|
||||
|
||||
<?php if ($currentPage < $totalPages): ?>
|
||||
<a href="api/folder/shareFolder.php?token=<?php echo urlencode($token); ?>&page=<?php echo $currentPage + 1; ?><?php echo !empty($providedPass) ? "&pass=" . urlencode($providedPass) : ""; ?>">Next</a>
|
||||
<a href="/api/folder/shareFolder.php?token=<?php echo urlencode($token); ?>&page=<?php echo $currentPage + 1; ?><?php echo !empty($providedPass) ? "&pass=" . urlencode($providedPass) : ""; ?>">Next</a>
|
||||
<?php else: ?>
|
||||
<span>Next</span>
|
||||
<?php endif; ?>
|
||||
@@ -584,7 +584,7 @@ class FolderController {
|
||||
<?php if (isset($data['record']['allowUpload']) && $data['record']['allowUpload'] == 1): ?>
|
||||
<div class="upload-container">
|
||||
<h3>Upload File (50mb max size)</h3>
|
||||
<form action="api/folder/uploadToSharedFolder.php" method="post" enctype="multipart/form-data">
|
||||
<form action="/api/folder/uploadToSharedFolder.php" method="post" enctype="multipart/form-data">
|
||||
<!-- Pass the share token so the upload endpoint can verify -->
|
||||
<input type="hidden" name="token" value="<?php echo htmlspecialchars($token, ENT_QUOTES, 'UTF-8'); ?>">
|
||||
<input type="file" name="fileToUpload" required>
|
||||
@@ -613,7 +613,9 @@ class FolderController {
|
||||
var galleryContainer = document.getElementById("galleryViewContainer");
|
||||
var html = '<div class="shared-gallery-container">';
|
||||
filesData.forEach(function(file) {
|
||||
var fileUrl = "uploads/<?php echo htmlspecialchars($folderName, ENT_QUOTES, 'UTF-8'); ?>/" + encodeURIComponent(file);
|
||||
var fileUrl = window.location.origin
|
||||
+ "/uploads/<?php echo rawurlencode($folderName); ?>/"
|
||||
+ encodeURIComponent(file);
|
||||
var ext = file.split('.').pop().toLowerCase();
|
||||
var thumbnail = "";
|
||||
if (['jpg','jpeg','png','gif','bmp','webp','svg','ico'].indexOf(ext) >= 0) {
|
||||
@@ -900,7 +902,7 @@ class FolderController {
|
||||
$_SESSION['upload_message'] = "File uploaded successfully.";
|
||||
|
||||
// Redirect back to the shared folder view.
|
||||
$redirectUrl = "api/folder/shareFolder.php?token=" . urlencode($token);
|
||||
$redirectUrl = "/api/folder/shareFolder.php?token=" . urlencode($token);
|
||||
header("Location: " . $redirectUrl);
|
||||
exit;
|
||||
}
|
||||
|
||||
@@ -104,7 +104,7 @@ class AdminModel
|
||||
'providerUrl' => 'https://your-oidc-provider.com',
|
||||
'clientId' => 'YOUR_CLIENT_ID',
|
||||
'clientSecret' => 'YOUR_CLIENT_SECRET',
|
||||
'redirectUri' => 'https://yourdomain.com/auth.php?oidc=callback'
|
||||
'redirectUri' => 'https://yourdomain.com/api/auth/auth.php?oidc=callback'
|
||||
],
|
||||
'loginOptions' => [
|
||||
'disableFormLogin' => false,
|
||||
|
||||
@@ -403,7 +403,7 @@ class FolderModel {
|
||||
$baseUrl = $protocol . "://" . $host;
|
||||
}
|
||||
// The share URL points to the shared folder page.
|
||||
$link = $baseUrl . "api/folder/shareFolder.php?token=" . urlencode($token);
|
||||
$link = $baseUrl . "/api/folder/shareFolder.php?token=" . urlencode($token);
|
||||
|
||||
return ["token" => $token, "expires" => $expires, "link" => $link];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user