Admin-scoped user accounts, secure qr code storage, PHP 8.4 upgrade

Admin-scoped users (answers: who can create a 'user' account, only super or
also an admin within their own scope?):
- New owner_admin_id column on users (migration 004). NULL means created by
  super (company-wide, previous behavior); otherwise scoped to that admin's
  own codes.
- Users::addUser/editUser/deleteUser now allow an 'admin' session, but force
  type='user' and owner_admin_id to their own id regardless of submitted
  input. user.php/users.php open up to admins with a restricted UI (no type
  picker, listing limited to their own created users).
- New qr_compute_scope_owner_id()/qr_apply_owner_scope()/qr_has_full_visibility()
  helpers in includes/security.php, replacing the ad-hoc type==='admin' checks
  in index.php, dynamic_qrcodes.php, static_qrcodes.php and bulk_action.php.
  A 'user' account created by an admin is now scoped to that admin's codes
  instead of seeing everything company-wide.

Qr code storage hardening: images were served as plain static files under the
document root with no auth check at all. Storage now lives outside the web
root; qrcode_image.php and qrcode_zip_download.php gate access with the same
permission model as the list pages, and the bulk zip download is bound to the
session that generated it.

PHP 8.4 + chillerlan/php-qrcode 6.0.1: bumped since this is a dockerized app,
so the PHP version shipped doesn't matter to end users. Note: the 6.0.1 tag
itself only requires PHP 8.2 - the earlier "needs 8.4" read was from an
unpinned clone of master, which has since moved past the tag. Fixed along the
way, surfaced by testing on 8.4:
- The hardcoded Imagick build (an old pinned master commit, workaround for
  3.7.0 being broken on PHP 8.3+) no longer compiles on 8.4. Imagick 3.8.1 is
  now a normal stable release, so the workaround is gone.
- config.php had display_errors=On + error_reporting(E_ALL), so PHP 8.4's new
  deprecation notices got dumped straight into the response before
  session_start() could run, breaking login outright. Also an info-disclosure
  risk on its own. Now logged instead of displayed.
- MysqliDb::insertMulti() had an implicit nullable parameter, now explicit.
- includes/auth_validate.php redirected unauthenticated requests but never
  called exit(), so the rest of the script kept running.
- Dockerfile.fpm was missing both git (needed to clone chillerlan/php-qrcode)
  and the imagick extension entirely.

Also removes the unused sample qr code images that shipped in the original
repo; storage now lives outside the document root so they were never going
to be served again.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-08 20:38:58 +02:00
parent a1ab16d54c
commit b5ef4ac0cb
46 changed files with 357 additions and 140 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
# Kopieer naar .env en pas de waarden aan. .env wordt niet gecommit (zie .gitignore). # Copy to .env and adjust the values. .env is not committed (see .gitignore).
TYPE=docker TYPE=docker
QRCODE_GENERATOR=internal-chillerlan.qrcode QRCODE_GENERATOR=internal-chillerlan.qrcode
+11 -10
View File
@@ -1,4 +1,4 @@
FROM php:8.3 FROM php:8.4
RUN if [ "$(grep '^VERSION_ID=' /etc/os-release | cut -d '=' -f 2 | tr -d '"')" -eq "9" ]; then \ RUN if [ "$(grep '^VERSION_ID=' /etc/os-release | cut -d '=' -f 2 | tr -d '"')" -eq "9" ]; then \
sed -i -e 's/deb.debian.org/archive.debian.org/g' \ sed -i -e 's/deb.debian.org/archive.debian.org/g' \
@@ -51,16 +51,12 @@ RUN DEBIAN_FRONTEND=noninteractive apt-get update -q \
sockets \ sockets \
xsl \ xsl \
zip \ zip \
imagick \
" \ " \
&& case "$PHP_VERSION" in \ && case "$PHP_VERSION" in \
5.6.*) PHP_EXTENSIONS="$PHP_EXTENSIONS mcrypt mysql";; \ 5.6.*) PHP_EXTENSIONS="$PHP_EXTENSIONS mcrypt mysql";; \
7.0.*|7.1.*) PHP_EXTENSIONS="$PHP_EXTENSIONS mcrypt";; \ 7.0.*|7.1.*) PHP_EXTENSIONS="$PHP_EXTENSIONS mcrypt";; \
esac \ esac \
# Install Imagick from master on PHP >= 8.3, because imagick 3.7.0 broke on latest PHP releases and Imagick maintainers don't care to tag a newer release
&& if [ $(php -r 'echo PHP_VERSION_ID;') -lt 80300 ]; then \
PHP_EXTENSIONS="$PHP_EXTENSIONS imagick"; \
else PHP_EXTENSIONS="$PHP_EXTENSIONS https://api.github.com/repos/Imagick/imagick/tarball/28f27044e435a2b203e32675e942eb8de620ee58"; \
fi \
&& install-php-extensions $PHP_EXTENSIONS \ && install-php-extensions $PHP_EXTENSIONS \
&& if command -v a2enmod; then a2enmod rewrite; fi && if command -v a2enmod; then a2enmod rewrite; fi
@@ -86,10 +82,10 @@ RUN docker-php-ext-install sockets && docker-php-ext-enable sockets
RUN mkdir -p /opt && chmod 777 /opt RUN mkdir -p /opt && chmod 777 /opt
WORKDIR /opt WORKDIR /opt
# Vastgezet op 5.0.5 (laatste 5.x-release): vanaf 6.0.0 vereist de library PHP >= 8.4, # Pinned to a specific release tag instead of an unpinned clone of master, which is a
# terwijl deze image op PHP 8.3 draait. Een ongepinde clone van master is bovendien # reproducibility/supply-chain risk (the build can break silently when upstream moves on,
# een reproduceerbaarheids-/supply-chain-risico (build kan zonder waarschuwing breken). # as happened when master started requiring PHP 8.4 while this image was still on 8.3).
RUN git clone --branch 5.0.5 --depth 1 https://github.com/chillerlan/php-qrcode.git \ RUN git clone --branch 6.0.1 --depth 1 https://github.com/chillerlan/php-qrcode.git \
&& chmod -R 777 ./php-qrcode && chmod -R 777 ./php-qrcode
RUN cp ./php-qrcode/composer.json /var/www/html/composer.json RUN cp ./php-qrcode/composer.json /var/www/html/composer.json
RUN mkdir -p /var/www/html/test && chmod 777 /var/www/html/test RUN mkdir -p /var/www/html/test && chmod 777 /var/www/html/test
@@ -100,5 +96,10 @@ WORKDIR /var/www/html
RUN composer update RUN composer update
COPY ./src ./ COPY ./src ./
RUN chmod 755 *; RUN chmod 755 *;
# Qr code storage lives outside the document root so files can only be reached through
# the authenticated qrcode_image.php / qrcode_zip_download.php endpoints.
RUN mkdir -p /var/www/qrcode-storage/zip && chmod -R 777 /var/www/qrcode-storage
EXPOSE 80 EXPOSE 80
CMD ["php", "-S", "0.0.0.0:80"] CMD ["php", "-S", "0.0.0.0:80"]
+12 -5
View File
@@ -1,4 +1,4 @@
FROM php:8.3-fpm FROM php:8.4-fpm
RUN if [ "$(grep '^VERSION_ID=' /etc/os-release | cut -d '=' -f 2 | tr -d '"')" -eq "9" ]; then \ RUN if [ "$(grep '^VERSION_ID=' /etc/os-release | cut -d '=' -f 2 | tr -d '"')" -eq "9" ]; then \
sed -i -e 's/deb.debian.org/archive.debian.org/g' \ sed -i -e 's/deb.debian.org/archive.debian.org/g' \
@@ -13,6 +13,7 @@ RUN chmod +x /usr/local/bin/install-php-extensions
RUN DEBIAN_FRONTEND=noninteractive apt-get update -q \ RUN DEBIAN_FRONTEND=noninteractive apt-get update -q \
&& DEBIAN_FRONTEND=noninteractive apt-get install -qq -y \ && DEBIAN_FRONTEND=noninteractive apt-get install -qq -y \
curl \ curl \
git \
libzip-dev \ libzip-dev \
libjpeg62-turbo-dev \ libjpeg62-turbo-dev \
libpng-dev \ libpng-dev \
@@ -21,6 +22,7 @@ RUN DEBIAN_FRONTEND=noninteractive apt-get update -q \
&& install-php-extensions \ && install-php-extensions \
gd \ gd \
gettext \ gettext \
imagick \
intl \ intl \
mysqli \ mysqli \
opcache \ opcache \
@@ -41,8 +43,8 @@ RUN cd /opt \
RUN mkdir -p /opt && chmod 777 /opt RUN mkdir -p /opt && chmod 777 /opt
WORKDIR /opt WORKDIR /opt
# Zie Dockerfile: vastgezet op 5.0.5, want 6.0.0+ vereist PHP >= 8.4. # See Dockerfile: pinned to a specific release tag instead of an unpinned clone of master.
RUN git clone --branch 5.0.5 --depth 1 https://github.com/chillerlan/php-qrcode.git \ RUN git clone --branch 6.0.1 --depth 1 https://github.com/chillerlan/php-qrcode.git \
&& chmod -R 777 ./php-qrcode && chmod -R 777 ./php-qrcode
RUN cp ./php-qrcode/composer.json /var/www/html/composer.json RUN cp ./php-qrcode/composer.json /var/www/html/composer.json
RUN cp -R ./php-qrcode/src /var/www/html/ RUN cp -R ./php-qrcode/src /var/www/html/
@@ -52,8 +54,13 @@ RUN composer update
COPY ./src ./ COPY ./src ./
RUN chown -R www-data:www-data /var/www/html \ RUN chown -R www-data:www-data /var/www/html \
&& find /var/www/html -type f -exec chmod 644 {} \; \ && find /var/www/html -type f -exec chmod 644 {} \; \
&& find /var/www/html -type d -exec chmod 755 {} \; \ && find /var/www/html -type d -exec chmod 755 {} \;
&& chmod -R 775 /var/www/html/saved_qrcode
# Qr code storage lives outside the document root so files can only be reached through
# the authenticated qrcode_image.php / qrcode_zip_download.php endpoints.
RUN mkdir -p /var/www/qrcode-storage/zip \
&& chown -R www-data:www-data /var/www/qrcode-storage \
&& chmod -R 775 /var/www/qrcode-storage
EXPOSE 9000 EXPOSE 9000
CMD ["php-fpm"] CMD ["php-fpm"]
+3 -2
View File
@@ -18,6 +18,7 @@ CREATE TABLE IF NOT EXISTS `users` (
`password_changed_at` datetime DEFAULT NULL, `password_changed_at` datetime DEFAULT NULL,
`can_view_static` tinyint(1) NOT NULL DEFAULT 0, `can_view_static` tinyint(1) NOT NULL DEFAULT 0,
`can_view_dynamic` tinyint(1) NOT NULL DEFAULT 0, `can_view_dynamic` tinyint(1) NOT NULL DEFAULT 0,
`owner_admin_id` int(25) DEFAULT NULL,
PRIMARY KEY (`id`), PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`) UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0 ; ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0 ;
@@ -60,7 +61,7 @@ CREATE TABLE IF NOT EXISTS `static_qrcodes` (
PRIMARY KEY (`id`) PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ; ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;
-- Security hardening (Fase 1): rate limiting op login pogingen -- Security hardening (Fase 1): rate limiting on login attempts
CREATE TABLE IF NOT EXISTS `login_attempts` ( CREATE TABLE IF NOT EXISTS `login_attempts` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT, `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL, `username` varchar(50) NOT NULL,
@@ -72,7 +73,7 @@ CREATE TABLE IF NOT EXISTS `login_attempts` (
KEY `ip_attempted_at` (`ip_address`, `attempted_at`) KEY `ip_attempted_at` (`ip_address`, `attempted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Security hardening (Fase 1): audit log van gevoelige acties -- Security hardening (Fase 1): audit log of sensitive actions
CREATE TABLE IF NOT EXISTS `audit_log` ( CREATE TABLE IF NOT EXISTS `audit_log` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(25) DEFAULT NULL, `user_id` int(25) DEFAULT NULL,
+6 -6
View File
@@ -1,7 +1,7 @@
-- Fase 1 security hardening migratie. -- Fase 1 security hardening migration.
-- Voer uit tegen een bestaande database (gebruikt de originele -- Run against an existing database (using the original
-- giandonatoinverso/php-dynamic-qr-code-db image of een oudere init.sql). -- giandonatoinverso/php-dynamic-qr-code-db image or an older init.sql).
-- Kolommen/tabellen worden alleen toegevoegd als ze nog niet bestaan. -- Columns/tables are only added if they don't already exist.
SET @db := DATABASE(); SET @db := DATABASE();
@@ -23,8 +23,8 @@ SET @sql := IF(@col_exists = 0,
'SELECT 1'); 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
-- Bestaand superadmin account met het fabriekswachtwoord (superadmin/superadmin) -- An existing superadmin account with the factory password (superadmin/superadmin)
-- moet bij eerstvolgende login het wachtwoord wijzigen. -- must change its password on next login.
UPDATE `users` UPDATE `users`
SET `must_change_password` = 1 SET `must_change_password` = 1
WHERE `username` = 'superadmin' WHERE `username` = 'superadmin'
+2 -2
View File
@@ -1,5 +1,5 @@
-- Fase 2: read-only 'user' rol met twee zichtbaarheids-toggles. -- Fase 2: read-only 'user' role with two visibility toggles.
-- type='user' vereist geen schemawijziging (varchar(10), geen enum-constraint). -- type='user' requires no schema change (varchar(10), no enum constraint).
SET @db := DATABASE(); SET @db := DATABASE();
+14
View File
@@ -0,0 +1,14 @@
-- Option 2: an admin may create their own 'user' accounts within their own scope.
-- owner_admin_id = NULL means: created by super, company-wide (previous behavior).
-- owner_admin_id = <id> means: created by that admin, sees only that admin's own codes.
SET @db := DATABASE();
SET @col_exists := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'users' AND COLUMN_NAME = 'owner_admin_id'
);
SET @sql := IF(@col_exists = 0,
'ALTER TABLE `users` ADD COLUMN `owner_admin_id` INT(25) DEFAULT NULL',
'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
+7 -8
View File
@@ -4,11 +4,10 @@ services:
restart: "unless-stopped" restart: "unless-stopped"
ports: ports:
- "80:80" - "80:80"
# 443 pas openzetten zodra SSL-certificaten zijn gemount (bv. via certbot-volume # Only open 443 once SSL certificates are mounted (e.g. via a certbot volume,
# of een losse reverse proxy zoals Caddy/Traefik ervoor). Zie infra-fase van het plan. # or a separate reverse proxy like Caddy/Traefik in front). See the infra phase of the plan.
volumes: volumes:
- ./nginx.conf:/etc/nginx/conf.d/default.conf:ro - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
- php_dynamic_qrcode_saved_qrcode_data:/var/www/html/saved_qrcode:ro
depends_on: depends_on:
- php-dynamic-qrcode - php-dynamic-qrcode
networks: networks:
@@ -22,19 +21,19 @@ services:
environment: environment:
TYPE: "docker" TYPE: "docker"
QRCODE_GENERATOR: "${QRCODE_GENERATOR:-internal-chillerlan.qrcode}" QRCODE_GENERATOR: "${QRCODE_GENERATOR:-internal-chillerlan.qrcode}"
BASE_URL: "${BASE_URL:?zet BASE_URL in .env, bv. https://qr.ensembia.com}" BASE_URL: "${BASE_URL:?set BASE_URL in .env, e.g. https://qr.ensembia.com}"
DATABASE_HOST: "php-dynamic-qrcode-db" DATABASE_HOST: "php-dynamic-qrcode-db"
DATABASE_PORT: "3306" DATABASE_PORT: "3306"
DATABASE_NAME: "${DATABASE_NAME:-qrcode}" DATABASE_NAME: "${DATABASE_NAME:-qrcode}"
DATABASE_USER: "${DATABASE_USER:-qrcode}" DATABASE_USER: "${DATABASE_USER:-qrcode}"
DATABASE_PASSWORD: "${DATABASE_PASSWORD:?zet DATABASE_PASSWORD in .env}" DATABASE_PASSWORD: "${DATABASE_PASSWORD:?set DATABASE_PASSWORD in .env}"
DATABASE_PREFIX: "${DATABASE_PREFIX:-}" DATABASE_PREFIX: "${DATABASE_PREFIX:-}"
DATABASE_CHARSET: "${DATABASE_CHARSET:-utf8}" DATABASE_CHARSET: "${DATABASE_CHARSET:-utf8}"
depends_on: depends_on:
php-dynamic-qrcode-db: php-dynamic-qrcode-db:
condition: service_healthy condition: service_healthy
volumes: volumes:
- php_dynamic_qrcode_saved_qrcode_data:/var/www/html/saved_qrcode - php_dynamic_qrcode_saved_qrcode_data:/var/www/qrcode-storage
networks: networks:
- php-dynamic-qrcode-network - php-dynamic-qrcode-network
@@ -45,10 +44,10 @@ services:
- php_dynamic_qrcode_db_data:/var/lib/mysql - php_dynamic_qrcode_db_data:/var/lib/mysql
- ./db/init.sql:/docker-entrypoint-initdb.d/init.sql:ro - ./db/init.sql:/docker-entrypoint-initdb.d/init.sql:ro
environment: environment:
MYSQL_ROOT_PASSWORD: "${MYSQL_ROOT_PASSWORD:?zet MYSQL_ROOT_PASSWORD in .env}" MYSQL_ROOT_PASSWORD: "${MYSQL_ROOT_PASSWORD:?set MYSQL_ROOT_PASSWORD in .env}"
MYSQL_DATABASE: "${DATABASE_NAME:-qrcode}" MYSQL_DATABASE: "${DATABASE_NAME:-qrcode}"
MYSQL_USER: "${DATABASE_USER:-qrcode}" MYSQL_USER: "${DATABASE_USER:-qrcode}"
MYSQL_PASSWORD: "${DATABASE_PASSWORD:?zet DATABASE_PASSWORD in .env}" MYSQL_PASSWORD: "${DATABASE_PASSWORD:?set DATABASE_PASSWORD in .env}"
healthcheck: healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p${MYSQL_ROOT_PASSWORD}"] test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p${MYSQL_ROOT_PASSWORD}"]
interval: 5s interval: 5s
+2 -6
View File
@@ -21,12 +21,8 @@ server {
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
} }
# Statisch gegenereerde qrcodes mogen gedownload worden, maar niet als PHP uitgevoerd. # Generated qr codes are stored outside the document root and are only served
location /saved_qrcode/ { # through the authenticated qrcode_image.php / qrcode_zip_download.php endpoints.
location ~ \.php$ {
deny all;
}
}
location ~ /\. { location ~ /\. {
deny all; deny all;
+1
View File
@@ -42,6 +42,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST')
$_SESSION['must_change_password'] = !empty($row['must_change_password']); $_SESSION['must_change_password'] = !empty($row['must_change_password']);
$_SESSION['can_view_static'] = !empty($row['can_view_static']); $_SESSION['can_view_static'] = !empty($row['can_view_static']);
$_SESSION['can_view_dynamic'] = !empty($row['can_view_dynamic']); $_SESSION['can_view_dynamic'] = !empty($row['can_view_dynamic']);
$_SESSION['scope_owner_id'] = qr_compute_scope_owner_id($row);
$_SESSION['last_activity'] = time(); $_SESSION['last_activity'] = time();
audit_log('login_success'); audit_log('login_success');
+10 -11
View File
@@ -46,22 +46,18 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
foreach ($params as $param) { foreach ($params as $param) {
$db->where('id', $param); $db->where('id', $param);
if ($_SESSION['type'] === 'admin') { qr_apply_owner_scope($db);
$db->where('id_owner', $_SESSION['user_id']);
$db->orWhere('id_owner', NULL, 'IS');
}
$row = $db->getOne("{$type}_qrcodes"); $row = $db->getOne("{$type}_qrcodes");
if ($row !== NULL) { if ($row !== NULL) {
$files[] = SAVED_QRCODE_FOLDER . $row['qrcode']; $files[] = SAVED_QRCODE_DIRECTORY . $row['qrcode'];
} }
} }
$zip = new ZipArchive(); $zip = new ZipArchive();
$uniqid = uniqid(); $zip_filename = 'qrcodes_' . uniqid() . '.zip';
$relative_dir = SAVED_QRCODE_FOLDER . 'zip/qrcodes_' . $uniqid . '.zip'; $zip_path = SAVED_QRCODE_DIRECTORY . 'zip/' . $zip_filename;
@unlink($relative_dir); @unlink($zip_path);
$url_path = SAVED_QRCODE_URL . 'zip/qrcodes_' . $uniqid . '.zip'; $zip->open($zip_path, ZipArchive::CREATE);
$zip->open($relative_dir, ZipArchive::CREATE);
foreach ($files as $file) { foreach ($files as $file) {
$download_file = @file_get_contents($file, true); $download_file = @file_get_contents($file, true);
@@ -70,10 +66,13 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$zip->close(); $zip->close();
// Proof-of-generation: only this session may download this specific zip file.
$_SESSION['generated_zips'][] = $zip_filename;
audit_log('bulk_download', $type, implode(',', $params)); audit_log('bulk_download', $type, implode(',', $params));
echo json_encode([ echo json_encode([
'data' => $url_path, 'data' => 'qrcode_zip_download.php?file=' . rawurlencode($zip_filename),
'status' => 200 'status' => 200
]); ]);
exit(); exit();
+9 -5
View File
@@ -2,8 +2,12 @@
//Note: This file should be included first in every php page. //Note: This file should be included first in every php page.
require_once ('environment.php'); require_once ('environment.php');
// Never display errors/warnings/deprecations in the response body: besides leaking
// internal file paths, it can inject output before session_start() runs and break
// login entirely (seen with PHP 8.4's new deprecation notices). Log them instead.
error_reporting(E_ALL); error_reporting(E_ALL);
ini_set('display_errors', 'On'); ini_set('display_errors', 'Off');
ini_set('log_errors', 'On');
define('BASE_PATH', dirname(dirname(__FILE__))); define('BASE_PATH', dirname(dirname(__FILE__)));
define('CURRENT_PAGE', basename($_SERVER['REQUEST_URI'])); define('CURRENT_PAGE', basename($_SERVER['REQUEST_URI']));
define('SCRIPT_NAME', ltrim(dirname($_SERVER['SCRIPT_NAME']), '/')); define('SCRIPT_NAME', ltrim(dirname($_SERVER['SCRIPT_NAME']), '/'));
@@ -17,10 +21,10 @@ require_once BASE_PATH . '/lib/MysqliDb/MysqliDb.php';
require_once BASE_PATH . '/helpers/helpers.php'; require_once BASE_PATH . '/helpers/helpers.php';
/* SAVED QR CODES */ /* SAVED QR CODES */
//You can change the folder where the qr code will be saved // Storage lives outside the document root so files can only be reached through the
define('SAVED_QRCODE_FOLDER', './saved_qrcode/'); // authenticated qrcode_image.php / qrcode_zip_download.php endpoints, never as a direct
define('SAVED_QRCODE_DIRECTORY', BASE_PATH.'/saved_qrcode/'); // static URL. See db/migrations and the "saved_qrcode" hardening note in the OSS repo.
define('SAVED_QRCODE_URL', base_url(). SCRIPT_FOLDER .'/saved_qrcode/'); define('SAVED_QRCODE_DIRECTORY', dirname(BASE_PATH).'/qrcode-storage/');
//You can change the page name for the redirect and the search parameter (the default is "id") //You can change the page name for the redirect and the search parameter (the default is "id")
define('READ_PATH', base_url().'/read.php?id='); define('READ_PATH', base_url().'/read.php?id=');
+3 -5
View File
@@ -18,11 +18,9 @@ require_once BASE_PATH . '/includes/search_order.php';
$page = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS) ?? 1; $page = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS) ?? 1;
$db->pageLimit = 15; $db->pageLimit = 15;
// 'user' ziet, net als 'super', alle codes (heeft zelf geen eigen codes om op te scopen). // Scoped to one admin's own codes for an admin (or a 'user' created by that admin);
if($_SESSION['type'] === 'admin') { // full visibility for super and company-wide 'user' accounts.
$db->where("id_owner", $_SESSION['user_id']); qr_apply_owner_scope($db);
$db->orWhere ("id_owner", NULL, 'IS');
}
$rows = $db->arraybuilder()->paginate('dynamic_qrcodes', $page, $select); $rows = $db->arraybuilder()->paginate('dynamic_qrcodes', $page, $select);
$total_pages = $db->totalPages; $total_pages = $db->totalPages;
+24 -4
View File
@@ -25,6 +25,7 @@
</div> </div>
</div> </div>
<?php if ($_SESSION['type'] === 'super'): ?>
<div class="col-sm-4"> <div class="col-sm-4">
<label for="user-type">User type *</label> <label for="user-type">User type *</label>
@@ -47,17 +48,17 @@
</div> </div>
<div class="col-sm-12 mt-2" id="user-view-toggles"> <div class="col-sm-12 mt-2" id="user-view-toggles">
<label>Zichtbaarheid voor 'User'-rol</label> <label>Visibility for the 'User' role</label>
<div class="form-group"> <div class="form-group">
<div class="icheck-primary d-inline-block mr-4"> <div class="icheck-primary d-inline-block mr-4">
<input type="checkbox" name="can_view_static" id="can_view_static" value="1" <?php echo ($edit && !empty($user['can_view_static'])) ? "checked": "" ; ?>> <input type="checkbox" name="can_view_static" id="can_view_static" value="1" <?php echo ($edit && !empty($user['can_view_static'])) ? "checked": "" ; ?>>
<label for="can_view_static">Mag statische QR-codes bekijken</label> <label for="can_view_static">Can view static qr codes</label>
</div> </div>
<div class="icheck-primary d-inline-block"> <div class="icheck-primary d-inline-block">
<input type="checkbox" name="can_view_dynamic" id="can_view_dynamic" value="1" <?php echo ($edit && !empty($user['can_view_dynamic'])) ? "checked": "" ; ?>> <input type="checkbox" name="can_view_dynamic" id="can_view_dynamic" value="1" <?php echo ($edit && !empty($user['can_view_dynamic'])) ? "checked": "" ; ?>>
<label for="can_view_dynamic">Mag dynamische QR-codes bekijken</label> <label for="can_view_dynamic">Can view dynamic qr codes</label>
</div> </div>
<small class="form-text text-muted">Alleen van toepassing op het type 'User'. Reports/statistieken zijn voor 'User' altijd zichtbaar.</small> <small class="form-text text-muted">Only applies to the 'User' type. Reports/statistics are always visible for 'User'.</small>
</div> </div>
</div> </div>
@@ -78,6 +79,25 @@
updateToggleVisibility(); updateToggleVisibility();
})(); })();
</script> </script>
<?php else: ?>
<!-- An 'admin' can only create/manage their own read-only 'user' accounts. -->
<input type="hidden" name="type" value="user">
<div class="col-sm-12 mt-2">
<label>Visibility for this user</label>
<div class="form-group">
<div class="icheck-primary d-inline-block mr-4">
<input type="checkbox" name="can_view_static" id="can_view_static" value="1" <?php echo ($edit && !empty($user['can_view_static'])) ? "checked": "" ; ?>>
<label for="can_view_static">Can view static qr codes</label>
</div>
<div class="icheck-primary d-inline-block">
<input type="checkbox" name="can_view_dynamic" id="can_view_dynamic" value="1" <?php echo ($edit && !empty($user['can_view_dynamic'])) ? "checked": "" ; ?>>
<label for="can_view_dynamic">Can view dynamic qr codes</label>
</div>
<small class="form-text text-muted">Reports/statistics are always visible for this account.</small>
</div>
</div>
<?php endif; ?>
<?php if($edit) { ?> <?php if($edit) { ?>
<input type="hidden" name="id" value="<?php echo $user['id'];?>"/> <input type="hidden" name="id" value="<?php echo $user['id'];?>"/>
+2 -2
View File
@@ -70,7 +70,7 @@
<td><?php echo htmlspecialchars($row['identifier']); ?></td> <td><?php echo htmlspecialchars($row['identifier']); ?></td>
<td><?php echo htmlspecialchars($row['link']); ?></td> <td><?php echo htmlspecialchars($row['link']); ?></td>
<td> <td>
<?php echo '<img src="'.SAVED_QRCODE_FOLDER.htmlspecialchars($row['qrcode']).'" width="100" height="100">'; ?> <?php echo '<img src="qrcode_image.php?type=dynamic&id='.$row['id'].'" width="100" height="100">'; ?>
</td> </td>
<td><?php echo htmlspecialchars($row['scan']); ?></td> <td><?php echo htmlspecialchars($row['scan']); ?></td>
<td><?php echo htmlspecialchars($row['state']); ?></td> <td><?php echo htmlspecialchars($row['state']); ?></td>
@@ -88,7 +88,7 @@
><i class="fas fa-trash"></i></a> ><i class="fas fa-trash"></i></a>
<?php endif; ?> <?php endif; ?>
<!-- DOWNLOAD --> <!-- DOWNLOAD -->
<a href="<?php echo SAVED_QRCODE_FOLDER.htmlspecialchars($row['qrcode']); ?>" class="btn btn-primary" download><i class="fa fa-download"></i></a> <a href="qrcode_image.php?type=dynamic&id=<?php echo $row['id']; ?>&download=1" class="btn btn-primary"><i class="fa fa-download"></i></a>
</td> </td>
</tr> </tr>
<?php endforeach; ?> <?php endforeach; ?>
+2 -2
View File
@@ -68,7 +68,7 @@
<td><?php echo htmlspecialchars($row['type']); ?></td> <td><?php echo htmlspecialchars($row['type']); ?></td>
<td><?php echo htmlspecialchars_decode($row['content']); ?></td> <td><?php echo htmlspecialchars_decode($row['content']); ?></td>
<td> <td>
<?php echo '<img src="'.SAVED_QRCODE_FOLDER.htmlspecialchars($row['qrcode']).'" width="100" height="100">'; ?> <?php echo '<img src="qrcode_image.php?type=static&id='.$row['id'].'" width="100" height="100">'; ?>
</td> </td>
<td> <td>
<?php if (!$is_readonly_user): ?> <?php if (!$is_readonly_user): ?>
@@ -84,7 +84,7 @@
><i class="fas fa-trash"></i></a> ><i class="fas fa-trash"></i></a>
<?php endif; ?> <?php endif; ?>
<!-- DOWNLOAD --> <!-- DOWNLOAD -->
<a href="<?php echo SAVED_QRCODE_FOLDER.htmlspecialchars($row['qrcode']); ?>" class="btn btn-primary" download><i class="fa fa-download"></i></a> <a href="qrcode_image.php?type=static&id=<?php echo $row['id']; ?>&download=1" class="btn btn-primary"><i class="fa fa-download"></i></a>
</td> </td>
</tr> </tr>
<?php endforeach; ?> <?php endforeach; ?>
+2 -1
View File
@@ -3,8 +3,9 @@
//If User is logged in the session['user_logged_in'] will be set to true //If User is logged in the session['user_logged_in'] will be set to true
//if user is Not Logged in, redirect to login.php page. //if user is Not Logged in, redirect to login.php page.
if (!isset($_SESSION['user_logged_in'])) { if (empty($_SESSION['user_logged_in'])) {
header('Location:login.php'); header('Location:login.php');
exit;
} }
?> ?>
+43
View File
@@ -143,6 +143,49 @@ function qr_is_login_locked_out($username) {
return $count !== null && $count >= LOGIN_MAX_ATTEMPTS; return $count !== null && $count >= LOGIN_MAX_ATTEMPTS;
} }
/**
* Compute the owner-scope for a freshly authenticated user row (see qr_scope_owner_id()
* below for the meaning of the returned value). Call once at login and store the result
* in $_SESSION['scope_owner_id'].
*/
function qr_compute_scope_owner_id($user_row) {
if ($user_row['type'] === 'admin') {
return (int) $user_row['id'];
}
if ($user_row['type'] === 'user' && !empty($user_row['owner_admin_id'])) {
return (int) $user_row['owner_admin_id'];
}
return null;
}
/**
* Owner-scope for the qr code lists/reports, set at login time in $_SESSION['scope_owner_id']:
* - null: full visibility (super, or a company-wide 'user' account created by super)
* - int: restricted to codes owned by this admin id (an admin's own account, or a
* 'user' account created by that admin)
*/
function qr_scope_owner_id() {
return $_SESSION['scope_owner_id'] ?? null;
}
function qr_has_full_visibility() {
return qr_scope_owner_id() === null;
}
/**
* Apply the current session's owner scope to a MysqliDb query builder in place.
* No-op when the session has full visibility.
*/
function qr_apply_owner_scope($db) {
$scope_owner_id = qr_scope_owner_id();
if ($scope_owner_id !== null) {
$db->where('id_owner', $scope_owner_id);
$db->orWhere('id_owner', NULL, 'IS');
}
}
/** /**
* Audit log * Audit log
*/ */
+1 -1
View File
@@ -87,7 +87,7 @@
</ul> </ul>
</li> </li>
<?php endif; ?> <?php endif; ?>
<?php if ($_SESSION['type'] === 'super'): ?> <?php if (in_array($_SESSION['type'], ['super', 'admin'], true)): ?>
<li class="nav-item"> <li class="nav-item">
<a href="./users.php" <?php echo ((substr(CURRENT_PAGE, 0, 15) == 'users.php') || (substr(CURRENT_PAGE, 0, 14) == 'user.php')) ? ' class="nav-link active"' : ' class="nav-link"'; ?>> <a href="./users.php" <?php echo ((substr(CURRENT_PAGE, 0, 15) == 'users.php') || (substr(CURRENT_PAGE, 0, 14) == 'user.php')) ? ' class="nav-link active"' : ' class="nav-link"'; ?>>
<i class="fas fa-users nav-icon"></i> <i class="fas fa-users nav-icon"></i>
+8 -17
View File
@@ -4,31 +4,22 @@ require_once 'includes/auth_validate.php';
$db = getDbInstance(); $db = getDbInstance();
// Reports/statistieken zijn voor de 'user'-rol altijd volledig zichtbaar (net als 'super'), // Full visibility (super, or a company-wide 'user' account) vs. scoped to one admin's
// ongeacht de can_view_static/can_view_dynamic toggles die alleen de qrcode-lijsten regelen. // own codes (an admin, or a 'user' account created by that admin).
$is_full_visibility = in_array($_SESSION['type'], ['super', 'user'], true); $is_full_visibility = qr_has_full_visibility();
//Get Dynamic qr code rows //Get Dynamic qr code rows
if(!$is_full_visibility) { qr_apply_owner_scope($db);
$db->where("id_owner", $_SESSION['user_id']);
$db->orWhere ("id_owner", NULL, 'IS');
}
$numQrcode_dynamic = $db->getValue("dynamic_qrcodes", "count(*)"); $numQrcode_dynamic = $db->getValue("dynamic_qrcodes", "count(*)");
//Get Static qr code rows //Get Static qr code rows
if(!$is_full_visibility) { qr_apply_owner_scope($db);
$db->where("id_owner", $_SESSION['user_id']);
$db->orWhere ("id_owner", NULL, 'IS');
}
$numQrcode_static = $db->getValue("static_qrcodes", "count(*)"); $numQrcode_static = $db->getValue("static_qrcodes", "count(*)");
$total = $numQrcode_dynamic + $numQrcode_static; $total = $numQrcode_dynamic + $numQrcode_static;
//Get Total scan //Get Total scan
if(!$is_full_visibility) { qr_apply_owner_scope($db);
$db->where("id_owner", $_SESSION['user_id']);
$db->orWhere ("id_owner", NULL, 'IS');
}
$numScan = $db->getOne("dynamic_qrcodes", "sum(scan) as numScan"); $numScan = $db->getOne("dynamic_qrcodes", "sum(scan) as numScan");
/* CREATED CHART */ /* CREATED CHART */
@@ -36,7 +27,7 @@ $numScan = $db->getOne("dynamic_qrcodes", "sum(scan) as numScan");
//Get the number of DYNAMIC qr code created in 7 days and total scan //Get the number of DYNAMIC qr code created in 7 days and total scan
if(!$is_full_visibility) if(!$is_full_visibility)
$createdQrcode_dynamic = $db->query("select `created_at`, `scan` from " . DATABASE_PREFIX . "dynamic_qrcodes where `created_at` > curdate()-7 AND (`id_owner`= " . $_SESSION['user_id'] . " OR `id_owner` IS NULL);"); $createdQrcode_dynamic = $db->query("select `created_at`, `scan` from " . DATABASE_PREFIX . "dynamic_qrcodes where `created_at` > curdate()-7 AND (`id_owner`= " . (int) qr_scope_owner_id() . " OR `id_owner` IS NULL);");
else else
$createdQrcode_dynamic = $db->query("select `created_at`, `scan` from ".DATABASE_PREFIX."dynamic_qrcodes where `created_at` > curdate()-7;"); $createdQrcode_dynamic = $db->query("select `created_at`, `scan` from ".DATABASE_PREFIX."dynamic_qrcodes where `created_at` > curdate()-7;");
@@ -59,7 +50,7 @@ foreach ($createdQrcode_dynamic as $row) {
/* SCAN CHART */ /* SCAN CHART */
//Get the number of STATIC qr code created in 7 days //Get the number of STATIC qr code created in 7 days
if(!$is_full_visibility) if(!$is_full_visibility)
$createdQrcode_static = $db->query("select `created_at` from " . DATABASE_PREFIX . "static_qrcodes where `created_at` > curdate()-7 AND (`id_owner`=" . $_SESSION['user_id'] . " OR `id_owner` IS NULL);"); $createdQrcode_static = $db->query("select `created_at` from " . DATABASE_PREFIX . "static_qrcodes where `created_at` > curdate()-7 AND (`id_owner`=" . (int) qr_scope_owner_id() . " OR `id_owner` IS NULL);");
else else
$createdQrcode_static = $db->query("select `created_at` from ".DATABASE_PREFIX."static_qrcodes where `created_at` > curdate()-7;"); $createdQrcode_static = $db->query("select `created_at` from ".DATABASE_PREFIX."static_qrcodes where `created_at` > curdate()-7;");
+1 -1
View File
@@ -830,7 +830,7 @@ class MysqliDb
* @return bool|array Boolean indicating the insertion failed (false), else return id-array ([int]) * @return bool|array Boolean indicating the insertion failed (false), else return id-array ([int])
* @throws Exception * @throws Exception
*/ */
public function insertMulti($tableName, array $multiInsertData, array $dataKeys = null) public function insertMulti($tableName, array $multiInsertData, ?array $dataKeys = null)
{ {
// only auto-commit our inserts, if no transaction is currently running // only auto-commit our inserts, if no transaction is currently running
$autoCommit = (isset($this->_transaction_in_progress) ? !$this->_transaction_in_progress : true); $autoCommit = (isset($this->_transaction_in_progress) ? !$this->_transaction_in_progress : true);
+64 -12
View File
@@ -13,7 +13,7 @@ class Users
} }
/** /**
* Server-side validatie van username/type. Geeft een foutmelding terug (string) of null als geldig. * Server-side validation of username/type. Returns an error message (string) or null if valid.
*/ */
private function validateUsernameAndType($username, $type) { private function validateUsernameAndType($username, $type) {
if (!is_string($username) || strlen($username) < 3 || strlen($username) > 50) { if (!is_string($username) || strlen($username) < 3 || strlen($username) > 50) {
@@ -57,6 +57,24 @@ class Users
return $db->get(DATABASE_PREFIX.'users'); return $db->get(DATABASE_PREFIX.'users');
} }
/**
* True if the logged-in admin is allowed to manage (edit/delete) this user record.
* Super can always manage everyone.
*/
private function canManage($target_user) {
if ($_SESSION['type'] === 'super') {
return true;
}
if ($_SESSION['type'] === 'admin') {
return $target_user !== null
&& $target_user['type'] === 'user'
&& (int) $target_user['owner_admin_id'] === (int) $_SESSION['user_id'];
}
return false;
}
public function getUser($id) { public function getUser($id) {
$db = getDbInstance(); $db = getDbInstance();
@@ -70,12 +88,27 @@ class Users
} }
/** /**
* Add user * Add user.
*
* A 'super' account can create any type freely (owner_admin_id stays NULL: company-wide).
* An 'admin' account can only create their own read-only 'user' accounts
* (type is forced to 'user', owner_admin_id is forced to their own id).
*/ */
public function addUser($input_data) { public function addUser($input_data) {
$db = getDbInstance(); $db = getDbInstance();
$validation_error = $this->validateUsernameAndType($input_data['username'] ?? '', $input_data['type'] ?? ''); $requested_type = $input_data['type'] ?? '';
$owner_admin_id = null;
if ($_SESSION['type'] === 'admin') {
$requested_type = 'user';
$owner_admin_id = $_SESSION['user_id'];
} elseif ($_SESSION['type'] !== 'super') {
header('HTTP/1.1 403 Forbidden', true, 403);
exit('403 Forbidden');
}
$validation_error = $this->validateUsernameAndType($input_data['username'] ?? '', $requested_type);
if ($validation_error !== null) { if ($validation_error !== null) {
$this->failure($validation_error, 'Location: user.php'); $this->failure($validation_error, 'Location: user.php');
} }
@@ -86,7 +119,8 @@ class Users
$data_to_db["username"] = $input_data["username"]; $data_to_db["username"] = $input_data["username"];
$data_to_db['password'] = password_hash($input_data['password'], PASSWORD_DEFAULT); $data_to_db['password'] = password_hash($input_data['password'], PASSWORD_DEFAULT);
$data_to_db["type"] = $input_data["type"]; $data_to_db["type"] = $requested_type;
$data_to_db['owner_admin_id'] = $owner_admin_id;
$data_to_db['can_view_static'] = !empty($input_data['can_view_static']) ? 1 : 0; $data_to_db['can_view_static'] = !empty($input_data['can_view_static']) ? 1 : 0;
$data_to_db['can_view_dynamic'] = !empty($input_data['can_view_dynamic']) ? 1 : 0; $data_to_db['can_view_dynamic'] = !empty($input_data['can_view_dynamic']) ? 1 : 0;
@@ -105,18 +139,30 @@ class Users
} }
/** /**
* Edit user * Edit user.
* *
* An 'admin' may only edit their own 'user' accounts (checked via canManage()) and
* cannot change the type away from 'user'. A 'super' account can edit anyone freely.
*/ */
public function editUser($input_data) { public function editUser($input_data) {
$db = getDbInstance(); $db = getDbInstance();
$db->where('id', $input_data['id']);
$target = $db->getOne('users');
if (!$this->canManage($target)) {
header('HTTP/1.1 403 Forbidden', true, 403);
exit('403 Forbidden');
}
$query_string = http_build_query(array( $query_string = http_build_query(array(
'id' => $input_data["id"], 'id' => $input_data["id"],
'edit' => "true", 'edit' => "true",
)); ));
$validation_error = $this->validateUsernameAndType($input_data['username'] ?? '', $input_data['type'] ?? ''); $requested_type = $_SESSION['type'] === 'admin' ? 'user' : ($input_data['type'] ?? '');
$validation_error = $this->validateUsernameAndType($input_data['username'] ?? '', $requested_type);
if ($validation_error !== null) { if ($validation_error !== null) {
$this->failure($validation_error, 'Location: user.php?'.$query_string); $this->failure($validation_error, 'Location: user.php?'.$query_string);
} }
@@ -125,6 +171,7 @@ class Users
$this->failure('Password must be at least 10 characters long.', 'Location: user.php?'.$query_string); $this->failure('Password must be at least 10 characters long.', 'Location: user.php?'.$query_string);
} }
$db = getDbInstance();
$db->where('username', $input_data['username']); $db->where('username', $input_data['username']);
$db->where('id', $input_data["id"], '!='); $db->where('id', $input_data["id"], '!=');
$row = $db->getOne('users'); $row = $db->getOne('users');
@@ -134,11 +181,11 @@ class Users
} }
$data_to_db["username"] = $input_data["username"]; $data_to_db["username"] = $input_data["username"];
$data_to_db["type"] = $input_data["type"]; $data_to_db["type"] = $requested_type;
$data_to_db['can_view_static'] = !empty($input_data['can_view_static']) ? 1 : 0; $data_to_db['can_view_static'] = !empty($input_data['can_view_static']) ? 1 : 0;
$data_to_db['can_view_dynamic'] = !empty($input_data['can_view_dynamic']) ? 1 : 0; $data_to_db['can_view_dynamic'] = !empty($input_data['can_view_dynamic']) ? 1 : 0;
// Alleen wachtwoord overschrijven als er een nieuwe waarde is opgegeven. // Only overwrite the password if a new value was submitted.
if (!empty($input_data['password'])) { if (!empty($input_data['password'])) {
$data_to_db['password'] = password_hash($input_data['password'], PASSWORD_DEFAULT); $data_to_db['password'] = password_hash($input_data['password'], PASSWORD_DEFAULT);
} }
@@ -154,13 +201,18 @@ class Users
} }
/** /**
* Delete user * Delete user.
* *
* An 'admin' may only delete their own 'user' accounts; 'super' can delete anyone.
*/ */
public function deleteUser($id) { public function deleteUser($id) {
if($_SESSION['type']!='super'){ $db = getDbInstance();
header('HTTP/1.1 401 Unauthorized', true, 401); $db->where('id', $id);
exit("401 Unauthorized"); $target = $db->getOne('users');
if (!$this->canManage($target)) {
header('HTTP/1.1 403 Forbidden', true, 403);
exit('403 Forbidden');
} }
$db = getDbInstance(); $db = getDbInstance();
+1
View File
@@ -42,6 +42,7 @@ if (isset($_COOKIE['series_id']) && isset($_COOKIE['remember_token']))
$_SESSION['must_change_password'] = !empty($row['must_change_password']); $_SESSION['must_change_password'] = !empty($row['must_change_password']);
$_SESSION['can_view_static'] = !empty($row['can_view_static']); $_SESSION['can_view_static'] = !empty($row['can_view_static']);
$_SESSION['can_view_dynamic'] = !empty($row['can_view_dynamic']); $_SESSION['can_view_dynamic'] = !empty($row['can_view_dynamic']);
$_SESSION['scope_owner_id'] = qr_compute_scope_owner_id($row);
$_SESSION['last_activity'] = time(); $_SESSION['last_activity'] = time();
audit_log('login_success_remember'); audit_log('login_success_remember');
+63
View File
@@ -0,0 +1,63 @@
<?php
/**
* Authenticated view/download endpoint for a generated qr code image.
* Replaces the previous direct static URL under saved_qrcode/, which any visitor
* could reach without logging in. Enforces the same visibility rules as the list
* pages (dynamic_qrcodes.php / static_qrcodes.php).
*/
require_once 'includes/bootstrap.php';
require_once BASE_PATH . '/includes/auth_validate.php';
$type = $_GET['type'] ?? '';
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!in_array($type, ['static', 'dynamic'], true) || !$id) {
http_response_code(404);
exit('Not found');
}
if ($_SESSION['type'] === 'user') {
$view_flag = $type === 'dynamic' ? 'can_view_dynamic' : 'can_view_static';
if (empty($_SESSION[$view_flag] ?? null)) {
http_response_code(403);
exit('Forbidden');
}
}
$db = getDbInstance();
$db->where('id', $id);
qr_apply_owner_scope($db);
$row = $db->getOne("{$type}_qrcodes");
if ($row === null) {
http_response_code(404);
exit('Not found');
}
$path = SAVED_QRCODE_DIRECTORY . $row['qrcode'];
if (!is_file($path)) {
http_response_code(404);
exit('Not found');
}
$mime_types = [
'png' => 'image/png',
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'svg' => 'image/svg+xml',
'eps' => 'application/postscript',
];
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
$mime = $mime_types[$extension] ?? 'application/octet-stream';
$is_download = isset($_GET['download']) && $_GET['download'] === '1';
header('Content-Type: ' . $mime);
header('Content-Length: ' . filesize($path));
header('Cache-Control: private, max-age=0, no-cache');
header('Content-Disposition: ' . ($is_download ? 'attachment' : 'inline') . '; filename="' . basename($path) . '"');
readfile($path);
exit;
+34
View File
@@ -0,0 +1,34 @@
<?php
/**
* Authenticated download endpoint for a bulk-export zip generated by bulk_action.php.
* The zip's contents were already permission-filtered when it was built, so this only
* requires a valid session plus proof that this specific file was generated for it.
*/
require_once 'includes/bootstrap.php';
require_once BASE_PATH . '/includes/auth_validate.php';
$file = basename($_GET['file'] ?? '');
if (!preg_match('/^qrcodes_[0-9a-f]+\.zip$/', $file)) {
http_response_code(404);
exit('Not found');
}
if (empty($_SESSION['generated_zips']) || !in_array($file, $_SESSION['generated_zips'], true)) {
http_response_code(403);
exit('Forbidden');
}
$path = SAVED_QRCODE_DIRECTORY . 'zip/' . $file;
if (!is_file($path)) {
http_response_code(404);
exit('Not found');
}
header('Content-Type: application/zip');
header('Content-Length: ' . filesize($path));
header('Content-Disposition: attachment; filename="' . $file . '"');
readfile($path);
exit;
Binary file not shown.

Before

Width:  |  Height:  |  Size: 545 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 295 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 558 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 447 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 539 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 398 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 895 B

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 462 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 298 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 629 B

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 14 KiB

View File
+3 -5
View File
@@ -18,11 +18,9 @@ require_once BASE_PATH . '/includes/search_order.php';
$page = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS) ?? 1; $page = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS) ?? 1;
$db->pageLimit = 15; $db->pageLimit = 15;
// 'user' ziet, net als 'super', alle codes (heeft zelf geen eigen codes om op te scopen). // Scoped to one admin's own codes for an admin (or a 'user' created by that admin);
if($_SESSION['type'] === 'admin') { // full visibility for super and company-wide 'user' accounts.
$db->where("id_owner", $_SESSION['user_id']); qr_apply_owner_scope($db);
$db->orWhere ("id_owner", NULL, 'IS');
}
$rows = $db->arraybuilder()->paginate('static_qrcodes', $page, $select); $rows = $db->arraybuilder()->paginate('static_qrcodes', $page, $select);
$total_pages = $db->totalPages; $total_pages = $db->totalPages;
+9 -2
View File
@@ -5,8 +5,8 @@ require_once BASE_PATH . '/lib/Users/Users.php';
$user_instance = new Users(); $user_instance = new Users();
if ($_SESSION['type'] !== 'super') if (!in_array($_SESSION['type'], ['super', 'admin'], true))
$user_instance->failure('Only a "super admin" account can access the admin listing page', 'Location: index.php'); $user_instance->failure('Only "super admin" and "admin" accounts can access the user management page', 'Location: index.php');
if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($_SERVER['REQUEST_METHOD'] === 'POST') {
csrf_verify_or_die(); csrf_verify_or_die();
@@ -16,6 +16,13 @@ $edit = false;
if($_SERVER["REQUEST_METHOD"] === "GET" && isset($_GET["edit"]) && $_GET["edit"] == "true" && isset($_GET["id"])) { if($_SERVER["REQUEST_METHOD"] === "GET" && isset($_GET["edit"]) && $_GET["edit"] == "true" && isset($_GET["id"])) {
$edit = true; $edit = true;
$user = $user_instance->getUser($_GET["id"]); $user = $user_instance->getUser($_GET["id"]);
// An admin may only open the edit form for their own 'user' accounts.
if ($_SESSION['type'] === 'admin' && (
$user['type'] !== 'user' || (int) $user['owner_admin_id'] !== (int) $_SESSION['user_id']
)) {
$user_instance->failure('You are not allowed to edit this user', 'Location: users.php');
}
} }
if($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["del_id"])) { if($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["del_id"])) {
+9 -2
View File
@@ -6,14 +6,21 @@ require_once BASE_PATH . '/lib/Users/Users.php';
$db = getDbInstance(); $db = getDbInstance();
$users = new Users(); $users = new Users();
if ($_SESSION['type'] !== 'super') if (!in_array($_SESSION['type'], ['super', 'admin'], true))
$users->failure('Only a "super admin" account can access the admin listing page', 'Location: index.php'); $users->failure('Only "super admin" and "admin" accounts can access the user management page', 'Location: index.php');
$select = array('id', 'username', 'type'); $select = array('id', 'username', 'type');
$search_fields = array('username'); $search_fields = array('username');
require_once BASE_PATH . '/includes/search_order.php'; require_once BASE_PATH . '/includes/search_order.php';
$page = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS) ?? 1; $page = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS) ?? 1;
$db->pageLimit = 15; $db->pageLimit = 15;
// An admin only sees the read-only 'user' accounts they created themselves.
if ($_SESSION['type'] === 'admin') {
$db->where('owner_admin_id', $_SESSION['user_id']);
$db->where('type', 'user');
}
$rows = $db->arraybuilder()->paginate('users', $page, $select); $rows = $db->arraybuilder()->paginate('users', $page, $select);
$total_pages = $db->totalPages; $total_pages = $db->totalPages;
?> ?>