Compare commits

..

10 Commits

Author SHA1 Message Date
Ryan
61357af203 Fetch URL fixes, Extended “Remember Me” cookie behavior, submitLogin() overhaul 2025-04-19 17:53:01 -04:00
Ryan
e390a35e8a Gallery View add selection actions and search filtering 2025-04-18 02:58:30 -04:00
Ryan
7e50ba1f70 test pipeline 2025-04-18 00:52:39 -04:00
Ryan
cc41f8cc95 update sync 2025-04-18 00:51:51 -04:00
Ryan
7c31b9689f update changelog & test pipeline 2025-04-18 00:43:33 -04:00
Ryan
461921b7bc Remember me adjustment 2025-04-18 00:40:17 -04:00
Ryan
3b58123584 User Panel added API Docs link 2025-04-17 06:45:00 -04:00
Ryan
cd9d7eb0ba HTML wrapper that pulls in Redoc from the CDN 2025-04-17 06:28:05 -04:00
Ryan
c0c8d68dc4 mark openapi.json & api.html as documentation 2025-04-17 06:11:27 -04:00
Ryan
2dfcb4062f Generate OpenAPI spec and API HTML docs 2025-04-17 06:04:15 -04:00
23 changed files with 3442 additions and 503 deletions

2
.gitattributes vendored Normal file
View File

@@ -0,0 +1,2 @@
public/api.html linguist-documentation
public/openapi.json linguist-documentation

40
.github/workflows/sync-changelog.yml vendored Normal file
View File

@@ -0,0 +1,40 @@
name: Sync Changelog to Docker Repo
on:
push:
paths:
- 'CHANGELOG.md'
jobs:
sync:
runs-on: ubuntu-latest
steps:
- name: Checkout FileRise
uses: actions/checkout@v4
with:
path: file-rise
- name: Checkout filerise-docker
uses: actions/checkout@v4
with:
repository: error311/filerise-docker
token: ${{ secrets.PAT_TOKEN }}
path: docker-repo
- name: Copy CHANGELOG.md
run: |
cp file-rise/CHANGELOG.md docker-repo/CHANGELOG.md
- name: Commit & push
working-directory: docker-repo
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add CHANGELOG.md
if git diff --cached --quiet; then
echo "No changes to commit"
else
git commit -m "chore: sync CHANGELOG.md from FileRise"
git push origin main
fi

View File

@@ -1,5 +1,68 @@
# Changelog
## Changes 4/19/2025
- **Extended “Remember Me” cookie behavior**
In `AuthController::finalizeLogin()`, after setting `remember_me_token` reissued the PHP session cookie with the same 30day expiry and called `session_regenerate_id(true)`.
- **Fetch URL fixes**
Changed all frontend `fetch("api/…")` calls to absolute paths `fetch("/api/…")` to avoid relativepath 404/403 issues.
- **CSRF token refresh**
Updated `submitLogin()` and both TOTP submission handlers to `async/await` a fresh CSRF token from `/api/auth/token.php` (with `credentials: "include"`) immediately before any POST.
- **submitLogin() overhaul**
Refactored to:
1. Fetch CSRF
2. POST credentials to `/api/auth/auth.php`
3. On `totp_required`, refetch CSRF *again* before calling `openTOTPLoginModal()`
4. Handle full logins vs. TOTP flows cleanly.
- **TOTP handlers update**
In both the “Confirm TOTP” button flow and the autosubmit on 6digit input:
- Refreshed CSRF token before every `/api/totp_verify.php` call
- Checked `response.ok` before parsing JSON
- Improved `.catch` error handling
- **verifyTOTP() endpoint enhancement**
Inside the **pendinglogin** branch of `verifyTOTP()`:
- Pulled `$_SESSION['pending_login_remember_me']`
- If true, wrote the persistent token store, set `remember_me_token`, reissued the session cookie, and regenerated the session ID
- Cleaned up pending session variables
---
## Changes 4/18/2025
### fileListView.js
- Seed and persist `itemsPerPage` from `localStorage`
- Use `window.itemsPerPage` for pagination in gallery
- Enable search input filtering in gallery mode
- Always rerender the viewtoggle button on gallery load
- Restore percard action buttons (download, edit, rename, share)
- Assign real `value` to checkboxes and call `updateFileActionButtons()` on change
- Update `changePage` and `changeItemsPerPage` to respect `viewMode`
### fileTags.js
- Import `renderFileTable` and `renderGalleryView`
- Rerender the list after saving a singlefile tag
- Rerender the list after saving multifile tags
---
## Changes 4/17/2025
- Generate OpenAPI spec and API HTML docs
- Fully autogenerated OpenAPI spec (`openapi.json`) and interactive HTML docs (`api.html`) powered by Redoc.
- .gitattributes added to mark (`openapi.json`) & (`api.html`) as documentation.
- User Panel added API Docs link.
- Adjusted remember_me_token.
- Test pipeline
---
## Changes 4/16 Refactor API endpoints and modularize controllers and models
- Reorganized project structure to separate API logic into dedicated controllers and models:

View File

@@ -20,6 +20,8 @@ Upload, organize, and share files through a sleek web interface. **FileRise** is
- 🗃️ **Folder Sharing & File Sharing:** Easily share entire folders via secure, expiring public links. Folder shares can be password-protected, and shared folders support file uploads from outside users with a separate, secure upload mechanism. Folder listings are paginated (10 items per page) with navigation controls, and file sizes are displayed in MB for clarity. Share files with others using one-time or expiring public links (with password protection if desired) convenient for sending individual files without exposing the whole app.
- 📚 **API Documentation:** Fully autogenerated OpenAPI spec (`openapi.json`) and interactive HTML docs (`api.html`) powered by Redoc.
- 📝 **Built-in Editor & Preview:** View images, videos, audio, and PDFs inline with a preview modal no need to download just to see them. Edit text/code files right in your browser with a CodeMirror-based editor featuring syntax highlighting and line numbers. Great for config files or notes tweak and save changes without leaving FileRise.
- 🏷️ **Tags & Search:** Categorize your files with color-coded tags and locate them instantly using our indexed real-time search. Easily switch to Advanced Search mode to enable fuzzy matching not only across file names, tags, and uploader fields but also within the content of text files—helping you find that “important” document even if you make a typo or need to search deep within the file.
@@ -28,7 +30,7 @@ Upload, organize, and share files through a sleek web interface. **FileRise** is
- 🎨 **Responsive UI (Dark/Light Mode):** FileRise is mobile-friendly out of the box manage files from your phone or tablet with a responsive layout. Choose between Dark mode or Light theme, or let it follow your system preference. The interface remembers your preferences (layout, items per page, last visited folder, etc.) for a personalized experience each time.
- 🌐 **Internationalization & Localization:** FileRise supports multiple languages via an integrated i18n system. Users can switch languages through a user panel dropdown, and their choice is saved in local storage for a consistent experience across sessions. Currently available in English, Spanish, and French—please report any translation issues you encounter.
- 🌐 **Internationalization & Localization:** FileRise supports multiple languages via an integrated i18n system. Users can switch languages through a user panel dropdown, and their choice is saved in local storage for a consistent experience across sessions. Currently available in English, Spanish, French & German—please report any translation issues you encounter.
- 🗑️ **Trash & File Recovery:** Mistakenly deleted files? No worries deleted items go to the Trash instead of immediate removal. Admins can restore files from Trash or empty it to free space. FileRise auto-purges old trash entries (default 3 days) to keep your storage tidy.
@@ -58,8 +60,6 @@ If you have Docker installed, you can get FileRise up and running in minutes:
docker pull error311/filerise-docker:latest
```
*(For Apple Silicon (M1/M2) users, use --platform linux/amd64 tag until multi-arch support is added.)*
- **Run a container:**
``` bash

View File

@@ -1,73 +1,61 @@
<?php
// config.php
// Prevent caching
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
header("Pragma: no-cache");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
header("Expires: 0");
header('X-Content-Type-Options: nosniff');
// Security headers
header("X-Content-Type-Options: nosniff");
header('X-Content-Type-Options: nosniff');
header("X-Frame-Options: SAMEORIGIN");
header("Referrer-Policy: no-referrer-when-downgrade");
// Only include Strict-Transport-Security if you are using HTTPS
header("Permissions-Policy: geolocation=(), microphone=(), camera=()");
header("X-XSS-Protection: 1; mode=block");
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
header("Strict-Transport-Security: max-age=31536000; includeSubDomains; preload");
}
header("Permissions-Policy: geolocation=(), microphone=(), camera=()");
header("X-XSS-Protection: 1; mode=block");
// Define constants.
// Define constants
define('PROJECT_ROOT', dirname(__DIR__));
define('UPLOAD_DIR', '/var/www/uploads/');
define('USERS_DIR', '/var/www/users/');
define('USERS_FILE', 'users.txt');
define('META_DIR', '/var/www/metadata/');
define('META_FILE', 'file_metadata.json');
define('TRASH_DIR', UPLOAD_DIR . 'trash/');
define('TIMEZONE', 'America/New_York');
define('DATE_TIME_FORMAT', 'm/d/y h:iA');
define('TOTAL_UPLOAD_SIZE', '5G');
define('UPLOAD_DIR', '/var/www/uploads/');
define('USERS_DIR', '/var/www/users/');
define('USERS_FILE', 'users.txt');
define('META_DIR', '/var/www/metadata/');
define('META_FILE', 'file_metadata.json');
define('TRASH_DIR', UPLOAD_DIR . 'trash/');
define('TIMEZONE', 'America/New_York');
define('DATE_TIME_FORMAT','m/d/y h:iA');
define('TOTAL_UPLOAD_SIZE','5G');
define('REGEX_FOLDER_NAME', '/^[\p{L}\p{N}_\-\s\/\\\\]+$/u');
define('PATTERN_FOLDER_NAME', '[\p{L}\p{N}_\-\s\/\\\\]+');
define('REGEX_FILE_NAME', '/^[\p{L}\p{N}\p{M}%\-\.\(\) _]+$/u');
define('REGEX_USER', '/^[\p{L}\p{N}_\- ]+$/u');
define('PATTERN_FOLDER_NAME','[\p{L}\p{N}_\-\s\/\\\\]+');
define('REGEX_FILE_NAME', '/^[\p{L}\p{N}\p{M}%\-\.\(\) _]+$/u');
define('REGEX_USER', '/^[\p{L}\p{N}_\- ]+$/u');
date_default_timezone_set(TIMEZONE);
/**
* Encrypts data using AES-256-CBC.
*
* @param string $data The plaintext.
* @param string $encryptionKey The encryption key.
* @return string Base64-encoded string containing IV and ciphertext.
*/
// Encryption helpers
function encryptData($data, $encryptionKey)
{
$cipher = 'AES-256-CBC';
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext = openssl_encrypt($data, $cipher, $encryptionKey, OPENSSL_RAW_DATA, $iv);
return base64_encode($iv . $ciphertext);
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$ct = openssl_encrypt($data, $cipher, $encryptionKey, OPENSSL_RAW_DATA, $iv);
return base64_encode($iv . $ct);
}
/**
* Decrypts data encrypted with AES-256-CBC.
*
* @param string $encryptedData Base64-encoded data containing IV and ciphertext.
* @param string $encryptionKey The encryption key.
* @return string|false The decrypted plaintext or false on failure.
*/
function decryptData($encryptedData, $encryptionKey)
{
$cipher = 'AES-256-CBC';
$data = base64_decode($encryptedData);
$ivlen = openssl_cipher_iv_length($cipher);
$iv = substr($data, 0, $ivlen);
$ciphertext = substr($data, $ivlen);
return openssl_decrypt($ciphertext, $cipher, $encryptionKey, OPENSSL_RAW_DATA, $iv);
$data = base64_decode($encryptedData);
$ivlen = openssl_cipher_iv_length($cipher);
$iv = substr($data, 0, $ivlen);
$ct = substr($data, $ivlen);
return openssl_decrypt($ct, $cipher, $encryptionKey, OPENSSL_RAW_DATA, $iv);
}
// Load encryption key from environment (override in production).
// Load encryption key
$envKey = getenv('PERSISTENT_TOKENS_KEY');
if ($envKey === false || $envKey === '') {
$encryptionKey = 'default_please_change_this_key';
@@ -76,97 +64,89 @@ if ($envKey === false || $envKey === '') {
$encryptionKey = $envKey;
}
// Helper to load JSON permissions (with optional decryption)
function loadUserPermissions($username)
{
global $encryptionKey;
$permissionsFile = USERS_DIR . 'userPermissions.json';
if (file_exists($permissionsFile)) {
$content = file_get_contents($permissionsFile);
// Try to decrypt the content.
$decryptedContent = decryptData($content, $encryptionKey);
if ($decryptedContent !== false) {
$permissions = json_decode($decryptedContent, true);
} else {
$permissions = json_decode($content, true);
}
if (is_array($permissions) && array_key_exists($username, $permissions)) {
$result = $permissions[$username];
return !empty($result) ? $result : false;
$decrypted = decryptData($content, $encryptionKey);
$json = ($decrypted !== false) ? $decrypted : $content;
$perms = json_decode($json, true);
if (is_array($perms) && isset($perms[$username])) {
return !empty($perms[$username]) ? $perms[$username] : false;
}
}
// Removed error_log() to prevent flooding logs when file is not found.
return false; // Return false if no permissions found.
return false;
}
// Determine whether HTTPS is used.
// Determine HTTPS usage
$envSecure = getenv('SECURE');
if ($envSecure !== false) {
$secure = filter_var($envSecure, FILTER_VALIDATE_BOOLEAN);
} else {
$secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
}
$secure = ($envSecure !== false)
? filter_var($envSecure, FILTER_VALIDATE_BOOLEAN)
: (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
$cookieParams = [
'lifetime' => 7200,
// Choose session lifetime based on "remember me" cookie
$defaultSession = 7200; // 2 hours
$persistentDays = 30 * 24 * 60 * 60; // 30 days
$sessionLifetime = isset($_COOKIE['remember_me_token'])
? $persistentDays
: $defaultSession;
// Configure PHP session cookie and GC
session_set_cookie_params([
'lifetime' => $sessionLifetime,
'path' => '/',
'domain' => '', // Set your domain as needed.
'domain' => '', // adjust if you need a specific domain
'secure' => $secure,
'httponly' => true,
'samesite' => 'Lax'
];
// At the very beginning of config.php
/*ini_set('session.save_path', __DIR__ . '/../sessions');
if (!is_dir(__DIR__ . '/../sessions')) {
mkdir(__DIR__ . '/../sessions', 0777, true);
}*/
]);
ini_set('session.gc_maxlifetime', (string)$sessionLifetime);
if (session_status() === PHP_SESSION_NONE) {
session_set_cookie_params($cookieParams);
ini_set('session.gc_maxlifetime', 7200);
session_start();
}
// CSRF token
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
// Auto-login via persistent token.
if (!isset($_SESSION["authenticated"]) && isset($_COOKIE['remember_me_token'])) {
$persistentTokensFile = USERS_DIR . 'persistent_tokens.json';
$persistentTokens = [];
if (file_exists($persistentTokensFile)) {
$encryptedContent = file_get_contents($persistentTokensFile);
$decryptedContent = decryptData($encryptedContent, $encryptionKey);
$persistentTokens = json_decode($decryptedContent, true);
if (!is_array($persistentTokens)) {
$persistentTokens = [];
}
// Autologin via persistent token
if (empty($_SESSION["authenticated"]) && !empty($_COOKIE['remember_me_token'])) {
$tokFile = USERS_DIR . 'persistent_tokens.json';
$tokens = [];
if (file_exists($tokFile)) {
$enc = file_get_contents($tokFile);
$dec = decryptData($enc, $encryptionKey);
$tokens = json_decode($dec, true) ?: [];
}
if (isset($persistentTokens[$_COOKIE['remember_me_token']])) {
$tokenData = $persistentTokens[$_COOKIE['remember_me_token']];
if ($tokenData['expiry'] >= time()) {
$token = $_COOKIE['remember_me_token'];
if (!empty($tokens[$token])) {
$data = $tokens[$token];
if ($data['expiry'] >= time()) {
$_SESSION["authenticated"] = true;
$_SESSION["username"] = $tokenData["username"];
// IMPORTANT: Set the folderOnly flag here for auto-login.
$_SESSION["folderOnly"] = loadUserPermissions($tokenData["username"]);
$_SESSION["username"] = $data["username"];
$_SESSION["folderOnly"] = loadUserPermissions($data["username"]);
$_SESSION["isAdmin"] = !empty($data["isAdmin"]);
} else {
unset($persistentTokens[$_COOKIE['remember_me_token']]);
$newEncryptedContent = encryptData(json_encode($persistentTokens, JSON_PRETTY_PRINT), $encryptionKey);
file_put_contents($persistentTokensFile, $newEncryptedContent, LOCK_EX);
// expired — clean up
unset($tokens[$token]);
file_put_contents($tokFile, encryptData(json_encode($tokens, JSON_PRETTY_PRINT), $encryptionKey), LOCK_EX);
setcookie('remember_me_token', '', time() - 3600, '/', '', $secure, true);
}
}
}
// Share URL fallback
define('BASE_URL', 'http://yourwebsite/uploads/');
if (strpos(BASE_URL, 'yourwebsite') !== false) {
$defaultShareUrl = isset($_SERVER['HTTP_HOST'])
? "http://" . $_SERVER['HTTP_HOST'] . "/api/file/share.php"
$defaultShare = isset($_SERVER['HTTP_HOST'])
? "http://{$_SERVER['HTTP_HOST']}/api/file/share.php"
: "http://localhost/api/file/share.php";
} else {
$defaultShareUrl = rtrim(BASE_URL, '/') . "/api/file/share.php";
$defaultShare = rtrim(BASE_URL, '/') . "/api/file/share.php";
}
define('SHARE_URL', getenv('SHARE_URL') ? getenv('SHARE_URL') : $defaultShareUrl);
define('SHARE_URL', getenv('SHARE_URL') ?: $defaultShare);

20
public/api.html Normal file
View File

@@ -0,0 +1,20 @@
<!-- public/api.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>FileRise API Docs</title>
<script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js" integrity="sha384-4vOjrBu7SuDWXcAw1qFznVLA/sKL+0l4nn+J1HY8w7cpa6twQEYuh4b0Cwuo7CyX" crossorigin="anonymous"></script>
</head>
<body>
<redoc spec-url="openapi.json"></redoc>
<div id="redoc-container"></div>
<script>
// If the <redoc> tag didnt render, fall back to init()
if (!customElements.get('redoc')) {
Redoc.init('openapi.json', {}, document.getElementById('redoc-container'));
}
</script>
</body>
</html>

View File

@@ -95,7 +95,7 @@ function updateLoginOptionsUIFromStorage() {
}
export function loadAdminConfigFunc() {
return fetch("api/admin/getConfig.php", { credentials: "include" })
return fetch("/api/admin/getConfig.php", { credentials: "include" })
.then(response => response.json())
.then(config => {
localStorage.setItem("headerTitle", config.header_title || "FileRise");
@@ -149,9 +149,9 @@ function updateAuthenticatedUI(data) {
if (data.username) {
localStorage.setItem("username", data.username);
}
if (typeof data.folderOnly !== "undefined") {
localStorage.setItem("folderOnly", data.folderOnly ? "true" : "false");
localStorage.setItem("readOnly", data.readOnly ? "true" : "false");
if (typeof data.folderOnly !== "undefined") {
localStorage.setItem("folderOnly", data.folderOnly ? "true" : "false");
localStorage.setItem("readOnly", data.readOnly ? "true" : "false");
localStorage.setItem("disableUpload", data.disableUpload ? "true" : "false");
}
@@ -214,7 +214,7 @@ function updateAuthenticatedUI(data) {
}
function checkAuthentication(showLoginToast = true) {
return sendRequest("api/auth/checkAuth.php")
return sendRequest("/api/auth/checkAuth.php")
.then(data => {
if (data.setup) {
window.setupMode = true;
@@ -228,9 +228,9 @@ function checkAuthentication(showLoginToast = true) {
}
window.setupMode = false;
if (data.authenticated) {
localStorage.setItem("folderOnly", data.folderOnly );
localStorage.setItem("readOnly", data.readOnly );
localStorage.setItem("disableUpload",data.disableUpload);
localStorage.setItem("folderOnly", data.folderOnly);
localStorage.setItem("readOnly", data.readOnly);
localStorage.setItem("disableUpload", data.disableUpload);
updateLoginOptionsUIFromStorage();
if (typeof data.totp_enabled !== "undefined") {
localStorage.setItem("userTOTPEnabled", data.totp_enabled ? "true" : "false");
@@ -251,55 +251,71 @@ function checkAuthentication(showLoginToast = true) {
}
/* ----------------- Authentication Submission ----------------- */
function submitLogin(data) {
async function submitLogin(data) {
setLastLoginData(data);
window.__lastLoginData = data;
sendRequest("api/auth/auth.php", "POST", data, { "X-CSRF-Token": window.csrfToken })
.then(response => {
if (response.success || response.status === "ok") {
sessionStorage.setItem("welcomeMessage", "Welcome back, " + data.username + "!");
// Fetch and update permissions, then reload.
sendRequest("api/getUserPermissions.php", "GET")
.then(permissionData => {
if (permissionData && typeof permissionData === "object") {
localStorage.setItem("folderOnly", permissionData.folderOnly ? "true" : "false");
localStorage.setItem("readOnly", permissionData.readOnly ? "true" : "false");
localStorage.setItem("disableUpload", permissionData.disableUpload ? "true" : "false");
}
})
.catch(() => {
// ignore permissionfetch errors
})
.finally(() => {
window.location.reload();
});
} else if (response.totp_required) {
openTOTPLoginModal();
} else if (response.error && response.error.includes("Too many failed login attempts")) {
showToast(response.error);
const loginButton = document.querySelector("#authForm button[type='submit']");
if (loginButton) {
loginButton.disabled = true;
setTimeout(() => {
loginButton.disabled = false;
showToast("You can now try logging in again.");
}, 30 * 60 * 1000);
try {
// ─── 1) Get CSRF for the initial auth call ───
let res = await fetch("/api/auth/token.php", { credentials: "include" });
if (!res.ok) throw new Error("Could not fetch CSRF token");
window.csrfToken = (await res.json()).csrf_token;
// ─── 2) Send credentials ───
const response = await sendRequest(
"/api/auth/auth.php",
"POST",
data,
{ "X-CSRF-Token": window.csrfToken }
);
// ─── 3a) Full login (no TOTP) ───
if (response.success || response.status === "ok") {
sessionStorage.setItem("welcomeMessage", "Welcome back, " + data.username + "!");
// … fetch permissions & reload …
try {
const perm = await sendRequest("/api/getUserPermissions.php", "GET");
if (perm && typeof perm === "object") {
localStorage.setItem("folderOnly", perm.folderOnly ? "true" : "false");
localStorage.setItem("readOnly", perm.readOnly ? "true" : "false");
localStorage.setItem("disableUpload",perm.disableUpload? "true" : "false");
}
} else {
showToast("Login failed: " + (response.error || "Unknown error"));
} catch {}
return window.location.reload();
}
// ─── 3b) TOTP required ───
if (response.totp_required) {
// **Refresh** CSRF before the TOTP verify call
res = await fetch("/api/auth/token.php", { credentials: "include" });
if (res.ok) {
window.csrfToken = (await res.json()).csrf_token;
}
})
.catch(err => {
// err may be an Error object or a string
let msg = "Unknown error";
if (err && typeof err === "object") {
msg = err.error || err.message || msg;
} else if (typeof err === "string") {
msg = err;
// now open the modal—any totp_verify fetch from here on will use the new token
return openTOTPLoginModal();
}
// ─── 3c) Too many attempts ───
if (response.error && response.error.includes("Too many failed login attempts")) {
showToast(response.error);
const btn = document.querySelector("#authForm button[type='submit']");
if (btn) {
btn.disabled = true;
setTimeout(() => {
btn.disabled = false;
showToast("You can now try logging in again.");
}, 30 * 60 * 1000);
}
showToast(`Login failed: ${msg}`);
});
return;
}
// ─── 3d) Other failures ───
showToast("Login failed: " + (response.error || "Unknown error"));
} catch (err) {
const msg = err.message || err.error || "Unknown error";
showToast(`Login failed: ${msg}`);
}
}
window.submitLogin = submitLogin;
@@ -327,7 +343,7 @@ function closeRemoveUserModal() {
function loadUserList() {
// Updated path: from "getUsers.php" to "api/getUsers.php"
fetch("api/getUsers.php", { credentials: "include" })
fetch("/api/getUsers.php", { credentials: "include" })
.then(response => response.json())
.then(data => {
// Assuming the endpoint returns an array of users.
@@ -368,7 +384,7 @@ function initAuth() {
});
}
document.getElementById("logoutBtn").addEventListener("click", function () {
fetch("api/auth/logout.php", {
fetch("/api/auth/logout.php", {
method: "POST",
credentials: "include",
headers: { "X-CSRF-Token": window.csrfToken }
@@ -387,7 +403,7 @@ function initAuth() {
showToast("Username and password are required!");
return;
}
let url = "api/addUser.php";
let url = "/api/addUser.php";
if (window.setupMode) url += "?setup=1";
fetch(url, {
method: "POST",
@@ -422,7 +438,7 @@ function initAuth() {
}
const confirmed = await showCustomConfirmModal("Are you sure you want to delete user " + usernameToRemove + "?");
if (!confirmed) return;
fetch("api/removeUser.php", {
fetch("/api/removeUser.php", {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json", "X-CSRF-Token": window.csrfToken },
@@ -461,7 +477,7 @@ function initAuth() {
return;
}
const data = { oldPassword, newPassword, confirmPassword };
fetch("api/changePassword.php", {
fetch("/api/changePassword.php", {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json", "X-CSRF-Token": window.csrfToken },

View File

@@ -3,8 +3,7 @@ import { sendRequest } from './networkUtils.js';
import { t, applyTranslations, setLocale } from './i18n.js';
import { loadAdminConfigFunc } from './auth.js';
const version = "v1.2.0";
// Use t() for the admin panel title. (Make sure t("admin_panel") returns "Admin Panel" in English.)
const version = "v1.2.1"; // Update this version string as needed
const adminTitle = `${t("admin_panel")} <small style="font-size: 12px; color: gray;">${version}</small>`;
let lastLoginData = null;
@@ -84,7 +83,7 @@ export function openTOTPLoginModal() {
showToast(t("please_enter_recovery_code"));
return;
}
fetch("api/totp_recover.php", {
fetch("/api/totp_recover.php", {
method: "POST",
credentials: "include",
headers: {
@@ -110,36 +109,47 @@ export function openTOTPLoginModal() {
// TOTP submission
const totpInput = document.getElementById("totpLoginInput");
totpInput.focus();
totpInput.addEventListener("input", function () {
totpInput.addEventListener("input", async function () {
const code = this.value.trim();
if (code.length === 6) {
fetch("api/totp_verify.php", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": window.csrfToken
},
body: JSON.stringify({ totp_code: code })
})
.then(res => res.json())
.then(json => {
if (json.status === "ok") {
window.location.href = "/index.html";
} else {
showToast(json.message || t("totp_verification_failed"));
this.value = "";
totpLoginModal.style.display = "flex";
totpInput.focus();
}
})
.catch(() => {
showToast(t("totp_verification_failed"));
this.value = "";
totpLoginModal.style.display = "flex";
totpInput.focus();
});
if (code.length !== 6) {
return;
}
const tokenRes = await fetch("/api/auth/token.php", {
credentials: "include"
});
if (!tokenRes.ok) {
showToast(t("totp_verification_failed"));
return;
}
window.csrfToken = (await tokenRes.json()).csrf_token;
const res = await fetch("/api/totp_verify.php", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": window.csrfToken
},
body: JSON.stringify({ totp_code: code })
});
if (res.ok) {
const json = await res.json();
if (json.status === "ok") {
window.location.href = "/index.html";
return;
}
showToast(json.message || t("totp_verification_failed"));
} else {
showToast(t("totp_verification_failed"));
}
this.value = "";
totpLoginModal.style.display = "flex";
this.focus();
});
} else {
// Re-open existing modal
@@ -166,105 +176,112 @@ export function openUserPanel() {
border-radius: 8px;
position: fixed;
overflow-y: auto;
max-height: 350px !important;
max-height: 400px !important;
border: ${isDarkMode ? "1px solid #444" : "1px solid #ccc"};
transform: none;
transition: none;
`;
// Retrieve the language setting from local storage, default to English ("en")
const savedLanguage = localStorage.getItem("language") || "en";
if (!userPanelModal) {
userPanelModal = document.createElement("div");
userPanelModal.id = "userPanelModal";
userPanelModal.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: ${overlayBackground};
display: flex;
justify-content: center;
align-items: center;
z-index: 3000;
`;
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: ${overlayBackground};
display: flex;
justify-content: center;
align-items: center;
z-index: 3000;
`;
userPanelModal.innerHTML = `
<div class="modal-content user-panel-content" style="${modalContentStyles}">
<span id="closeUserPanel" style="position: absolute; top: 10px; right: 10px; cursor: pointer; font-size: 24px;">&times;</span>
<h3>${t("user_panel")} (${username})</h3>
<button type="button" id="openChangePasswordModalBtn" class="btn btn-primary" style="margin-bottom: 15px;">${t("change_password")}</button>
<fieldset style="margin-bottom: 15px;">
<legend>${t("totp_settings")}</legend>
<div class="form-group">
<label for="userTOTPEnabled">${t("enable_totp")}:</label>
<input type="checkbox" id="userTOTPEnabled" style="vertical-align: middle;" />
</div>
</fieldset>
<fieldset style="margin-bottom: 15px;">
<legend>${t("language")}</legend>
<div class="form-group">
<label for="languageSelector">${t("select_language")}:</label>
<select id="languageSelector">
<option value="en">${t("english")}</option>
<option value="es">${t("spanish")}</option>
<option value="fr">${t("french")}</option>
<option value="de">${t("german")}</option>
</select>
</div>
</fieldset>
<div class="modal-content user-panel-content" style="${modalContentStyles}">
<span id="closeUserPanel" style="position: absolute; top: 10px; right: 10px; cursor: pointer; font-size: 24px;">&times;</span>
<h3>${t("user_panel")} (${username})</h3>
<button type="button" id="openChangePasswordModalBtn" class="btn btn-primary" style="margin-bottom: 15px;">
${t("change_password")}
</button>
<fieldset style="margin-bottom: 15px;">
<legend>${t("totp_settings")}</legend>
<div class="form-group">
<label for="userTOTPEnabled">${t("enable_totp")}:</label>
<input type="checkbox" id="userTOTPEnabled" style="vertical-align: middle;" />
</div>
</fieldset>
<fieldset style="margin-bottom: 15px;">
<legend>${t("language")}</legend>
<div class="form-group">
<label for="languageSelector">${t("select_language")}:</label>
<select id="languageSelector">
<option value="en">${t("english")}</option>
<option value="es">${t("spanish")}</option>
<option value="fr">${t("french")}</option>
<option value="de">${t("german")}</option>
</select>
</div>
</fieldset>
<!-- New API Docs link -->
<div style="margin-bottom: 15px;">
<a href="api.html" target="_blank" class="btn btn-secondary">
${t("api_docs") || "API Docs"}
</a>
</div>
`;
</div>
`;
document.body.appendChild(userPanelModal);
// Close button handler
// Handlers…
document.getElementById("closeUserPanel").addEventListener("click", () => {
userPanelModal.style.display = "none";
});
// Change Password button
document.getElementById("openChangePasswordModalBtn").addEventListener("click", () => {
document.getElementById("changePasswordModal").style.display = "block";
});
// TOTP checkbox behavior
// TOTP checkbox
const totpCheckbox = document.getElementById("userTOTPEnabled");
totpCheckbox.checked = localStorage.getItem("userTOTPEnabled") === "true";
totpCheckbox.addEventListener("change", function () {
localStorage.setItem("userTOTPEnabled", this.checked ? "true" : "false");
const enabled = this.checked;
fetch("api/updateUserPanel.php", {
fetch("/api/updateUserPanel.php", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": window.csrfToken
},
body: JSON.stringify({ totp_enabled: enabled })
headers: { "Content-Type": "application/json", "X-CSRF-Token": window.csrfToken },
body: JSON.stringify({ totp_enabled: this.checked })
})
.then(r => r.json())
.then(result => {
if (!result.success) {
showToast(t("error_updating_totp_setting") + ": " + result.error);
} else if (enabled) {
openTOTPModal();
}
if (!result.success) showToast(t("error_updating_totp_setting") + ": " + result.error);
else if (this.checked) openTOTPModal();
})
.catch(() => { showToast(t("error_updating_totp_setting")); });
.catch(() => showToast(t("error_updating_totp_setting")));
});
// Language dropdown initialization
// Language selector
const languageSelector = document.getElementById("languageSelector");
languageSelector.value = savedLanguage;
languageSelector.addEventListener("change", function () {
const selectedLanguage = this.value;
localStorage.setItem("language", selectedLanguage);
setLocale(selectedLanguage);
localStorage.setItem("language", this.value);
setLocale(this.value);
applyTranslations();
});
} else {
// If the modal already exists, update its colors
// Update colors if already exists
userPanelModal.style.backgroundColor = overlayBackground;
const modalContent = userPanelModal.querySelector(".modal-content");
modalContent.style.background = isDarkMode ? "#2c2c2c" : "#fff";
modalContent.style.color = isDarkMode ? "#e0e0e0" : "#000";
modalContent.style.border = isDarkMode ? "1px solid #444" : "1px solid #ccc";
}
userPanelModal.style.display = "flex";
}
@@ -347,13 +364,24 @@ export function openTOTPModal() {
closeTOTPModal(true);
});
document.getElementById("confirmTOTPBtn").addEventListener("click", function () {
document.getElementById("confirmTOTPBtn").addEventListener("click", async function () {
const code = document.getElementById("totpConfirmInput").value.trim();
if (code.length !== 6) {
showToast(t("please_enter_valid_code"));
return;
}
fetch("api/totp_verify.php", {
const tokenRes = await fetch("/api/auth/token.php", {
credentials: "include"
});
if (!tokenRes.ok) {
showToast(t("error_verifying_totp_code"));
return;
}
const { csrf_token } = await tokenRes.json();
window.csrfToken = csrf_token;
const verifyRes = await fetch("/api/totp_verify.php", {
method: "POST",
credentials: "include",
headers: {
@@ -361,36 +389,40 @@ export function openTOTPModal() {
"X-CSRF-Token": window.csrfToken
},
body: JSON.stringify({ totp_code: code })
})
.then(r => r.json())
.then(result => {
if (result.status === 'ok') {
showToast(t("totp_enabled_successfully"));
// After successful TOTP verification, fetch the recovery code
fetch("api/totp_saveCode.php", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": window.csrfToken
}
})
.then(r => r.json())
.then(data => {
if (data.status === 'ok' && data.recoveryCode) {
// Show the recovery code in a secure modal
showRecoveryCodeModal(data.recoveryCode);
} else {
showToast(t("error_generating_recovery_code") + ": " + (data.message || t("unknown_error")));
}
})
.catch(() => { showToast(t("error_generating_recovery_code")); });
closeTOTPModal(false);
} else {
showToast(t("totp_verification_failed") + ": " + (result.message || t("invalid_code")));
}
})
.catch(() => { showToast(t("error_verifying_totp_code")); });
});
if (!verifyRes.ok) {
showToast(t("totp_verification_failed"));
return;
}
const result = await verifyRes.json();
if (result.status !== "ok") {
showToast(result.message || t("totp_verification_failed"));
return;
}
showToast(t("totp_enabled_successfully"));
const saveRes = await fetch("/api/totp_saveCode.php", {
method: "POST",
credentials: "include",
headers: {
"X-CSRF-Token": window.csrfToken
}
});
if (!saveRes.ok) {
showToast(t("error_generating_recovery_code"));
closeTOTPModal(false);
return;
}
const data = await saveRes.json();
if (data.status === "ok" && data.recoveryCode) {
showRecoveryCodeModal(data.recoveryCode);
} else {
showToast(t("error_generating_recovery_code") + ": " + (data.message || t("unknown_error")));
}
closeTOTPModal(false);
});
// Focus the input and attach enter key listener
@@ -431,7 +463,7 @@ export function openTOTPModal() {
}
function loadTOTPQRCode() {
fetch("api/totp_setup.php", {
fetch("/api/totp_setup.php", {
method: "GET",
credentials: "include",
headers: {
@@ -470,7 +502,7 @@ export function closeTOTPModal(disable = true) {
localStorage.setItem("userTOTPEnabled", "false");
}
// Call endpoint to remove the TOTP secret from the user's record
fetch("api/totp_disable.php", {
fetch("/api/totp_disable.php", {
method: "POST",
credentials: "include",
headers: {
@@ -556,7 +588,7 @@ function showCustomConfirmModal(message) {
}
export function openAdminPanel() {
fetch("api/admin/getConfig.php", { credentials: "include" })
fetch("/api/admin/getConfig.php", { credentials: "include" })
.then(response => response.json())
.then(config => {
if (config.header_title) {
@@ -718,7 +750,7 @@ export function openAdminPanel() {
const disableBasicAuth = disableBasicAuthCheckbox.checked;
const disableOIDCLogin = disableOIDCLoginCheckbox.checked;
const globalOtpauthUrl = document.getElementById("globalOtpauthUrl").value.trim();
sendRequest("api/admin/updateConfig.php", "POST", {
sendRequest("/api/admin/updateConfig.php", "POST", {
header_title: newHeaderTitle,
oidc: newOIDCConfig,
disableFormLogin,
@@ -891,7 +923,7 @@ export function openUserPermissionsModal() {
});
});
// Send the permissionsData to the server.
sendRequest("api/updateUserPermissions.php", "POST", { permissions: permissionsData }, { "X-CSRF-Token": window.csrfToken })
sendRequest("/api/updateUserPermissions.php", "POST", { permissions: permissionsData }, { "X-CSRF-Token": window.csrfToken })
.then(response => {
if (response.success) {
showToast(t("user_permissions_updated_successfully"));
@@ -917,11 +949,11 @@ function loadUserPermissionsList() {
listContainer.innerHTML = "";
// First, fetch the current permissions from the server.
fetch("api/getUserPermissions.php", { credentials: "include" })
fetch("/api/getUserPermissions.php", { credentials: "include" })
.then(response => response.json())
.then(permissionsData => {
// Then, fetch the list of users.
return fetch("api/getUsers.php", { credentials: "include" })
return fetch("/api/getUsers.php", { credentials: "include" })
.then(response => response.json())
.then(usersData => {
const users = Array.isArray(usersData) ? usersData : (usersData.users || []);

View File

@@ -32,7 +32,7 @@ document.addEventListener("DOMContentLoaded", function () {
const confirmDelete = document.getElementById("confirmDeleteFiles");
if (confirmDelete) {
confirmDelete.addEventListener("click", function () {
fetch("api/file/deleteFiles.php", {
fetch("/api/file/deleteFiles.php", {
method: "POST",
credentials: "include",
headers: {
@@ -178,7 +178,7 @@ export function handleExtractZipSelected(e) {
// Show the progress modal.
document.getElementById("downloadProgressModal").style.display = "block";
fetch("api/file/extractZip.php", {
fetch("/api/file/extractZip.php", {
method: "POST",
credentials: "include",
headers: {
@@ -245,7 +245,7 @@ document.addEventListener("DOMContentLoaded", function () {
console.log("Download confirmed. Showing progress modal.");
document.getElementById("downloadProgressModal").style.display = "block";
const folder = window.currentFolder || "root";
fetch("api/file/downloadZip.php", {
fetch("/api/file/downloadZip.php", {
method: "POST",
credentials: "include",
headers: {
@@ -309,7 +309,7 @@ export async function loadCopyMoveFolderListForModal(dropdownId) {
if (window.userFolderOnly) {
const username = localStorage.getItem("username") || "root";
try {
const response = await fetch("api/folder/getFolderList.php?restricted=1");
const response = await fetch("/api/folder/getFolderList.php?restricted=1");
let folders = await response.json();
if (Array.isArray(folders) && folders.length && typeof folders[0] === "object" && folders[0].folder) {
folders = folders.map(item => item.folder);
@@ -339,7 +339,7 @@ export async function loadCopyMoveFolderListForModal(dropdownId) {
}
try {
const response = await fetch("api/folder/getFolderList.php");
const response = await fetch("/api/folder/getFolderList.php");
let folders = await response.json();
if (Array.isArray(folders) && folders.length && typeof folders[0] === "object" && folders[0].folder) {
folders = folders.map(item => item.folder);
@@ -397,7 +397,7 @@ document.addEventListener("DOMContentLoaded", function () {
showToast("Error: Cannot copy files to the same folder.");
return;
}
fetch("api/file/copyFiles.php", {
fetch("/api/file/copyFiles.php", {
method: "POST",
credentials: "include",
headers: {
@@ -448,7 +448,7 @@ document.addEventListener("DOMContentLoaded", function () {
showToast("Error: Cannot move files to the same folder.");
return;
}
fetch("api/file/moveFiles.php", {
fetch("/api/file/moveFiles.php", {
method: "POST",
credentials: "include",
headers: {
@@ -514,7 +514,7 @@ document.addEventListener("DOMContentLoaded", () => {
return;
}
const folderUsed = window.fileFolder;
fetch("api/file/renameFile.php", {
fetch("/api/file/renameFile.php", {
method: "POST",
credentials: "include",
headers: {

View File

@@ -96,7 +96,7 @@ export function folderDropHandler(event) {
return;
}
if (!dragData || !dragData.fileName) return;
fetch("api/file/moveFiles.php", {
fetch("/api/file/moveFiles.php", {
method: "POST",
credentials: "include",
headers: {

View File

@@ -160,7 +160,7 @@ export function saveFile(fileName, folder) {
content: editor.getValue(),
folder: folderUsed
};
fetch("api/file/saveFile.php", {
fetch("/api/file/saveFile.php", {
method: "POST",
credentials: "include",
headers: {

View File

@@ -20,9 +20,12 @@ import { openTagModal, openMultiTagModal } from './fileTags.js';
export let fileData = [];
export let sortOrder = { column: "uploaded", ascending: true };
window.itemsPerPage = window.itemsPerPage || 10;
window.itemsPerPage = parseInt(
localStorage.getItem('itemsPerPage') || window.itemsPerPage || '10',
10
);
window.currentPage = window.currentPage || 1;
window.viewMode = localStorage.getItem("viewMode") || "table"; // "table" or "gallery"
window.viewMode = localStorage.getItem("viewMode") || "table";
// Global flag for advanced search mode.
window.advancedSearchEnabled = false;
@@ -193,7 +196,7 @@ export function loadFileList(folderParam) {
fileListContainer.style.visibility = "hidden";
fileListContainer.innerHTML = "<div class='loader'>Loading files...</div>";
return fetch("api/file/getFileList.php?folder=" + encodeURIComponent(folder) + "&recursive=1&t=" + new Date().getTime())
return fetch("/api/file/getFileList.php?folder=" + encodeURIComponent(folder) + "&recursive=1&t=" + new Date().getTime())
.then(response => {
if (response.status === 401) {
showToast("Session expired. Please log in again.");
@@ -407,33 +410,89 @@ export function renderGalleryView(folder, container) {
? "uploads/"
: "uploads/" + folder.split("/").map(encodeURIComponent).join("/") + "/";
// Use the current global column value (default to 3).
const numColumns = window.galleryColumns || 3;
// pagination settings
const itemsPerPage = window.itemsPerPage;
let currentPage = window.currentPage || 1;
const totalFiles = filteredFiles.length;
const totalPages = Math.ceil(totalFiles / itemsPerPage);
if (currentPage > totalPages) {
currentPage = totalPages || 1;
window.currentPage = currentPage;
}
// --- Insert slider controls ---
const sliderHTML = `
<div class="gallery-slider" style="margin: 10px; text-align: center;">
<label for="galleryColumnsSlider" style="margin-right: 5px;">${t('columns')}:</label>
<input type="range" id="galleryColumnsSlider" min="1" max="6" value="${numColumns}" style="vertical-align: middle;">
// --- Top controls: search + pagination + items-per-page ---
let galleryHTML = buildSearchAndPaginationControls({
currentPage,
totalPages,
searchTerm: window.currentSearchTerm || ""
});
// wire up search input just like table view
setTimeout(() => {
const searchInput = document.getElementById("searchInput");
if (searchInput) {
searchInput.addEventListener("input", debounce(() => {
window.currentSearchTerm = searchInput.value;
window.currentPage = 1;
renderGalleryView(folder);
// keep caret at end
setTimeout(() => {
const f = document.getElementById("searchInput");
if (f) {
f.focus();
const len = f.value.length;
f.setSelectionRange(len, len);
}
}, 0);
}, 300));
}
}, 0);
// --- Column slider ---
const numColumns = window.galleryColumns || 3;
galleryHTML += `
<div class="gallery-slider" style="margin:10px; text-align:center;">
<label for="galleryColumnsSlider" style="margin-right:5px;">
${t('columns')}:
</label>
<input type="range" id="galleryColumnsSlider" min="1" max="6"
value="${numColumns}" style="vertical-align:middle;">
<span id="galleryColumnsValue">${numColumns}</span>
</div>
`;
// Set up the grid container using the slider's current value.
const gridStyle = `display: grid; grid-template-columns: repeat(${numColumns}, 1fr); gap: 10px; padding: 10px;`;
// --- Start gallery grid ---
galleryHTML += `
<div class="gallery-container"
style="display:grid;
grid-template-columns:repeat(${numColumns},1fr);
gap:10px;
padding:10px;">
`;
// Build the gallery container HTML including the slider.
let galleryHTML = sliderHTML;
galleryHTML += `<div class="gallery-container" style="${gridStyle}">`;
filteredFiles.forEach((file) => {
// slice current page
const startIdx = (currentPage - 1) * itemsPerPage;
const pageFiles = filteredFiles.slice(startIdx, startIdx + itemsPerPage);
pageFiles.forEach((file, idx) => {
const idSafe = encodeURIComponent(file.name) + "-" + (startIdx + idx);
// thumbnail
let thumbnail;
if (/\.(jpg|jpeg|png|gif|bmp|webp|svg|ico)$/i.test(file.name)) {
if (/\.(jpe?g|png|gif|bmp|webp|svg|ico)$/i.test(file.name)) {
const cacheKey = folderPath + encodeURIComponent(file.name);
if (window.imageCache && window.imageCache[cacheKey]) {
thumbnail = `<img src="${window.imageCache[cacheKey]}" class="gallery-thumbnail" alt="${escapeHTML(file.name)}" style="max-width: 100%; max-height: ${getMaxImageHeight()}px; display: block; margin: 0 auto;">`;
thumbnail = `<img src="${window.imageCache[cacheKey]}"
class="gallery-thumbnail"
alt="${escapeHTML(file.name)}"
style="max-width:100%; max-height:${getMaxImageHeight()}px; display:block; margin:0 auto;">`;
} else {
const imageUrl = folderPath + encodeURIComponent(file.name) + "?t=" + new Date().getTime();
thumbnail = `<img src="${imageUrl}" onload="cacheImage(this, '${cacheKey}')" class="gallery-thumbnail" alt="${escapeHTML(file.name)}" style="max-width: 100%; max-height: ${getMaxImageHeight()}px; display: block; margin: 0 auto;">`;
const imageUrl = folderPath + encodeURIComponent(file.name) + "?t=" + Date.now();
thumbnail = `<img src="${imageUrl}"
onload="cacheImage(this,'${cacheKey}')"
class="gallery-thumbnail"
alt="${escapeHTML(file.name)}"
style="max-width:100%; max-height:${getMaxImageHeight()}px; display:block; margin:0 auto;">`;
}
} else if (/\.(mp3|wav|m4a|ogg|flac|aac|wma|opus)$/i.test(file.name)) {
thumbnail = `<span class="material-icons gallery-icon">audiotrack</span>`;
@@ -441,82 +500,127 @@ export function renderGalleryView(folder, container) {
thumbnail = `<span class="material-icons gallery-icon">insert_drive_file</span>`;
}
// tag badges
let tagBadgesHTML = "";
if (file.tags && file.tags.length > 0) {
if (file.tags && file.tags.length) {
tagBadgesHTML = `<div class="tag-badges" style="margin-top:4px;">`;
file.tags.forEach(tag => {
tagBadgesHTML += `<span style="background-color: ${tag.color}; color: #fff; padding: 2px 4px; border-radius: 3px; margin-right: 2px; font-size: 0.8em;">${escapeHTML(tag.name)}</span>`;
tagBadgesHTML += `<span style="background-color:${tag.color};
color:#fff;
padding:2px 4px;
border-radius:3px;
margin-right:2px;
font-size:0.8em;">
${escapeHTML(tag.name)}
</span>`;
});
tagBadgesHTML += `</div>`;
}
// card with checkbox, preview, info, buttons
galleryHTML += `
<div class="gallery-card" style="border: 1px solid #ccc; padding: 5px; text-align: center;">
<div class="gallery-preview" style="cursor: pointer;" onclick="previewFile('${folderPath + encodeURIComponent(file.name)}?t=' + new Date().getTime(), '${file.name}')">
<div class="gallery-card"
style="position:relative; border:1px solid #ccc; padding:5px; text-align:center;">
<input type="checkbox"
class="file-checkbox"
id="cb-${idSafe}"
value="${escapeHTML(file.name)}"
style="position:absolute; top:5px; left:5px; z-index:10;">
<label for="cb-${idSafe}"
style="position:absolute; top:5px; left:5px; width:16px; height:16px;"></label>
<div class="gallery-preview"
style="cursor:pointer;"
onclick="previewFile('${folderPath + encodeURIComponent(file.name)}?t='+Date.now(), '${file.name}')">
${thumbnail}
</div>
<div class="gallery-info" style="margin-top: 5px;">
<span class="gallery-file-name" style="display: block; white-space: normal; overflow-wrap: break-word; word-wrap: break-word;">${escapeHTML(file.name)}</span>
<div class="gallery-info" style="margin-top:5px;">
<span class="gallery-file-name"
style="display:block; white-space:normal; overflow-wrap:break-word;">
${escapeHTML(file.name)}
</span>
${tagBadgesHTML}
<div class="button-wrap" style="display: flex; justify-content: center; gap: 5px;">
<div class="button-wrap" style="display:flex; justify-content:center; gap:5px; margin-top:5px;">
<button type="button" class="btn btn-sm btn-success download-btn"
onclick="openDownloadModal('${file.name}', '${file.folder || 'root'}')"
title="${t('download')}">
<i class="material-icons">file_download</i>
onclick="openDownloadModal('${file.name}', '${file.folder || "root"}')"
title="${t('download')}">
<i class="material-icons">file_download</i>
</button>
${file.editable ? `
<button class="btn btn-sm edit-btn" onclick='editFile(${JSON.stringify(file.name)}, ${JSON.stringify(file.folder || "root")})' title="${t('Edit')}">
<i class="material-icons">edit</i>
</button>
` : ""}
<button class="btn btn-sm btn-warning rename-btn" onclick='renameFile(${JSON.stringify(file.name)}, ${JSON.stringify(file.folder || "root")})' title="${t('rename')}">
<i class="material-icons">drive_file_rename_outline</i>
<button class="btn btn-sm edit-btn"
onclick='editFile(${JSON.stringify(file.name)}, ${JSON.stringify(file.folder || "root")})'
title="${t('Edit')}">
<i class="material-icons">edit</i>
</button>` : ""}
<button class="btn btn-sm btn-warning rename-btn"
onclick='renameFile(${JSON.stringify(file.name)}, ${JSON.stringify(file.folder || "root")})'
title="${t('rename')}">
<i class="material-icons">drive_file_rename_outline</i>
</button>
<button class="btn btn-sm btn-secondary share-btn" data-file="${escapeHTML(file.name)}" title="${t('share')}">
<i class="material-icons">share</i>
<button class="btn btn-sm btn-secondary share-btn"
data-file="${escapeHTML(file.name)}"
title="${t('share')}">
<i class="material-icons">share</i>
</button>
</div>
</div>
</div>`;
});
galleryHTML += "</div>"; // End gallery container.
</div>
</div>
`;
});
galleryHTML += `</div>`; // end gallery-container
// bottom controls
galleryHTML += buildBottomControls(itemsPerPage);
// render
fileListContent.innerHTML = galleryHTML;
// Re-apply slider constraints for the newly rendered slider.
updateSliderConstraints();
// ensure toggle button
createViewToggleButton();
// Attach share button event listeners.
document.querySelectorAll(".share-btn").forEach(btn => {
btn.addEventListener("click", e => {
e.stopPropagation();
const fileName = btn.getAttribute("data-file");
const file = fileData.find(f => f.name === fileName);
if (file) {
import('./filePreview.js').then(module => {
module.openShareModal(file, folder);
});
}
});
// attach listeners
// checkboxes
document.querySelectorAll(".file-checkbox").forEach(cb => {
cb.addEventListener("change", () => updateFileActionButtons());
});
// --- Slider Event Listener ---
// slider
const slider = document.getElementById("galleryColumnsSlider");
if (slider) {
slider.addEventListener("input", function () {
const value = this.value;
document.getElementById("galleryColumnsValue").textContent = value;
window.galleryColumns = value;
const galleryContainer = document.querySelector(".gallery-container");
if (galleryContainer) {
galleryContainer.style.gridTemplateColumns = `repeat(${value}, 1fr)`;
}
const newMaxHeight = getMaxImageHeight();
document.querySelectorAll(".gallery-thumbnail").forEach(img => {
img.style.maxHeight = newMaxHeight + "px";
});
slider.addEventListener("input", () => {
const v = +slider.value;
document.getElementById("galleryColumnsValue").textContent = v;
window.galleryColumns = v;
document.querySelector(".gallery-container")
.style.gridTemplateColumns = `repeat(${v},1fr)`;
document.querySelectorAll(".gallery-thumbnail")
.forEach(img => img.style.maxHeight = getMaxImageHeight() + "px");
});
}
// pagination
window.changePage = newPage => {
window.currentPage = newPage;
if (window.viewMode === "gallery") renderGalleryView(folder);
else renderFileTable(folder);
};
// items per page
window.changeItemsPerPage = cnt => {
window.itemsPerPage = +cnt;
localStorage.setItem("itemsPerPage", cnt);
window.currentPage = 1;
if (window.viewMode === "gallery") renderGalleryView(folder);
else renderFileTable(folder);
};
// update toolbar buttons
updateFileActionButtons();
}
// Responsive slider constraints based on screen size.
@@ -638,12 +742,22 @@ export function canEditFile(fileName) {
// Expose global functions for pagination and preview.
window.changePage = function (newPage) {
window.currentPage = newPage;
renderFileTable(window.currentFolder);
if (window.viewMode === 'gallery') {
renderGalleryView(window.currentFolder);
} else {
renderFileTable(window.currentFolder);
}
};
window.changeItemsPerPage = function (newCount) {
window.itemsPerPage = parseInt(newCount);
window.itemsPerPage = parseInt(newCount, 10);
localStorage.setItem('itemsPerPage', newCount);
window.currentPage = 1;
renderFileTable(window.currentFolder);
if (window.viewMode === 'gallery') {
renderGalleryView(window.currentFolder);
} else {
renderFileTable(window.currentFolder);
}
};
// fileListView.js (bottom)

View File

@@ -48,7 +48,7 @@ export function openShareModal(file, folder) {
document.getElementById("generateShareLinkBtn").addEventListener("click", () => {
const expiration = document.getElementById("shareExpiration").value;
const password = document.getElementById("sharePassword").value;
fetch("api/file/createShareLink.php", {
fetch("/api/file/createShareLink.php", {
method: "POST",
credentials: "include",
headers: {

View File

@@ -5,6 +5,7 @@
// filtering the file list by tag, and persisting tag data.
import { escapeHTML } from './domUtils.js';
import { t } from './i18n.js';
import { renderFileTable, renderGalleryView } from './fileListView.js';
export function openTagModal(file) {
// Create the modal element.
@@ -63,6 +64,11 @@ export function openTagModal(file) {
updateTagModalDisplay(file);
updateFileRowTagDisplay(file);
saveFileTags(file);
if (window.viewMode === 'gallery') {
renderGalleryView(window.currentFolder);
} else {
renderFileTable(window.currentFolder);
}
document.getElementById('tagNameInput').value = '';
updateCustomTagDropdown();
});
@@ -125,6 +131,11 @@ export function openMultiTagModal(files) {
saveFileTags(file);
});
modal.remove();
if (window.viewMode === 'gallery') {
renderGalleryView(window.currentFolder);
} else {
renderFileTable(window.currentFolder);
}
});
}
@@ -261,7 +272,7 @@ function removeGlobalTag(tagName) {
// NEW: Save global tag removal to the server.
function saveGlobalTagRemoval(tagName) {
fetch("api/file/saveFileTag.php", {
fetch("/api/file/saveFileTag.php", {
method: "POST",
credentials: "include",
headers: {
@@ -305,7 +316,7 @@ if (localStorage.getItem('globalTags')) {
// New function to load global tags from the server's persistent JSON.
export function loadGlobalTags() {
fetch("api/file/getFileTag.php", { credentials: "include" })
fetch("/api/file/getFileTag.php", { credentials: "include" })
.then(response => {
if (!response.ok) {
// If the file doesn't exist, assume there are no global tags.
@@ -438,7 +449,7 @@ export function saveFileTags(file, deleteGlobal = false, tagToDelete = null) {
payload.deleteGlobal = true;
payload.tagToDelete = tagToDelete;
}
fetch("api/file/saveFileTag.php", {
fetch("/api/file/saveFileTag.php", {
method: "POST",
credentials: "include",
headers: {

View File

@@ -154,7 +154,7 @@ function breadcrumbDropHandler(e) {
}
const filesToMove = dragData.files ? dragData.files : (dragData.fileName ? [dragData.fileName] : []);
if (filesToMove.length === 0) return;
fetch("api/file/moveFiles.php", {
fetch("/api/file/moveFiles.php", {
method: "POST",
credentials: "include",
headers: {
@@ -202,7 +202,7 @@ function checkUserFolderPermission() {
window.currentFolder = username;
return Promise.resolve(true);
}
return fetch("api/getUserPermissions.php", { credentials: "include" })
return fetch("/api/getUserPermissions.php", { credentials: "include" })
.then(response => response.json())
.then(permissionsData => {
console.log("checkUserFolderPermission: permissionsData =", permissionsData);
@@ -302,7 +302,7 @@ function folderDropHandler(event) {
}
const filesToMove = dragData.files ? dragData.files : (dragData.fileName ? [dragData.fileName] : []);
if (filesToMove.length === 0) return;
fetch("api/file/moveFiles.php", {
fetch("/api/file/moveFiles.php", {
method: "POST",
credentials: "include",
headers: {
@@ -353,7 +353,7 @@ export async function loadFolderTree(selectedFolder) {
}
// Build fetch URL.
let fetchUrl = 'api/folder/getFolderList.php';
let fetchUrl = '/api/folder/getFolderList.php';
if (window.userFolderOnly) {
fetchUrl += '?restricted=1';
}
@@ -547,7 +547,7 @@ document.getElementById("submitRenameFolder").addEventListener("click", function
showToast("CSRF token not loaded yet! Please try again.");
return;
}
fetch("api/folder/renameFolder.php", {
fetch("/api/folder/renameFolder.php", {
method: "POST",
credentials: "include",
headers: {
@@ -592,7 +592,7 @@ attachEnterKeyListener("deleteFolderModal", "confirmDeleteFolder");
document.getElementById("confirmDeleteFolder").addEventListener("click", function () {
const selectedFolder = window.currentFolder || "root";
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
fetch("api/folder/deleteFolder.php", {
fetch("/api/folder/deleteFolder.php", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -639,7 +639,7 @@ document.getElementById("submitCreateFolder").addEventListener("click", function
fullFolderName = selectedFolder + "/" + folderInput;
}
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
fetch("api/folder/createFolder.php", {
fetch("/api/folder/createFolder.php", {
method: "POST",
headers: {
"Content-Type": "application/json",

View File

@@ -64,7 +64,7 @@ export function openFolderShareModal(folder) {
return;
}
// Post to the createFolderShareLink endpoint.
fetch("api/folder/createShareFolderLink.php", {
fetch("/api/folder/createShareFolderLink.php", {
method: "POST",
credentials: "include",
headers: {

View File

@@ -237,7 +237,8 @@ const translations = {
"ok": "OK",
"show": "Show",
"items_per_page": "items per page",
"columns":"Columns"
"columns":"Columns",
"api_docs": "API Docs"
},
es: {
"please_log_in_to_continue": "Por favor, inicie sesión para continuar.",

View File

@@ -14,7 +14,7 @@ import { t, applyTranslations, setLocale } from './i18n.js';
// Remove the retry logic version and just use loadCsrfToken directly:
function loadCsrfToken() {
return fetch('api/auth/token.php', { credentials: 'include' })
return fetch('/api/auth/token.php', { credentials: 'include' })
.then(response => {
if (!response.ok) {
throw new Error("Token fetch failed with status: " + response.status);

View File

@@ -69,7 +69,7 @@ export function setupTrashRestoreDelete() {
showToast(t("no_trash_selected"));
return;
}
fetch("api/file/restoreFiles.php", {
fetch("/api/file/restoreFiles.php", {
method: "POST",
credentials: "include",
headers: {
@@ -109,7 +109,7 @@ export function setupTrashRestoreDelete() {
showToast(t("trash_empty"));
return;
}
fetch("api/file/restoreFiles.php", {
fetch("/api/file/restoreFiles.php", {
method: "POST",
credentials: "include",
headers: {
@@ -151,7 +151,7 @@ export function setupTrashRestoreDelete() {
return;
}
showConfirm("Are you sure you want to permanently delete the selected trash items?", () => {
fetch("api/file/deleteTrashFiles.php", {
fetch("/api/file/deleteTrashFiles.php", {
method: "POST",
credentials: "include",
headers: {
@@ -186,7 +186,7 @@ export function setupTrashRestoreDelete() {
if (deleteAllBtn) {
deleteAllBtn.addEventListener("click", () => {
showConfirm("Are you sure you want to permanently delete all trash items? This action cannot be undone.", () => {
fetch("api/file/deleteTrashFiles.php", {
fetch("/api/file/deleteTrashFiles.php", {
method: "POST",
credentials: "include",
headers: {
@@ -234,7 +234,7 @@ export function setupTrashRestoreDelete() {
* Loads trash items from the server and updates the restore modal list.
*/
export function loadTrashItems() {
fetch("api/file/getTrashItems.php", { credentials: "include" })
fetch("/api/file/getTrashItems.php", { credentials: "include" })
.then(response => response.json())
.then(trashItems => {
const listContainer = document.getElementById("restoreFilesList");
@@ -271,7 +271,7 @@ export function loadTrashItems() {
* Automatically purges (permanently deletes) trash items older than 3 days.
*/
function autoPurgeOldTrash() {
fetch("api/file/getTrashItems.php", { credentials: "include" })
fetch("/api/file/getTrashItems.php", { credentials: "include" })
.then(response => response.json())
.then(trashItems => {
const now = Date.now();
@@ -279,7 +279,7 @@ function autoPurgeOldTrash() {
const oldItems = trashItems.filter(item => (now - (item.trashedAt * 1000)) > threeDays);
if (oldItems.length > 0) {
const files = oldItems.map(item => item.trashName);
fetch("api/file/deleteTrashFiles.php", {
fetch("/api/file/deleteTrashFiles.php", {
method: "POST",
credentials: "include",
headers: {

View File

@@ -126,7 +126,7 @@ function removeChunkFolderRepeatedly(identifier, csrfToken, maxAttempts = 3, int
// Prefix with "resumable_" to match your PHP regex.
params.append('folder', 'resumable_' + identifier);
params.append('csrf_token', csrfToken);
fetch('api/upload/removeChunks.php', {
fetch('/api/upload/removeChunks.php', {
method: 'POST',
credentials: 'include',
headers: {
@@ -664,7 +664,7 @@ function submitFiles(allFiles) {
}
});
xhr.open("POST", "api/upload/upload.php", true);
xhr.open("POST", "/api/upload/upload.php", true);
xhr.setRequestHeader("X-CSRF-Token", window.csrfToken);
xhr.send(formData);
});

2599
public/openapi.json Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -84,7 +84,7 @@ class AuthController
if ($totpCode && isset($_SESSION['pending_login_user'], $_SESSION['pending_login_secret'])) {
$username = $_SESSION['pending_login_user'];
$secret = $_SESSION['pending_login_secret'];
$rememberMe = $_SESSION['pending_login_remember_me'] ?? false;
$tfa = new TwoFactorAuth(new GoogleChartsQrCodeProvider(), 'FileRise', 6, 30, Algorithm::Sha1);
if (! $tfa->verifyCode($secret, $totpCode)) {
echo json_encode(['error' => 'Invalid TOTP code']);
@@ -203,6 +203,7 @@ class AuthController
if (! empty($user['totp_secret'])) {
$_SESSION['pending_login_user'] = $username;
$_SESSION['pending_login_secret'] = $user['totp_secret'];
$_SESSION['pending_login_remember_me'] = $rememberMe;
echo json_encode(['totp_required' => true]);
exit();
}
@@ -237,22 +238,39 @@ class AuthController
$token = bin2hex(random_bytes(32));
$expiry = time() + 30 * 24 * 60 * 60;
$all = [];
if (file_exists($tokFile)) {
$dec = decryptData(file_get_contents($tokFile), $GLOBALS['encryptionKey']);
$all = json_decode($dec, true) ?: [];
}
$all[$token] = [
'username' => $username,
'expiry' => $expiry,
'isAdmin' => $_SESSION['isAdmin']
'expiry' => $expiry,
'isAdmin' => $_SESSION['isAdmin']
];
file_put_contents(
$tokFile,
encryptData(json_encode($all, JSON_PRETTY_PRINT), $GLOBALS['encryptionKey']),
LOCK_EX
);
$secure = (! empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
$secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
setcookie('remember_me_token', $token, $expiry, '/', '', $secure, true);
setcookie(
session_name(),
session_id(),
$expiry,
'/',
'',
$secure,
true
);
session_regenerate_id(true);
}
echo json_encode([

View File

@@ -847,104 +847,147 @@ class UserController
* )
*/
public function verifyTOTP()
{
header('Content-Type: application/json');
// Set CSP headers if desired:
header("Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self';");
public function verifyTOTP()
{
header('Content-Type: application/json');
header("Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self';");
// Ratelimit: initialize totp_failures if not set.
if (!isset($_SESSION['totp_failures'])) {
$_SESSION['totp_failures'] = 0;
}
if ($_SESSION['totp_failures'] >= 5) {
http_response_code(429);
echo json_encode(['status' => 'error', 'message' => 'Too many TOTP attempts. Please try again later.']);
exit;
}
// Ratelimit
if (!isset($_SESSION['totp_failures'])) {
$_SESSION['totp_failures'] = 0;
}
if ($_SESSION['totp_failures'] >= 5) {
http_response_code(429);
echo json_encode(['status' => 'error', 'message' => 'Too many TOTP attempts. Please try again later.']);
exit;
}
// Must be authenticated OR have a pending login.
if (!((isset($_SESSION['authenticated']) && $_SESSION['authenticated'] === true) || isset($_SESSION['pending_login_user']))) {
http_response_code(403);
echo json_encode(['status' => 'error', 'message' => 'Not authenticated']);
exit;
}
// Must be authenticated OR pending login
if (!((!empty($_SESSION['authenticated'])) || isset($_SESSION['pending_login_user']))) {
http_response_code(403);
echo json_encode(['status' => 'error', 'message' => 'Not authenticated']);
exit;
}
// CSRF check.
$headersArr = array_change_key_case(getallheaders(), CASE_LOWER);
$csrfHeader = isset($headersArr['x-csrf-token']) ? trim($headersArr['x-csrf-token']) : '';
if (!isset($_SESSION['csrf_token']) || $csrfHeader !== $_SESSION['csrf_token']) {
http_response_code(403);
echo json_encode(['status' => 'error', 'message' => 'Invalid CSRF token']);
exit;
}
// CSRF check
$headersArr = array_change_key_case(getallheaders(), CASE_LOWER);
$csrfHeader = $headersArr['x-csrf-token'] ?? '';
if (empty($_SESSION['csrf_token']) || $csrfHeader !== $_SESSION['csrf_token']) {
http_response_code(403);
echo json_encode(['status' => 'error', 'message' => 'Invalid CSRF token']);
exit;
}
// Parse input.
$inputData = json_decode(file_get_contents("php://input"), true);
$code = trim($inputData['totp_code'] ?? '');
if (!preg_match('/^\d{6}$/', $code)) {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'A valid 6-digit TOTP code is required']);
exit;
}
// Parse and validate input
$inputData = json_decode(file_get_contents("php://input"), true);
$code = trim($inputData['totp_code'] ?? '');
if (!preg_match('/^\d{6}$/', $code)) {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'A valid 6-digit TOTP code is required']);
exit;
}
// Create TFA object.
$tfa = new \RobThree\Auth\TwoFactorAuth(
new \RobThree\Auth\Providers\Qr\GoogleChartsQrCodeProvider(),
'FileRise',
6,
30,
\RobThree\Auth\Algorithm::Sha1
);
// TFA helper
$tfa = new \RobThree\Auth\TwoFactorAuth(
new \RobThree\Auth\Providers\Qr\GoogleChartsQrCodeProvider(),
'FileRise', 6, 30, \RobThree\Auth\Algorithm::Sha1
);
// Check if we are in pending login flow.
if (isset($_SESSION['pending_login_user'])) {
$username = $_SESSION['pending_login_user'];
$pendingSecret = $_SESSION['pending_login_secret'] ?? null;
if (!$pendingSecret || !$tfa->verifyCode($pendingSecret, $code)) {
$_SESSION['totp_failures']++;
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Invalid TOTP code']);
exit;
}
// Successful pending login: finalize login.
session_regenerate_id(true);
$_SESSION['authenticated'] = true;
$_SESSION['username'] = $username;
// Set isAdmin based on user role.
$_SESSION['isAdmin'] = (userModel::getUserRole($username) === "1");
// Load additional permissions (e.g., folderOnly) as needed.
$_SESSION['folderOnly'] = loadUserPermissions($username);
unset($_SESSION['pending_login_user'], $_SESSION['pending_login_secret'], $_SESSION['totp_failures']);
echo json_encode(['status' => 'ok', 'message' => 'Login successful']);
exit;
}
// Pendinglogin flow (first password step passed)
if (isset($_SESSION['pending_login_user'])) {
$username = $_SESSION['pending_login_user'];
$pendingSecret = $_SESSION['pending_login_secret'] ?? null;
$rememberMe = $_SESSION['pending_login_remember_me'] ?? false;
// Otherwise, we are in setup/verification flow.
$username = $_SESSION['username'] ?? '';
if (!$username) {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Username not found in session']);
exit;
}
if (!$pendingSecret || !$tfa->verifyCode($pendingSecret, $code)) {
$_SESSION['totp_failures']++;
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Invalid TOTP code']);
exit;
}
// Retrieve the user's TOTP secret from the model.
$totpSecret = userModel::getTOTPSecret($username);
if (!$totpSecret) {
http_response_code(500);
echo json_encode(['status' => 'error', 'message' => 'TOTP secret not found. Please set up TOTP again.']);
exit;
}
// === Issue “remember me” token if requested ===
if ($rememberMe) {
$tokFile = USERS_DIR . 'persistent_tokens.json';
$token = bin2hex(random_bytes(32));
$expiry = time() + 30 * 24 * 60 * 60;
$all = [];
if (!$tfa->verifyCode($totpSecret, $code)) {
$_SESSION['totp_failures']++;
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Invalid TOTP code']);
exit;
}
if (file_exists($tokFile)) {
$dec = decryptData(file_get_contents($tokFile), $GLOBALS['encryptionKey']);
$all = json_decode($dec, true) ?: [];
}
$all[$token] = [
'username' => $username,
'expiry' => $expiry,
'isAdmin' => $_SESSION['isAdmin']
];
file_put_contents(
$tokFile,
encryptData(json_encode($all, JSON_PRETTY_PRINT), $GLOBALS['encryptionKey']),
LOCK_EX
);
// Successful verification.
unset($_SESSION['totp_failures']);
echo json_encode(['status' => 'ok', 'message' => 'TOTP successfully verified']);
}
$secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
// Persistent cookie
setcookie('remember_me_token', $token, $expiry, '/', '', $secure, true);
// Reissue PHP session cookie
setcookie(
session_name(),
session_id(),
$expiry,
'/',
'',
$secure,
true
);
}
// Finalize login
session_regenerate_id(true);
$_SESSION['authenticated'] = true;
$_SESSION['username'] = $username;
$_SESSION['isAdmin'] = (userModel::getUserRole($username) === "1");
$_SESSION['folderOnly'] = loadUserPermissions($username);
// Clean up
unset(
$_SESSION['pending_login_user'],
$_SESSION['pending_login_secret'],
$_SESSION['pending_login_remember_me'],
$_SESSION['totp_failures']
);
echo json_encode(['status' => 'ok', 'message' => 'Login successful']);
exit;
}
// Setup/verification flow (not pending)
$username = $_SESSION['username'] ?? '';
if (!$username) {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Username not found in session']);
exit;
}
$totpSecret = userModel::getTOTPSecret($username);
if (!$totpSecret) {
http_response_code(500);
echo json_encode(['status' => 'error', 'message' => 'TOTP secret not found. Please set up TOTP again.']);
exit;
}
if (!$tfa->verifyCode($totpSecret, $code)) {
$_SESSION['totp_failures']++;
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Invalid TOTP code']);
exit;
}
// Successful setup/verification
unset($_SESSION['totp_failures']);
echo json_encode(['status' => 'ok', 'message' => 'TOTP successfully verified']);
}
}