Compare commits

...

55 Commits

Author SHA1 Message Date
Aiirondev_dev 46f79b002b Changes to the admin_damaged_items 2026-07-31 21:40:20 +02:00
Aiirondev_dev dcc8aae650 Implemenmtation of the new encryption into the my borrowed funktion 2026-07-31 21:28:34 +02:00
Aiirondev_dev c9fdf41e0b Implemenmtation of the new encryption into the my borrowed funktion 2026-07-31 21:21:43 +02:00
Aiirondev_dev 3e26c691b1 Addition of backwarts compatibility 2026-07-31 20:57:19 +02:00
Aiirondev_dev 6c3d62e84b Fix of a NoneType has no attribute 'get' Error 2026-07-31 20:50:58 +02:00
Aiirondev_dev 88f6c3c0f5 backwarts compaibility and integration of encryption in the manage-tenant.sh 2026-07-31 20:45:16 +02:00
Aiirondev_dev 08d8b78d91 changes to the encryption to the users and Items 2026-07-31 20:16:34 +02:00
Aiirondev_dev 258e287a39 changes to the encryption to the users and Items 2026-07-31 19:55:59 +02:00
Aiirondev_dev 9b12d9a3d0 changes to the encryption to the users and Items 2026-07-31 15:15:09 +02:00
Aiirondev_dev 237788af96 implementation of encryption for the username to avoid any recognission potetioal 2026-07-31 13:12:46 +02:00
Aiirondev_dev 7368d82fc4 changes to fully incorpereate the school info managment back into the working system 2026-07-30 23:55:46 +02:00
Aiirondev_dev 3e5e243ddf changes to the autorisation system for the page autorisation to have a continued line of page authentification and no discrepencies in the Software it self 2026-07-30 23:34:06 +02:00
Aiirondev_dev 8176cea8fe change of the HTML Signature 2026-07-30 16:52:34 +02:00
Aiirondev_dev b71f2e9089 changes 2026-07-30 01:09:58 +02:00
Aiirondev_dev 1331afa4da Fix of hexdigest 2026-07-29 13:40:17 +02:00
Aiirondev_dev 5a2d703bc7 Debug of Vapid Keys 2026-07-29 13:35:15 +02:00
Aiirondev_dev 8e6dd17243 Fix of the notification subscription 2026-07-29 11:57:34 +02:00
Aiirondev_dev 2124ca65b2 Fix of the notification subscription 2026-07-29 11:49:54 +02:00
Aiirondev_dev bc86dc4a0d Fix of the notification subscription 2026-07-29 11:43:18 +02:00
Aiirondev_dev a49ed98ed7 Fix of the notification subscription 2026-07-29 11:35:04 +02:00
Aiirondev_dev 4d9bb62907 Fix of the notification subscription 2026-07-29 11:15:57 +02:00
Aiirondev_dev 8251cd9bfd Fix of a dubled function 2026-07-29 00:22:35 +02:00
Aiirondev_dev 3ed3148b8a Fix of the notifikationssystem 2026-07-29 00:10:12 +02:00
Aiirondev_dev 27b265eaf5 Addition of a missing Funktion 2026-07-29 00:03:14 +02:00
Aiirondev_dev 3571bb6f6d Fix of the Notifications Funktions and the notifications system in generell in regarts to the Vapid key handeling 2026-07-28 23:46:15 +02:00
Aiirondev_dev b037434e89 fix correct VAPID key loading and public key assignment when PEM files exist 2026-07-28 23:21:35 +02:00
Aiirondev_dev ad14499df0 fix of the direction for _match_mail 2026-07-28 22:43:12 +02:00
Aiirondev_dev 6f50fb2263 Changes from old deployment system to new dynamic one 2026-07-28 22:09:40 +02:00
Aiirondev_dev a1c5a78b20 Changes for the System to accept the changes 2026-07-28 21:53:48 +02:00
Aiirondev_dev 38320f488a patch for the Secret Getting that is not functioning 2026-07-28 21:47:37 +02:00
Aiirondev_dev 2aee36cc92 Updates to the Update Group logic to have a cleaner output 2026-07-28 21:23:21 +02:00
Aiirondev_dev aa2ad37cd7 Changes ti the release to fiy an issue 2026-07-28 21:01:05 +02:00
Aiirondev_dev 315918098d Changes of the settings.py and in generell the Variable Proccessing to have a more secure deployment Process 2026-07-28 20:52:05 +02:00
Aiirondev_dev ea402f3223 Changes to the mail sending system to allow for a more fluent proccessing of the mails in regarts to the rate limiting 2026-07-28 19:03:15 +02:00
Aiirondev_dev 70b108d841 Changes 2026-07-27 23:49:30 +02:00
Aiirondev_dev fc53333436 Oke 2026-07-27 23:49:30 +02:00
Aiirondev_dev 33ae7ee1ac removal of unused legal files from old gh repo 2026-07-27 22:42:21 +02:00
Aiirondev_dev 16962b20b6 Add of descryption of for the removal of big tmp files 2026-07-27 21:17:51 +02:00
Aiirondev_dev 6fcabc8638 changes to the open Damage Invoice Modal 2026-07-27 21:13:18 +02:00
Aiirondev_dev 3068f44563 implementet automatic including of the price 2026-07-27 20:16:53 +02:00
Aiirondev_dev c4dd18a2e4 change to have automatic clearing of the tmp directory 2026-07-27 15:30:34 +02:00
Aiirondev_dev d0ac21e7dd changes to the Library Type 2026-07-27 15:20:27 +02:00
Aiirondev_dev b4a505c20b changes to the borrow_record creation 2026-07-27 15:09:26 +02:00
Aiirondev_dev 39302d4d1f CHanges to the In and out 2026-07-27 14:53:09 +02:00
Aiirondev_dev e46f8b0c66 finisch of the borrower funktion 2026-07-27 14:43:39 +02:00
Aiirondev_dev 06486f039f changes for the loading of the recent borrowers that only the latest 3 get displayed 2026-07-27 14:34:59 +02:00
Aiirondev_dev feac00f0df changes to the permission development 2026-07-27 14:19:01 +02:00
Aiirondev_dev 0b0169ef96 made the Cookie Banner accoding to the ePrivacy-Richtlinie/TTDSG only a visual informative banner 2026-07-27 11:35:12 +02:00
Aiirondev_dev a6db3a001f changes to maybe have the right passtword 2026-07-27 00:32:21 +02:00
Aiirondev_dev 8fa495a23c changes to allow a easier register process 2026-07-26 23:52:08 +02:00
Aiirondev_dev 9df7a73db1 change to the CRFS 2026-07-26 23:45:49 +02:00
Aiirondev_dev dcfd23b412 changes to work 2026-07-26 23:21:56 +02:00
Aiirondev_dev d523dd0a68 change to allow for the wtf tocken to be read in correctly 2026-07-26 23:08:47 +02:00
Aiirondev_dev d7d96d5567 changes to the register Funktion 2026-07-26 22:56:39 +02:00
Aiirondev_dev a0018eebd5 slight mistake because of disregard for the new package that needs to be in the requirements 2026-07-26 22:37:45 +02:00
30 changed files with 1345 additions and 2159 deletions
-8
View File
@@ -1,8 +0,0 @@
services:
app:
working_dir: /app/Web
command: ["gunicorn", "app:app", "--bind", "0.0.0.0:8000", "--workers", "4", "--threads", "2", "--timeout", "30", "--graceful-timeout", "20", "--worker-connections", "100", "--max-requests", "1000", "--max-requests-jitter", "100", "--log-level", "info", "--access-logfile", "-", "--error-logfile", "-"]
image: ghcr.io/aiirondev/legendary-octo-garbanzo:v0.7.42
build: null
ports:
- "10000:8000"
+91 -128
View File
@@ -25,7 +25,6 @@ env:
jobs:
release-docker:
# Hinweis: Falls dein lokaler Gitea-Runner ein anderes Label hat (z.B. 'linux' oder 'self-hosted'), passe dies hier an.
runs-on: ubuntu-latest
steps:
@@ -35,7 +34,6 @@ jobs:
- name: Set metadata
id: meta
env:
# Gitea stellt das GITHUB_TOKEN für Kompatibilität mit GitHub Actions automatisch zur Verfügung
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPO: ${{ gitea.repository }}
EVENT_NAME: ${{ gitea.event_name }}
@@ -46,7 +44,6 @@ jobs:
if [ "$EVENT_NAME" = "push" ] && [ -n "$REF_NAME" ]; then
TAG="$REF_NAME"
else
# Gitea API Endpunkt nutzen, um das aktuellste Release abzufragen
latest_tag="v0.8.31"
if meta_json=$(curl -fsSL -H "Authorization: Bearer $GH_TOKEN" -H "Accept: application/json" "https://git.invario-software.eu/api/v1/repos/$REPO/releases/latest" 2>/dev/null); then
tag_name=$(printf "%s" "$meta_json" | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n1)
@@ -63,7 +60,6 @@ jobs:
major=0; minor=8; patch=31
fi
# Bump strategy: major / minor / patch
if [ "${BUMP_TYPE:-}" = "major" ]; then
major=$((major + 1)); minor=0; patch=0
elif [ "${BUMP_TYPE:-}" = "minor" ]; then
@@ -72,11 +68,9 @@ jobs:
patch=$((patch + 1))
fi
# Zusammenbau des Tags für den manuellen Run
TAG="v${major}.${minor}.${patch}"
fi
# Validierung des erzeugten oder übergebenen Tags
if ! echo "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+(-dev(\.[0-9]+)?)?$'; then
echo "Error: tag '$TAG' is not valid semver (vX.Y.Z)"
exit 1
@@ -95,13 +89,11 @@ jobs:
LATEST_MAJOR="0"
fi
# If not explicitly bumping major, disallow changing major version
if [ "${BUMP_TYPE:-}" != "major" ] && [ "$TAG_MAJOR" != "$LATEST_MAJOR" ]; then
echo "Error: major version must stay v$LATEST_MAJOR.x.x (got $TAG)"
exit 1
fi
# Ensure tag uniqueness: if tag exists append numeric suffix
if git rev-parse -q --verify "refs/tags/$TAG" >/dev/null; then
i=1
base="$TAG"
@@ -111,24 +103,18 @@ jobs:
TAG="${base}.${i}"
fi
# Docker Images verlangen Kleinbuchstaben. Repository-Namen daher umwandeln.
LOWER_REPO=$(echo "$REPO" | tr '[:upper:]' '[:lower:]')
IMAGE="git.invario-software.eu/${LOWER_REPO}:${TAG}"
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "image=$IMAGE" >> "$GITHUB_OUTPUT"
echo "lower_repo=$LOWER_REPO" >> "$GITHUB_OUTPUT"
- name: Ensure Docker CLI is available and up to date
run: |
install_docker=true
# Prüfen, ob Docker existiert und ob die Version ausreicht
if command -v docker >/dev/null 2>&1; then
# Extrahiere die Major-Version
DOCKER_MAJOR=$(docker --version | grep -oE '[0-9]+' | head -n1)
# API 1.44 erfordert mindestens Docker v25
if [ -n "$DOCKER_MAJOR" ] && [ "$DOCKER_MAJOR" -ge 25 ]; then
install_docker=false
fi
@@ -136,34 +122,19 @@ jobs:
if [ "$install_docker" = true ]; then
echo "Veraltete oder fehlende Docker-Installation erkannt. Lade statische Docker CLI herunter..."
DOCKER_VERSION="26.1.4"
# Download der statischen Binaries via curl oder wget (umgeht apt-get komplett)
if command -v curl >/dev/null 2>&1; then
curl -fsSLO "https://download.docker.com/linux/static/stable/x86_64/docker-${DOCKER_VERSION}.tgz"
else
wget -q "https://download.docker.com/linux/static/stable/x86_64/docker-${DOCKER_VERSION}.tgz"
fi
tar -xzf docker-${DOCKER_VERSION}.tgz
# Installation in lokalen Benutzer-Pfad, um sudo/root-Rechte-Probleme zu vermeiden
mkdir -p "$HOME/.local/bin"
cp docker/docker "$HOME/.local/bin/"
# Pfad für nachfolgende GitHub Actions Schritte verfügbar machen
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
# Pfad für diesen spezifischen Shell-Run exportieren
export PATH="$HOME/.local/bin:$PATH"
rm -rf docker docker-${DOCKER_VERSION}.tgz
echo "Docker CLI wurde erfolgreich aktualisiert."
else
echo "Docker CLI ist bereits auf einem aktuellen Stand."
fi
docker --version
- name: Set up Docker Buildx
@@ -186,109 +157,101 @@ jobs:
${{ steps.meta.outputs.image }}
git.invario-software.eu/${{ steps.meta.outputs.lower_repo }}:latest
- name: Build local image tar for offline deploy
run: |
set -euo pipefail
IMG="${{ steps.meta.outputs.image }}"
TAG="${{ steps.meta.outputs.tag }}"
echo "Pulling freshly pushed image from registry: $IMG"
docker pull "$IMG"
echo "Saving image to offline tar archive..."
docker save "$IMG" | gzip > "inventarsystem-image-${TAG}.tar.gz"
- name: Create release-only docker bundle
run: |
mkdir -p release-bundle
cat > release-bundle/docker-compose.yml <<EOF
services:
app:
image: \${INVENTAR_APP_IMAGE:-${{ steps.meta.outputs.image }}}
container_name: inventarsystem-app
restart: unless-stopped
ports:
- "\${INVENTAR_HTTP_PORT:-10000}:8000"
depends_on:
- mongodb
- redis
environment:
INVENTAR_MONGODB_HOST: mongodb
INVENTAR_MONGODB_PORT: "27017"
INVENTAR_MONGODB_DB: Inventarsystem
INVENTAR_BACKUP_FOLDER: /data/backups
INVENTAR_LOGS_FOLDER: /data/logs
expose:
- "8000"
volumes:
- ./config.json:/app/config.json:ro
- app_uploads:/app/Web/uploads
- app_thumbnails:/app/Web/thumbnails
- app_previews:/app/Web/previews
- app_qrcodes:/app/Web/QRCodes
- app_backups:/data/backups
- app_logs:/data/logs
mongodb:
image: mongo:7.0
container_name: inventarsystem-mongodb
restart: unless-stopped
volumes:
- mongodb_data:/data/db
healthcheck:
test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand('ping').ok"]
interval: 10s
timeout: 5s
retries: 10
redis:
image: redis:7-alpine
container_name: inventarsystem-redis
restart: unless-stopped
command: redis-server --appendonly yes --maxmemory 512mb --maxmemory-policy allkeys-lru
ports:
- "6379:6379"
volumes:
- redis_data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
volumes:
mongodb_data:
app_uploads:
app_thumbnails:
app_previews:
app_qrcodes:
app_backups:
app_logs:
redis_data:
EOF
# Copy runtime scripts and config if present
for f in start.sh stop.sh restart.sh backup.sh restore.sh config.json update.sh; do
if [ -f "$f" ]; then
cp "$f" "release-bundle/$(basename "$f")"
fi
done
# Multitenant scripts & docs (optional)
for f in docker-compose-multitenant.yml manage-tenant.sh run-tenant-cmd.sh MULTITENANT_DEPLOYMENT.md MULTITENANT_PYTHON_API.md; do
if [ -f "$f" ]; then
cp "$f" "release-bundle/$(basename "$f")"
fi
done
# Make any shipped scripts executable
find release-bundle -maxdepth 1 -type f -name '*.sh' -exec chmod +x {} \; || true
tar -czf inventarsystem-docker-bundle.tar.gz -C release-bundle .
mkdir -p release-bundle
cat > release-bundle/docker-compose.yml <<EOF
services:
app:
image: \${INVENTAR_APP_IMAGE:-${{ steps.meta.outputs.image }}}
container_name: inventarsystem-app
restart: unless-stopped
ports:
- "\${INVENTAR_HTTP_PORT:-10000}:8000"
depends_on:
- mongodb
- redis
environment:
INVENTAR_MONGODB_HOST: mongodb
INVENTAR_MONGODB_PORT: "27017"
INVENTAR_MONGODB_DB: Inventarsystem
INVENTAR_BACKUP_FOLDER: /data/backups
INVENTAR_LOGS_FOLDER: /data/logs
INVENTAR_SECRET_KEY: ${{secrets.INVENTAR_SECRET_KEY}}
INVENTAR_DATA_ENCRYPTION_KEY: ${{secrets.INVENTAR_DATA_ENCRYPTION_KEY}}
INVENTAR_MONGODB_PASSWORD: ${{secrets.INVENTAR_MONGODB_PASSWORD}}
EMAIL_ENABLED: ${{secrets.EMAIL_ENABLED}}
EMAIL_SMTP_HOST: ${{secrets.EMAIL_SMTP_HOST}}
EMAIL_SMTP_PORT: ${{secrets.EMAIL_SMTP_PORT}}
EMAIL_USERNAME: ${{secrets.EMAIL_USERNAME}}
EMAIL_PASSWORD: ${{secrets.EMAIL_PASSWORD}}
expose:
- "8000"
volumes:
- ./config.json:/app/config.json:ro
- app_uploads:/app/Web/uploads
- app_thumbnails:/app/Web/thumbnails
- app_previews:/app/Web/previews
- app_qrcodes:/app/Web/QRCodes
- app_backups:/data/backups
- app_logs:/data/logs
mongodb:
image: mongo:7.0
container_name: inventarsystem-mongodb
restart: unless-stopped
volumes:
- mongodb_data:/data/db
healthcheck:
test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand('ping').ok"]
interval: 10s
timeout: 5s
retries: 10
redis:
image: redis:7-alpine
container_name: inventarsystem-redis
restart: unless-stopped
command: redis-server --appendonly yes --maxmemory 512mb --maxmemory-policy allkeys-lru
ports:
- "6379:6379"
volumes:
- redis_data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
volumes:
mongodb_data:
app_uploads:
app_thumbnails:
app_previews:
app_qrcodes:
app_backups:
app_logs:
redis_data:
EOF
for f in start.sh stop.sh restart.sh backup.sh restore.sh config.json update.sh; do
if [ -f "$f" ]; then
cp "$f" "release-bundle/$(basename "$f")"
fi
done
for f in docker-compose-multitenant.yml manage-tenant.sh run-tenant-cmd.sh MULTITENANT_DEPLOYMENT.md MULTITENANT_PYTHON_API.md; do
if [ -f "$f" ]; then
cp "$f" "release-bundle/$(basename "$f")"
fi
done
find release-bundle -maxdepth 1 -type f -name '*.sh' -exec chmod +x {} \; || true
tar -czf inventarsystem-docker-bundle.tar.gz -C release-bundle .
- name: Create or update Gitea Release
uses: https://gitea.com/actions/gitea-release-action@v1
with:
tag_name: ${{ steps.meta.outputs.tag }}
files: |
inventarsystem-docker-bundle.tar.gz
inventarsystem-image-${{ steps.meta.outputs.tag }}.tar.gz
inventarsystem-docker-bundle.tar.gz
+1
View File
@@ -3,6 +3,7 @@ logs
certs
build
.venv
.idea
__pycache__
.pycvapid.json
Web/vapid.json
-1
View File
@@ -1 +0,0 @@
v0.8.31.1
-128
View File
@@ -1,128 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
Iron.ai.dev@gmail.com.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
-55
View File
@@ -1,55 +0,0 @@
# Endbenutzer-Lizenzvertrag (EULA) und Nutzungsbedingungen
**Softwareprojekt:** Inventarsystem
**Urheberrechtshalter (Lizenzgeber):** Maximilian Gründinger
**Gültigkeit:** Stand 2026
---
### PRÄAMBEL
Dieser Endbenutzer-Lizenzvertrag (im Folgenden „Vertrag“) stellt eine rechtsgültige Vereinbarung zwischen Ihnen (im Folgenden „Lizenznehmer“) und dem Urheber **AIIrondev** (im Folgenden „Lizenzgeber“) dar. Durch den Zugriff auf den Quellcode, die Installation, das Kopieren oder die sonstige Nutzung der Software „Inventarsystem“ (im Folgenden „Produkt“) erklärt sich der Lizenznehmer mit den nachfolgenden Bedingungen vollumfänglich einverstanden.
Sollte der Lizenznehmer den Bedingungen dieses Vertrags nicht zustimmen, ist jegliche Nutzung, Vervielfältigung oder Distribution des Produkts mit sofortiger Wirkung untersagt.
---
### § 1 GEGENSTAND DER LIZENZ UND EIGENTUMSRECHTE
1. Das Produkt wird dem Lizenznehmer unter Vorbehalt lizenziert, nicht verkauft. Sämtliche Eigentumsrechte, Urheberrechte und sonstigen geistigen Eigentumsrechte am Produkt sowie an allen Kopien davon verbleiben ausschließlich beim Lizenzgeber.
2. Diese Lizenz gewährt lediglich ein eingeschränktes Nutzungsrecht unter den in diesem Vertrag explizit genannten Bedingungen.
### § 2 ZULÄSSIGER NUTZUNGSKREIS (PRIVATNUTZUNG)
1. Die unentgeltliche Nutzung des Produkts ist ausschließlich **natürlichen Personen für den rein privaten, häuslichen Gebrauch** gestattet.
2. Die Nutzung umfasst die Verwaltung privater Bestände ohne jegliche Gewinnerzielungsabsicht.
3. Jegliche Nutzung durch **Institutionelle Nutzer** (einschließlich, aber nicht beschränkt auf: Unternehmen, Einzelunternehmer, Freiberufler, Vereine, Bildungseinrichtungen, Behörden oder NGOs) ist ausdrücklich **untersagt** und bedarf einer gesonderten, schriftlichen Lizenzvereinbarung mit dem Lizenzgeber.
### § 3 FUNKTIONALE EINSCHRÄNKUNGEN UND SUPPORT
1. Dem Lizenznehmer wird das Produkt in der jeweils vorliegenden Fassung bereitgestellt („As-Is“).
2. Für die kostenlose Privatnutzung besteht **kein Anspruch** auf:
- Technischen Support oder Beratung.
- Bereitstellung von Sicherheits-Updates oder Patches.
- Gewährleistung der Kompatibilität mit spezifischen Hardware- oder Softwareumgebungen.
3. Der Lizenzgeber behält sich das Recht vor, Funktionen in zukünftigen Versionen zu ändern, einzuschränken oder kostenpflichtig zu gestalten.
### § 4 WAHRUNG DER URHEBERBEZEICHNUNG (BRANDING-KLAUSEL)
1. Das Produkt verfügt über fest integrierte Urheberrechtshinweise, insbesondere die Kennzeichnung **„Powered by AIIrondev“** in der Benutzeroberfläche (Footer/Menü).
2. Es ist dem Lizenznehmer untersagt, diese Hinweise zu entfernen, zu modifizieren, zu verdecken oder deren Sichtbarkeit durch technische Maßnahmen (z. B. Manipulation von CSS, JavaScript oder Metadaten) zu beeinträchtigen.
3. Das Entfernen dieser Hinweise führt zum sofortigen und automatischen Erlöschen der Nutzungslizenz.
### § 5 VERBOT DER KOMMERZIELLEN VERWERTUNG & SAAS
1. Die Bereitstellung des Produkts als Dienstleistung für Dritte (Software-as-a-Service, SaaS), insbesondere gegen Entgelt oder zur Generierung von Werbeeinnahmen, ist strikt untersagt.
2. Das Hosting auf öffentlichen Servern mit dem Ziel, Dritten ohne eigene Installation Zugriff auf die Funktionalität zu gewähren, ist nur mit ausdrücklicher schriftlicher Genehmigung des Lizenzgebers zulässig.
### § 6 MODIFIKATIONEN UND CONTRIBUTIONS
1. Der Lizenznehmer darf den Quellcode für den privaten Eigenbedarf modifizieren.
2. Im Falle einer Veröffentlichung von Modifikationen oder der Einreichung von Verbesserungsvorschlägen (z. B. Pull Requests auf GitHub) räumt der Lizenznehmer dem Lizenzgeber ein unwiderrufliches, weltweites, zeitlich unbeschränktes und kostenfreies Nutzungs- und Verwertungsrecht an diesen Änderungen ein. Der Lizenzgeber ist berechtigt, diese Änderungen in das Hauptprodukt zu übernehmen und unter dieser oder einer anderen Lizenz zu vertreiben.
### § 7 HAFTUNGSBESCHRÄNKUNG
1. Die Haftung des Lizenzgebers für Schäden, die aus der Nutzung oder Unmöglichkeit der Nutzung des Produkts entstehen (einschließlich Datenverlust, Betriebsunterbrechung oder entgangener Gewinn), ist auf Vorsatz und grobe Fahrlässigkeit beschränkt.
2. Der Lizenzgeber übernimmt keine Haftung für die Richtigkeit der mit dem Produkt verwalteten Daten.
### § 8 RECHTSWAHL UND GERICHTSSTAND
1. Es gilt ausschließlich das Recht der **Bundesrepublik Deutschland** unter Ausschluss des UN-Kaufrechts (CISG).
2. Soweit gesetzlich zulässig, wird als Gerichtsstand für alle Streitigkeiten aus diesem Vertrag der Sitz des Lizenzgebers vereinbart.
3. Sollten einzelne Bestimmungen dieses Vertrags unwirksam sein, bleibt die Wirksamkeit der übrigen Bestimmungen unberührt (Salvatorische Klausel).
---
**ANFRAGEN FÜR AUSNAHMEGENEHMIGUNGEN (KOMMERZIELLE LIZENZEN):** Bitte kontaktieren Sie den Urheber direkt über das GitHub-Profil: [AIIrondev auf GitHub](https://github.com/AIIrondev)
-38
View File
@@ -1,38 +0,0 @@
Release-Optionen
=================
Diese Datei beschreibt die Eingabeoptionen des CI-Workflows `.github/workflows/release-docker.yml`.
Inputs (workflow_dispatch)
- `bump` (choice)
- `patch` (Standard): Erhöht nur die Patch-Version (vX.Y.Z -> vX.Y.Z+1).
- `minor`: Erhöht die Minor-Version und setzt Patch auf 0 (vX.Y.Z -> vX.Y+1.0).
- `major`: Erhöht die Major-Version und setzt Minor/Patch auf 0 (vX.Y.Z -> vX+1.0.0).
- `development`: Erzeugt einen Development-Release mit Suffix `-dev` (z. B. `v3.1.4-dev`).
- `push_dev` (choice, optional)
- `false` (Standard): Bei `bump=development` wird das `:dev`-Image NICHT automatisch an GHCR gepusht.
- `true`: Bei `bump=development` wird zusätzlich das Image `ghcr.io/aiirondev/legendary-octo-garbanzo:dev` gepusht.
Verhalten/Anmerkungen
- Development releases werden als GitHub Release erzeugt und als `prerelease` markiert, damit sie nicht automatisch von normalen UpdateFlows genutzt werden.
- Es gibt pro Release genau einen ReleaseEintrag (für DevReleases mit `-dev` Suffix). Es wird kein separates `inventarsystem-image-dev.tar.gz` mehr erzeugt; das Update/Deployment erfolgt über den ReleaseTag / ImageTag.
- `update.sh` unterstützt weiterhin `dev`/`development`-Modus und akzeptiert nun auch explizite ReleaseTags wie `v3.1.4-dev`.
Beispiele
- Patch-Release (manuell):
- GitHub UI: Run workflow → `bump=patch`
- CLI mit `gh`:
gh workflow run release-docker.yml --repo AIIrondev/legendary-octo-garbanzo --field bump=patch
- Development prerelease (ohne Push des :dev Images):
- GitHub UI: Run workflow → `bump=development` (leave `push_dev=false`)
- Ergebnis: Release `vX.Y.Z-dev` als prerelease, Image wird nicht automatisch als `:dev` gepusht.
- Development prerelease + push des :dev Images:
- GitHub UI: Run workflow → `bump=development`, `push_dev=true`
- CLI Beispiel:
gh workflow run release-docker.yml --repo AIIrondev/legendary-octo-garbanzo --field bump=development --field push_dev=true
Empfehlung
- Verwende `bump=development` für experimentelle/early releases; Nutzer müssen explizit `./update.sh vX.Y.Z-dev` ausführen, um auf diese Version zu upgraden.
-25
View File
@@ -1,25 +0,0 @@
# Security Policy
## Supported Versions
The latest version will allways be supported the rest are old version that are not activly supported.
| Version | Supported |
| ------- | ------------------ |
| 0.2.17 | ✅ |
| 3.2.x | :white_check_mark: |
| 3.1.x | :x: |
| 3.0.x | :x: |
| 2.6.x | :x: |
| 2.4.x | :x: |
| 1.8.x | :x: |
| 1.7.x | :x: |
| 1.5.x | :x: |
| 1.4.x | :x: |
| 1.3.x | :x: |
| 1.1.x | :x: |
## Reporting a Vulnerability
To report a vulnerability contact me via. my E-Mail Iron.ai.dev@gmail.com or in insevere cases over an Issue.
+253 -264
View File
@@ -18,7 +18,6 @@ Features:
"""
from flask import Flask, render_template, request, redirect, url_for, session, flash, send_from_directory, get_flashed_messages, jsonify, Response, make_response, send_file, abort
from flask_wtf.csrf import CSRFProtect
from werkzeug.utils import secure_filename
from werkzeug.middleware.proxy_fix import ProxyFix
from werkzeug.exceptions import HTTPException
@@ -116,7 +115,6 @@ app.config['PREFERRED_URL_SCHEME'] = 'https' if app.config['SESSION_COOKIE_SECUR
# app.config['QR_CODE_FOLDER'] = cfg.QR_CODE_FOLDER # QR Code storage deactivated
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_port=1)
app.register_blueprint(terminplaner_bp, url_prefix='/terminplaner')
csrf = CSRFProtect(app)
"""--------------------------------------------------------------Path Init-------------------------------------------------------"""
@@ -1826,9 +1824,9 @@ def _excel_list(value):
seen = set()
unique = []
for entry in cleaned:
if entry not in seen:
if str(entry) not in seen:
unique.append(entry)
seen.add(entry)
seen.add(str(entry))
return unique
@@ -3159,6 +3157,7 @@ def library_loans_admin():
'damage_text': (damage_reports[0].get('description', '') if damage_reports else ''),
'available': bool(item_doc.get('Verfuegbar', False)),
'last_updated': fmt_dt(item_doc.get('LastUpdated')),
'acquisition_costs': item_doc.get('Anschaffungskosten', "")
})
return render_template(
@@ -3607,7 +3606,8 @@ def api_item_detail(item_id):
borrows_html = ''
if borrow_records:
rows = []
for rec in borrow_records:
for rec in borrow_records[:3]:
user_raw = rec.get('User')
try:
user = decrypt_text(user_raw) if user_raw is not None else ''
@@ -3617,7 +3617,6 @@ def api_item_detail(item_id):
start = fmt_dt(rec.get('Start'))
end = fmt_dt(rec.get('End'))
notes = html.escape(str(rec.get('Notes') or ''))
rows.append(
f"<li><strong>{html.escape(str(user or '-'))}</strong> — "
f"{html.escape(str(status))}"
@@ -6738,6 +6737,8 @@ def update_group():
{'$set': shared_update}
)
app.logger.debug(f"Individual Codes: {individual_items}")
# B. Apply Unique Codes to specific items
# We iterate through the provided list to update the specific code for each ID
for item in individual_items:
@@ -6751,6 +6752,8 @@ def update_group():
)
client.close()
app.logger.debug("Success When Updating the Item")
flash("Objekte wurden erfolgreich Bearbeitet", "success")
return jsonify({'success': True, 'message': 'Gruppe und individuelle Codes aktualisiert'})
except Exception as e:
@@ -7905,66 +7908,69 @@ def terminplan():
@app.route('/register', methods=['GET', 'POST'])
def register():
"""
User registration route.false
User registration route.
Returns:
flask.Response: Rendered template or redirect
"""
if 'username' not in session:
flash('Ihnen ist es nicht gestattet auf dieser Internetanwendung, die eben besuchte Adrrese zu nutzen, versuchen sie es erneut nach dem sie sich mit einem berechtigten Nutzer angemeldet haben!', 'error')
flash('Ihnen ist es nicht gestattet auf dieser Internetanwendung, die eben besuchte Adresse zu nutzen, versuchen Sie es erneut, nachdem Sie sich mit einem berechtigten Nutzer angemeldet haben!', 'error')
return redirect(url_for('login'))
if 'username' in session:
if request.method == 'POST':
password = request.form['password']
name = (request.form.get('name') or '').strip()
last_name = (request.form.get('last-name') or '').strip()
if request.method == 'POST':
password = request.form['password']
name = (request.form.get('name') or '').strip()
last_name = (request.form.get('last-name') or '').strip()
# Generate a username from the first 3 letters of first and last name.
username = us.build_unique_username_from_name(name, last_name)
username = us.build_unique_username_from_name(name, last_name)
permission_preset = (request.form.get('permission_preset') or 'standard_user').strip()
use_custom_permissions = request.form.get('use_custom_permissions') == 'on'
if not username or not password or not name or not last_name:
flash('Bitte füllen Sie alle Felder aus', 'error')
return redirect(url_for('register'))
permission_preset = (request.form.get('permission_preset') or 'standard_user').strip()
use_custom_permissions = request.form.get('use_custom_permissions') == 'on'
if not us.check_password_strength(password):
flash('Passwort ist zu schwach oder entspricht nicht den Richtlinien', 'error')
return redirect(url_for('register'))
action_permissions = None
page_permissions = None
if use_custom_permissions:
action_permissions = {}
for action_key, _ in PERMISSION_ACTION_OPTIONS:
action_permissions[action_key] = request.form.get(f'action_{action_key}') == 'on'
page_permissions = {}
for endpoint_name, _ in PERMISSION_PAGE_OPTIONS:
page_permissions[endpoint_name] = request.form.get(f'page_{endpoint_name}') == 'on'
if not username or not password or not name or not last_name:
flash('Bitte füllen Sie alle Felder aus', 'error')
return redirect(url_for('register'))
if not us.check_password_strength(password):
flash('Passwort ist zu schwach', 'error')
return redirect(url_for('register'))
action_permissions = None
page_permissions = None
if use_custom_permissions:
action_permissions = {}
for action_key, _ in PERMISSION_ACTION_OPTIONS:
action_permissions[action_key] = request.form.get(f'action_{action_key}') == 'on'
page_permissions = {}
for endpoint_name, _ in PERMISSION_PAGE_OPTIONS:
page_permissions[endpoint_name] = request.form.get(f'page_{endpoint_name}') == 'on'
us.add_user(
username,
password,
name,
last_name,
is_student=False,
student_card_id=None,
max_borrow_days=None,
permission_preset=permission_preset,
action_permissions=action_permissions,
page_permissions=page_permissions,
)
return redirect(url_for('home_admin'))
return render_template(
'register.html',
library_module_enabled=cfg.MODULES.is_enabled('library'),
student_cards_module_enabled=cfg.MODULES.is_enabled('student_cards'),
student_default_borrow_days=cfg.STUDENT_DEFAULT_BORROW_DAYS,
student_max_borrow_days=cfg.STUDENT_MAX_BORROW_DAYS
us.add_user(
username,
password,
name,
last_name,
is_student=False,
student_card_id=None,
max_borrow_days=None,
permission_preset=permission_preset,
action_permissions=action_permissions,
page_permissions=page_permissions,
)
flash('Sie sind nicht berechtigt, diese Seite anzuzeigen', 'error')
return redirect(url_for('login'))
flash(f'Benutzer "{username}" wurde erfolgreich registriert!', 'success')
return redirect(url_for('home_admin'))
return render_template(
'register.html',
library_module_enabled=cfg.MODULES.is_enabled('library'),
student_cards_module_enabled=cfg.MODULES.is_enabled('student_cards'),
student_default_borrow_days=cfg.STUDENT_DEFAULT_BORROW_DAYS,
student_max_borrow_days=cfg.STUDENT_MAX_BORROW_DAYS,
permission_presets=getattr(us, 'PERMISSION_PRESETS', {}),
permission_action_options=PERMISSION_ACTION_OPTIONS,
permission_page_options=PERMISSION_PAGE_OPTIONS
)
@app.route('/user_del', methods=['GET'])
def user_del():
@@ -10242,74 +10248,58 @@ def get_period_times(booking_date, period_num):
"""---------------------------------------------------------Borrowing-----------------------------------------------------------------"""
@app.route('/my_borrowed_items')
def my_borrowed_items():
"""
Zeigt alle vom aktuellen Benutzer ausgeliehenen und geplanten Objekte an.
Returns:
Response: Gerendertes Template mit den ausgeliehenen und geplanten Objekten des Benutzers
"""
if 'username' not in session:
flash('Bitte melden Sie sich an, um Ihre ausgeliehenen Objekte anzuzeigen', 'error')
return redirect(url_for('login', next=request.path))
username = session['username']
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
db = client[MONGODB_DB]
items_collection = db.items
ausleihungen_collection = db.ausleihungen
# Get current time for comparison
current_time = datetime.datetime.now()
# Check if user is admin
user_is_admin = False
if 'is_admin' in session:
user_is_admin = session['is_admin']
# Get items currently borrowed by the user (where Verfuegbar=false and User=username)
borrowed_items = list(items_collection.find({'Verfuegbar': False, 'User': username}))
# Get active and planned ausleihungen for the user
active_ausleihungen = list(ausleihungen_collection.find({
'User': username,
'Status': 'active'
items_collection = db['items']
ausleihungen_collection = db['ausleihungen']
all_ausleihungen = list(ausleihungen_collection.find({
'Status': {'$in': ['active', 'planned']}
}))
planned_ausleihungen = list(ausleihungen_collection.find({
'User': username,
'Status': 'planned'
}))
# Process items
active_items = []
planned_items = []
processed_item_ids = set() # Keep track of processed item IDs to avoid duplicates
# First, process items that are directly marked as borrowed by the user
for item in borrowed_items:
# Convert ObjectId to string for template
item['_id'] = str(item['_id'])
active_items.append(item)
processed_item_ids.add(item['_id'])
# Process active appointments
for appointment in active_ausleihungen:
# Get the item ID from the appointment
processed_item_ids = set()
for appointment in all_ausleihungen:
raw_user = appointment.get('User', '')
try:
decrypted_user = decrypt_text(raw_user) if raw_user else ''
except Exception as e:
app.logger.error(f"Entschlüsselungsfehler: {e}")
decrypted_user = ''
if decrypted_user != username:
continue
item_id = appointment.get('Item')
if not item_id or str(item_id) in processed_item_ids:
continue # Skip if we already processed this item or no item ID
# Get item details
item_obj = items_collection.find_one({'_id': ObjectId(item_id)})
if not item_id:
continue
try:
if isinstance(item_id, str):
query_id = ObjectId(item_id)
else:
query_id = item_id
item_obj = items_collection.find_one({'_id': query_id})
except Exception:
item_obj = None
if item_obj:
# Convert ObjectId to string for template
item_obj['_id'] = str(item_obj['_id'])
# Add appointment data
item_obj['AppointmentData'] = {
'id': str(appointment['_id']),
'start': appointment.get('Start'),
@@ -10318,70 +10308,76 @@ def my_borrowed_items():
'period': appointment.get('Period'),
'status': appointment.get('VerifiedStatus', appointment.get('Status')),
}
# Mark that this item is part of an active appointment
item_obj['ActiveAppointment'] = True
# Add to the list only if not already there
if str(item_obj['_id']) not in processed_item_ids:
active_items.append(item_obj)
processed_item_ids.add(str(item_obj['_id']))
# Process planned appointments
for appointment in planned_ausleihungen:
item_id = appointment.get('Item')
if not item_id:
continue
item_obj = items_collection.find_one({'_id': ObjectId(item_id)})
if item_obj:
item_obj['_id'] = str(item_obj['_id'])
# Add appointment data
item_obj['AppointmentData'] = {
'id': str(appointment['_id']),
'start': appointment.get('Start'),
'end': appointment.get('End'),
'notes': appointment.get('Notes'),
'period': appointment.get('Period'),
'status': appointment.get('Status'),
}
planned_items.append(item_obj)
status = appointment.get('Status')
if status == 'active':
item_obj['ActiveAppointment'] = True
if str(item_obj['_id']) not in processed_item_ids:
active_items.append(item_obj)
processed_item_ids.add(str(item_obj['_id']))
elif status == 'planned':
planned_items.append(item_obj)
all_borrowed_items = list(items_collection.find({'Verfuegbar': False}))
for item in all_borrowed_items:
raw_item_user = item.get('User', '')
try:
dec_item_user = decrypt_text(raw_item_user) if raw_item_user else ''
except Exception:
dec_item_user = ''
if dec_item_user == username and str(item['_id']) not in processed_item_ids:
item['_id'] = str(item['_id'])
item['ActiveAppointment'] = True
item['AppointmentData'] = {'status': 'active (no document)'}
active_items.append(item)
processed_item_ids.add(item['_id'])
client.close()
# DEBUG: Log what we're passing to the template
app.logger.info(f"Passing {len(active_items)} active items and {len(planned_items)} planned items to template")
if planned_items:
for i, item in enumerate(planned_items):
app.logger.info(f"Planned item {i+1}: {item['Name']}, Appointment ID: {item['AppointmentData']['id']}")
# DEBUG Logging
app.logger.info(
f"Passing {len(active_items)} active items and {len(planned_items)} planned items to template for user {username}")
return render_template(
'my_borrowed_items.html',
items=active_items,
planned_items=planned_items,
user_is_admin=user_is_admin
planned_items=planned_items
)
@app.route('/api/push/vapid-key', methods=['GET'])
def get_vapid_key():
"""
Returns the VAPID public key for web push subscriptions
"""
from Web.push_notifications import _get_vapid_public
if 'username' not in session:
return jsonify({'success': False, 'error': 'Not authenticated'}), 401
try:
if not _get_vapid_public():
return jsonify({'success': False, 'error': 'VAPID public key not configured'}), 500
return jsonify({
'success': True,
'publicKey': _get_vapid_public()
})
except Exception as e:
app.logger.error(f'Error getting VAPID key: {e}')
return jsonify({'success': False}), 500
@app.route('/notifications')
def notifications_view():
"""Notification center for users and admins."""
from Web.push_notifications import _get_vapid_public
if 'username' not in session:
flash('Bitte melden Sie sich an, um Benachrichtigungen zu sehen.', 'error')
return redirect(url_for('login'))
username = session['username']
is_admin_user = False
current_permissions = us.get_effective_permissions(session['username'])
if not current_permissions['actions'].get('can_manage_settings', False):
is_admin_user = True
else:
is_admin_user = False
is_admin_user = current_permissions['actions'].get('can_manage_settings', False)
client = None
try:
@@ -10393,15 +10389,17 @@ def notifications_view():
admin_notifications = []
for notif in notifications:
is_read = username in (notif.get('ReadBy') or [])
created_at_val = notif.get('CreatedAt')
row = {
'id': str(notif.get('_id')),
'title': notif.get('Title', 'Benachrichtigung'),
'message': notif.get('Message', ''),
'severity': notif.get('Severity', 'info'),
'type': notif.get('Type', ''),
'created_at': notif.get('CreatedAt'),
'created_at': created_at_val if created_at_val else None,
'is_read': is_read,
'reference': notif.get('Reference', {}) or {},
'reference': notif.get('Reference') or {},
}
if notif.get('Audience') == 'admin':
admin_notifications.append(row)
@@ -10415,6 +10413,7 @@ def notifications_view():
is_admin_user=is_admin_user,
library_module_enabled=cfg.MODULES.is_enabled('library'),
student_cards_module_enabled=cfg.MODULES.is_enabled('student_cards'),
vapid_public_key=_get_vapid_public()
)
except Exception as exc:
app.logger.error(f"Error loading notifications: {exc}")
@@ -10454,45 +10453,49 @@ def mark_notification_read(notification_id):
return redirect(url_for('notifications_view'))
@app.route('/notifications/mark_all_read', methods=['POST'])
@app.route('/notifications/mark-all-read', methods=['POST'])
def mark_all_notifications_read():
"""Mark all visible notifications as read for the current user."""
if 'username' not in session:
flash('Bitte melden Sie sich an.', 'error')
return redirect(url_for('login'))
username = session['username']
is_admin_user = False
current_permissions = us.get_effective_permissions(session['username'])
if not current_permissions['actions'].get('can_manage_settings', False):
is_admin_user = True
else:
is_admin_user = False
query = {
'$or': [
{'Audience': 'user', 'TargetUser': username},
]
}
if is_admin_user:
query['$or'].append({'Audience': 'admin'})
current_permissions = us.get_effective_permissions(username)
is_admin_user = current_permissions['actions'].get('can_manage_settings', False)
client = None
try:
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
db = client[MONGODB_DB]
result = db['notifications'].update_many(
# Filter-Logik: Welche Benachrichtigungen sollen als gelesen markiert werden?
# Wenn Sie 'Audience' nutzen (wie in Ihrer notifications_view Route):
query = {}
if is_admin_user:
# Ein Admin sieht sowohl an ihn gerichtete als auch allgemeine Admin-Meldungen
query['$or'] = [
{'TargetUser': username},
{'Audience': 'admin'}
]
else:
# Normale User sehen nur Meldungen, die an sie oder alle User gerichtet sind
query['$or'] = [
{'TargetUser': username},
{'Audience': 'user'}
]
# WICHTIG: Fügt den Benutzernamen per $addToSet in das ReadBy-Array ein.
# $addToSet verhindert, dass der Name doppelt eingetragen wird, falls er schon drinsteht.
db['notifications'].update_many(
query,
{
'$addToSet': {'ReadBy': username},
'$set': {'UpdatedAt': datetime.datetime.now()}
}
{'$addToSet': {'ReadBy': username}}
)
if result.modified_count > 0:
_bump_notification_version(f'user:{username}')
flash('Alle Benachrichtigungen wurden als gelesen markiert.', 'success')
except Exception as exc:
app.logger.warning(f"Could not mark all notifications as read for {encrypt_text(username)}: {exc}")
app.logger.error(f"Error marking all notifications as read: {exc}")
flash('Fehler beim Aktualisieren der Benachrichtigungen.', 'error')
finally:
if client:
client.close()
@@ -10581,15 +10584,24 @@ def notifications_unread_status():
client.close()
@app.route('/admin/damaged_items')
@app.route('/admin/damaged_items')
def admin_damaged_items():
"""Admin-Übersicht aller aktiven und vergangenen Ausleihen."""
"""Admin-Übersicht aller Ausleihen von beschädigten Objekten."""
if 'username' not in session:
flash('Administratorrechte erforderlich.', 'error')
flash('Anmeldung erforderlich.', 'error')
return redirect(url_for('login'))
# SICHERHEIT: Berechtigungsprüfung (wie in admin_borrowings)
# Entferne die Kommentare, falls du `us` in dieser Datei importiert hast
"""
current_permissions = us.get_effective_permissions(session['username'])
if not current_permissions['pages'].get('admin_damaged_items', False):
flash('Ihnen fehlen die nötigen Berechtigungen, um diese Aktion auszuführen.', 'error')
return redirect(url_for('home_admin'))
"""
# Import sicherstellen
from modules.inventarsystem.data_protection import decrypt_text
from bson.objectid import ObjectId
client = None
try:
@@ -10598,36 +10610,53 @@ def admin_damaged_items():
ausleihungen_col = db['ausleihungen']
items_col = db['items']
ausleihungen = list(ausleihungen_col.find().sort('Start', -1))
alle_ausleihungen = list(ausleihungen_col.find().sort('Start', -1))
for record in ausleihungen:
raw_user = record.get('User', '')
if raw_user:
record['User'] = decrypt_text(raw_user)
beschädigte_ausleihungen = []
for record in alle_ausleihungen:
item_id = record.get('Item')
if item_id:
try:
item_doc = items_col.find_one({'_id': ObjectId(item_id)})
if item_doc:
if not item_id:
continue
try:
if isinstance(item_id, str):
query_id = ObjectId(item_id)
else:
query_id = item_id
item_doc = items_col.find_one({'_id': query_id})
if item_doc:
condition_value = str(item_doc.get('Condition', '')).strip().lower()
has_damage = bool(item_doc.get('HasDamage')) or condition_value == 'destroyed' or bool(
item_doc.get('DamageReports'))
if has_damage:
raw_user = record.get('User', '')
if raw_user:
record['User'] = decrypt_text(raw_user)
if item_doc.get('User'):
item_doc['User'] = decrypt_text(item_doc['User'])
record['ItemDetails'] = item_doc
except Exception as e:
app.logger.warning(f"Konnte Item {item_id} für Ausleihe {record.get('_id')} nicht laden: {e}")
beschädigte_ausleihungen.append(record)
except Exception as e:
app.logger.warning(f"Konnte Item {item_id} für Ausleihe {record.get('_id')} nicht laden: {e}")
return render_template(
'admin_damaged_items.html',
ausleihungen=ausleihungen,
'admin_damaged_items.html',
ausleihungen=beschädigte_ausleihungen,
library_module_enabled=cfg.MODULES.is_enabled('library'),
student_cards_module_enabled=cfg.MODULES.is_enabled('student_cards'),
mail_module_enabled=cfg.MODULES.is_enabled('mail')
)
except Exception as exc:
app.logger.error(f"Fehler beim Laden der Ausleihen-Verwaltung: {exc}")
flash('Fehler beim Laden der Ausleihen-Übersicht.', 'error')
app.logger.error(f"Fehler beim Laden der beschädigten Objekte: {exc}")
flash('Fehler beim Laden der Übersicht.', 'error')
return redirect(url_for('home_admin'))
finally:
if client:
@@ -12103,44 +12132,33 @@ def get_optimal_image_quality(img, target_size_kb=80):
def health_check():
return 'OK', 200
@app.route('/api/push/subscribe', methods=['POST'])
def subscribe_to_push():
"""
Subscribe a user to push notifications
Expects JSON payload:
{
'subscription': {
'endpoint': '...',
'keys': {'p256dh': '...', 'auth': '...'}
}
}
"""
if 'username' not in session:
return jsonify({'success': False, 'error': 'Not authenticated'}), 401
return jsonify({'success': False, 'error': 'Unauthorized'}), 401
data = request.get_json(silent=True) or {}
subscription_obj = data.get('subscription') if 'subscription' in data else data
if not subscription_obj or not isinstance(subscription_obj, dict):
app.logger.error("Invalid subscription payload received")
return jsonify({'success': False, 'error': 'Invalid payload'}), 400
username = session['username']
try:
data = request.get_json() or {}
subscription = data.get('subscription')
if not subscription or not subscription.get('endpoint'):
return jsonify({'success': False, 'error': 'Invalid subscription'}), 400
username = session['username']
success = pn.save_push_subscription(username, subscription)
success = pn.save_push_subscription(username, subscription_obj)
if success:
app.logger.info(f'Push subscription saved for {encrypt_text(username)}')
return jsonify({
'success': True,
'message': 'Successfully subscribed to push notifications'
})
return jsonify({'success': True})
else:
return jsonify({'success': False, 'error': 'Failed to save subscription'}), 500
return jsonify({'success': False, 'error': 'Failed to save in DB'}), 400
except Exception as e:
app.logger.error(f'Error subscribing to push: {e}')
return jsonify({'success': False}), 500
app.logger.error(f"Error in subscribe_to_push route: {e}")
return jsonify({'success': False, 'error': 'Internal server error'}), 500
@app.route('/api/push/unsubscribe', methods=['POST'])
@@ -12157,7 +12175,7 @@ def unsubscribe_from_push():
return jsonify({'success': False, 'error': 'Not authenticated'}), 401
try:
data = request.get_json() or {}
data = request.get_json(silent=True) or {}
endpoint = data.get('endpoint')
if not endpoint:
@@ -12213,32 +12231,6 @@ def get_push_subscriptions():
app.logger.error(f'Error getting push subscriptions: {e}')
return jsonify({'success': False}), 500
@app.route('/api/push/vapid-key', methods=['GET'])
def get_vapid_key():
"""
Get the VAPID public key for push notifications
Used by the service worker to communicate with push service
"""
try:
vapid_key = pn.VAPID_PUBLIC_KEY
if not vapid_key:
app.logger.warning('VAPID_PUBLIC_KEY not configured')
return jsonify({
'success': False,
'error': 'Push notifications not configured on server'
}), 501
return jsonify({
'success': True,
'vapid_key': vapid_key
})
except Exception as e:
app.logger.error(f'Error getting VAPID key: {e}')
return jsonify({'success': False}), 500
@app.route('/api/push/test', methods=['POST'])
def test_push_notification():
"""
@@ -12247,11 +12239,8 @@ def test_push_notification():
if 'username' not in session:
return jsonify({'success': False, 'error': 'Not authenticated'}), 401
if not us.is_admin(session['username']):
return jsonify({'success': False, 'error': 'Admin access required'}), 403
try:
data = request.get_json() or {}
data = request.get_json(silent=True) or {}
target_user = data.get('target_user', session['username'])
sent = pn.send_push_notification(
File diff suppressed because it is too large Load Diff
+205 -173
View File
@@ -19,11 +19,61 @@ Collection Structure:
- Status fields: Verfuegbar, User (if currently borrowed)
"""
from bson.objectid import ObjectId
from bson.errors import InvalidId
import datetime
import Web.modules.database.settings as cfg
from Web.modules.database.settings import MongoClient
import Web.modules.inventarsystem.data_protection as dp
def safe_decrypt_user(encrypted_user):
"""
Safely decrypt an encrypted username string.
Returns the original string if decryption fails or if input is empty/None.
"""
if not encrypted_user:
return encrypted_user
try:
return dp.decrypt_text(encrypted_user)
except Exception as e:
print(f"Error decrypting user data: {e}")
# Return fallback value or None to prevent downstream crashes
return "[Decryption Failed]"
def decrypt_item_user_data(item):
"""
Decrypts encrypted user fields within an inventory item document in-place.
Args:
item (dict): MongoDB document representing an item.
Returns:
dict: The item with decrypted user fields.
"""
if not item:
return item
# 1. Decrypt top-level 'User' field if present
if 'User' in item and item['User']:
item['User'] = safe_decrypt_user(item['User'])
# 2. Decrypt nested 'user' field in 'NextAppointment' if present
if 'NextAppointment' in item and isinstance(item['NextAppointment'], dict):
if 'user' in item['NextAppointment']:
item['NextAppointment']['user'] = safe_decrypt_user(item['NextAppointment']['user'])
return item
def _to_object_id(id_str):
"""Safely convert a string to ObjectId."""
try:
return ObjectId(id_str)
except (InvalidId, TypeError):
return None
LIBRARY_ITEM_TYPES = ('book', 'cd', 'dvd', 'other', 'schoolbook', 'Buch', 'Schulbuch', 'schulbuch')
@@ -52,7 +102,7 @@ def add_item(name, ort, beschreibung, images=None, filter=None, filter2=None, fi
isbn=None, item_type='general', library_category=None, is_library=False):
"""
Add a new item to the inventory.
Args:
name (str): Name of the item
ort (str): Location of the item
@@ -73,7 +123,7 @@ def add_item(name, ort, beschreibung, images=None, filter=None, filter2=None, fi
isbn (str, optional): ISBN for books or media items
item_type (str, optional): Type of the item (e.g., 'general', 'book', 'cd')
library_category (str, optional): Library category for the item
Returns:
ObjectId: ID of the new item or None if failed
"""
@@ -102,7 +152,7 @@ def add_item(name, ort, beschreibung, images=None, filter=None, filter2=None, fi
'ISBN': isbn,
'library_category': library_category,
'ItemType': item_type,
'is_library': is_library,
'is_library': is_library,
'SeriesGroupId': series_group_id,
'SeriesCount': series_count,
'SeriesPosition': series_position,
@@ -124,10 +174,10 @@ def add_item(name, ort, beschreibung, images=None, filter=None, filter2=None, fi
def remove_item(id):
"""
Soft-delete an item from the inventory.
Args:
id (str): ID of the item to remove
Returns:
bool: True if successful, False otherwise
"""
@@ -199,21 +249,19 @@ def get_group_item_ids(id):
return []
def update_item(id, name, ort, beschreibung, images, verfuegbar, filter1, filter2, filter3,
def update_item(id, name, ort, beschreibung, images, verfuegbar, filter1, filter2, filter3,
ansch_jahr, ansch_kost, code_4, reservierbar, isbn=None, item_type='general'):
try:
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
items = db['items']
# 1. Altes Item laden, um SeriesGroupId zu bestimmen
old_item = items.find_one({'_id': ObjectId(id)})
if not old_item:
return False
series_group_id = old_item.get('SeriesGroupId')
# 2. Shared Data: Daten, die für ALLE in der Gruppe gleich sind
shared_update = {
'Name': name,
'Ort': ort,
@@ -227,18 +275,15 @@ def update_item(id, name, ort, beschreibung, images, verfuegbar, filter1, filter
'Reservierbar': reservierbar,
'ISBN': isbn,
'ItemType': item_type,
'Verfuegbar': verfuegbar, # Wir behalten den Status bei
'Verfuegbar': verfuegbar,
'LastUpdated': datetime.datetime.now()
}
# 3. Spezifische Daten: Was NICHT synchronisiert wird
specific_update = shared_update.copy()
specific_update['Code_4'] = code_4
# 4. Das aktuelle Item updaten
items.update_one({'_id': ObjectId(id)}, {'$set': specific_update})
# 5. Alle anderen Gruppen-Mitglieder synchronisieren
if series_group_id:
items.update_many(
{
@@ -257,12 +302,12 @@ def update_item(id, name, ort, beschreibung, images, verfuegbar, filter1, filter
def update_item_status(id, verfuegbar, user=None):
"""
Update the availability status of an inventory item.
Args:
id (str): ID of the item to update
verfuegbar (bool): New availability status
user (str, optional): Username of person who borrowed the item
Returns:
bool: True if successful, False otherwise
"""
@@ -279,7 +324,7 @@ def update_item_status(id, verfuegbar, user=None):
update_query = {'$set': update_data}
if user is not None:
update_data['User'] = user
update_data['User'] = dp.encrypt_text(user)
elif verfuegbar:
# If item is being marked as available, clear the user field
update_query['$unset'] = {'User': ""}
@@ -299,11 +344,11 @@ def update_item_status(id, verfuegbar, user=None):
def update_item_exemplare_status(id, exemplare_status):
"""
Update the exemplar status of an inventory item.
Args:
id (str): ID of the item to update
exemplare_status (list): List of status objects for each exemplar
Returns:
bool: True if successful, False otherwise
"""
@@ -332,32 +377,32 @@ def update_item_exemplare_status(id, exemplare_status):
def is_code_unique(code_4, exclude_id=None):
"""
Check if a given code is unique (not used by any other item).
Args:
code_4 (str): The code to check
exclude_id (str, optional): ID of item to exclude from the check (for edit operations)
Returns:
bool: True if code is unique, False if already in use
"""
if not code_4 or code_4.strip() == "":
# Empty codes are not considered unique
return False
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
items = db['items']
# Build query to find items with this code
query = {'Code_4': code_4, 'Deleted': {'$ne': True}}
# If we're editing an item, exclude it from the uniqueness check
if exclude_id:
query['_id'] = {'$ne': ObjectId(exclude_id)}
# Check if any items with this code exist
count = items.count_documents(query)
client.close()
return count == 0
@@ -367,7 +412,7 @@ def is_code_unique(code_4, exclude_id=None):
def get_items():
"""
Retrieve all inventory items.
Returns:
list: List of all inventory item documents with string IDs
"""
@@ -390,7 +435,7 @@ def get_items():
def get_available_items():
"""
Retrieve all available inventory items.
Returns:
list: List of available inventory item documents with string IDs
"""
@@ -413,7 +458,7 @@ def get_available_items():
def get_borrowed_items():
"""
Retrieve all currently borrowed inventory items.
Returns:
list: List of borrowed inventory item documents with string IDs
"""
@@ -432,36 +477,36 @@ def get_borrowed_items():
print(f"Error retrieving borrowed items: {e}")
return []
def get_item(id, decrypt=True):
"""
Retrieve an inventory item by ID, with optional decryption.
"""
item_id = _to_object_id(id)
if not item_id:
return None
def get_item(id):
"""
Retrieve a specific inventory item by its ID.
Args:
id (str): ID of the item to retrieve
Returns:
dict: The inventory item document or None if not found
"""
try:
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
items = db['items']
item = items.find_one(_active_record_query({'_id': ObjectId(id)}))
client.close()
query = _active_record_query({'_id': item_id})
item = items.find_one(query)
if item:
item['_id'] = str(item['_id'])
if decrypt:
decrypt_item_user_data(item)
return item
except Exception as e:
print(f"Error retrieving item: {e}")
print(f"Error retrieving item {id}: {e}")
return None
def get_item_by_name(name):
"""
Retrieve a specific inventory item by its name.
Args:
name (str): Name of the item to retrieve
Returns:
dict: The inventory item document or None if not found
"""
@@ -480,10 +525,10 @@ def get_item_by_name(name):
def get_items_by_filter(filter_value):
"""
Retrieve inventory items matching a specific filter/category.
Args:
filter_value (str): Filter value to search for
Returns:
list: List of items matching the filter in primary, secondary, or tertiary category
"""
@@ -491,7 +536,7 @@ def get_items_by_filter(filter_value):
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
items = db['items']
# Use $or to find matches in any filter field
query = _active_record_query(_non_library_query({
'$or': [
@@ -500,14 +545,14 @@ def get_items_by_filter(filter_value):
{'Filter3': filter_value}
]
}))
results = list(items.find(query))
client.close()
# Convert ObjectId to string
for item in results:
item['_id'] = str(item['_id'])
return results
except Exception as e:
print(f"Error retrieving items by filter: {e}")
@@ -517,7 +562,7 @@ def get_items_by_filter(filter_value):
def get_filters():
"""
Retrieve all unique filter/category values from the inventory.
Returns:
list: Combined list of all primary, secondary and tertiary filter values
"""
@@ -529,16 +574,16 @@ def get_filters():
filters = items.distinct('Filter', non_library)
filters2 = items.distinct('Filter2', non_library)
filters3 = items.distinct('Filter3', non_library)
# Combine filters and remove None/empty values
all_filters = [f for f in filters + filters2 + filters3 if f]
# Remove duplicates while preserving order
unique_filters = []
for f in all_filters:
if f not in unique_filters:
unique_filters.append(f)
client.close()
return unique_filters
except Exception as e:
@@ -549,7 +594,7 @@ def get_filters():
def get_primary_filters():
"""
Retrieve all unique primary filter values.
Returns:
list: List of all primary filter values
"""
@@ -559,7 +604,7 @@ def get_primary_filters():
items = db['items']
filters = [f for f in items.distinct('Filter', _active_record_query(_non_library_query())) if f]
client.close()
# Add predefined values
predefined = get_predefined_filter_values(1)
return sorted(list(set(filters + predefined)))
@@ -571,7 +616,7 @@ def get_primary_filters():
def get_secondary_filters():
"""
Retrieve all unique secondary filter values.
Returns:
list: List of all secondary filter values
"""
@@ -581,7 +626,7 @@ def get_secondary_filters():
items = db['items']
filters = [f for f in items.distinct('Filter2', _active_record_query(_non_library_query())) if f]
client.close()
# Add predefined values
predefined = get_predefined_filter_values(2)
return sorted(list(set(filters + predefined)))
@@ -593,7 +638,7 @@ def get_secondary_filters():
def get_tertiary_filters():
"""
Retrieve all unique tertiary filter values.
Returns:
list: List of all tertiary filter values
"""
@@ -603,7 +648,7 @@ def get_tertiary_filters():
items = db['items']
filters = [f for f in items.distinct('Filter3', _active_record_query(_non_library_query())) if f]
client.close()
# Add predefined values
predefined = get_predefined_filter_values(3)
return sorted(list(set(filters + predefined)))
@@ -615,10 +660,10 @@ def get_tertiary_filters():
def get_item_by_code_4(code_4):
"""
Retrieve inventory items matching a specific 4-digit code.
Args:
code_4 (str): 4-digit code to search for
Returns:
list: List of items matching the code
"""
@@ -627,11 +672,11 @@ def get_item_by_code_4(code_4):
db = client[cfg.MONGODB_DB]
items = db['items']
results = list(items.find(_active_record_query(_non_library_query({"Code_4": code_4}))))
# Convert ObjectId to string
for item in results:
item['_id'] = str(item['_id'])
client.close()
return results
except Exception as e:
@@ -645,10 +690,10 @@ def unstuck_item(id):
"""
Remove all borrowing records for a specific item to reset its status.
Used to fix problematic or stuck items.
Args:
id (str): ID of the item to unstick
Returns:
bool: True if successful, False otherwise
"""
@@ -664,7 +709,7 @@ def unstuck_item(id):
'LastUpdated': datetime.datetime.now()
}}
)
# Also reset the item status
items = db['items']
items.update_one(
@@ -677,7 +722,7 @@ def unstuck_item(id):
'$unset': {'User': ""}
}
)
client.close()
return True
except Exception as e:
@@ -688,24 +733,24 @@ def unstuck_item(id):
def get_predefined_filter_values(filter_num):
"""
Get predefined values for a specific filter.
Args:
filter_num (int): Filter number (1 for Unterrichtsfach, 2 for Jahrgangsstufe)
Returns:
list: List of predefined filter values
"""
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
# Use a dedicated collection for filter presets
filter_presets = db['filter_presets']
# Find the document for the specified filter
filter_doc = filter_presets.find_one({'filter_num': filter_num})
client.close()
if filter_doc and 'values' in filter_doc:
# Sort values alphabetically
return sorted(filter_doc['values'])
@@ -725,60 +770,60 @@ def get_predefined_filter_values(filter_num):
def add_predefined_filter_value(filter_num, value):
"""
Add a new predefined value to a filter.
Args:
filter_num (int): Filter number (1 for Unterrichtsfach, 2 for Jahrgangsstufe)
value (str): Value to add
Returns:
bool: True if value was added, False if it already existed
"""
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
filter_presets = db['filter_presets']
# Check if value already exists
filter_doc = filter_presets.find_one({
'filter_num': filter_num,
'values': value
})
if filter_doc:
# Value already exists
client.close()
return False
# Add the value to the filter
result = filter_presets.update_one(
{'filter_num': filter_num},
{'$push': {'values': value}},
upsert=True
)
client.close()
return result.modified_count > 0 or result.upserted_id is not None
def remove_predefined_filter_value(filter_num, value):
"""
Remove a predefined value from a filter.
Args:
filter_num (int): Filter number (1 for Unterrichtsfach, 2 for Jahrgangsstufe)
value (str): Value to remove
Returns:
bool: True if value was removed, False otherwise
"""
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
filter_presets = db['filter_presets']
# Remove the value from the filter
result = filter_presets.update_one(
{'filter_num': filter_num},
{'$pull': {'values': value}}
)
client.close()
return result.modified_count > 0
@@ -786,45 +831,45 @@ def remove_predefined_filter_value(filter_num, value):
def edit_predefined_filter_value(filter_num, old_value, new_value):
"""
Edit a predefined value from a filter and update all matching items.
Args:
filter_num (int): Filter number (1 for Unterrichtsfach, 2 for Jahrgangsstufe)
old_value (str): Value to replace
new_value (str): New value
Returns:
bool: True if value was updated, False otherwise
"""
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
filter_presets = db['filter_presets']
# Check if the new value already exists
existing = filter_presets.find_one({
'filter_num': filter_num,
'values': new_value
})
if existing and old_value != new_value:
client.close()
return False
# Update the value in the filter
result = filter_presets.update_one(
{'filter_num': filter_num, 'values': old_value},
{'$set': {'values.$': new_value}}
)
if result.modified_count > 0:
items = db['items']
filter_field = 'Filter' if filter_num == 1 else f'Filter{filter_num}'
# Also update all items that use this filter
items.update_many(
{filter_field: old_value},
{'$set': {filter_field: new_value}}
)
client.close()
return result.modified_count > 0
@@ -862,22 +907,22 @@ def set_filter_name(filter_num, name):
def get_predefined_locations():
"""
Get list of all predefined locations/placement options.
Returns:
list: List of predefined location strings
"""
try:
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
# Check if settings collection exists, create if not
if 'settings' not in db.list_collection_names():
db.create_collection('settings')
# Get settings document or create if it doesn't exist
settings_collection = db['settings']
location_settings = settings_collection.find_one({'setting_type': 'predefined_locations'})
if not location_settings:
# Create default settings document if it doesn't exist
settings_collection.insert_one({
@@ -885,12 +930,12 @@ def get_predefined_locations():
'locations': []
})
return []
# Return the predefined locations
locations = location_settings.get('locations', [])
client.close()
return sorted(locations)
except Exception as e:
print(f"Error getting predefined locations: {str(e)}")
return []
@@ -899,28 +944,28 @@ def get_predefined_locations():
def add_predefined_location(location):
"""
Add a new predefined location.
Args:
location (str): Location to add
Returns:
bool: True if added successfully, False if already exists
"""
if not location or not isinstance(location, str):
return False
location = location.strip()
if not location:
return False
try:
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
settings_collection = db['settings']
# Check if settings document exists, create if not
location_settings = settings_collection.find_one({'setting_type': 'predefined_locations'})
if not location_settings:
# Create with the new location
settings_collection.insert_one({
@@ -929,22 +974,22 @@ def add_predefined_location(location):
})
client.close()
return True
# Check if location already exists (case-insensitive)
current_locations = location_settings.get('locations', [])
if any(loc.lower() == location.lower() for loc in current_locations):
client.close()
return False
# Add the new location
settings_collection.update_one(
{'setting_type': 'predefined_locations'},
{'$push': {'locations': location}}
)
client.close()
return True
except Exception as e:
print(f"Error adding predefined location: {str(e)}")
return False
@@ -953,29 +998,29 @@ def add_predefined_location(location):
def remove_predefined_location(location):
"""
Remove a predefined location.
Args:
location (str): Location to remove
Returns:
bool: True if removed successfully
"""
if not location:
return False
try:
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
settings_collection = db['settings']
result = settings_collection.update_one(
{'setting_type': 'predefined_locations'},
{'$pull': {'locations': location}}
)
client.close()
return result.modified_count > 0
except Exception as e:
print(f"Error removing predefined location: {str(e)}")
return False
@@ -984,17 +1029,12 @@ def remove_predefined_location(location):
def update_item_next_appointment(item_id, appointment_data):
"""
Update an item with information about its next scheduled appointment.
Args:
item_id (str): ID of the item to update
appointment_data (dict): Appointment information containing:
- date: Date of the appointment
- start_period: Start period number
- end_period: End period number
- user: Username who scheduled the appointment
- notes: Optional notes
- appointment_id: ID of the appointment booking
item_id (str): ID of the item
appointment_data (dict or None): Dictionary containing appointment details
(e.g., user, start_time, end_time) or None to clear it.
Returns:
bool: True if successful, False otherwise
"""
@@ -1002,35 +1042,33 @@ def update_item_next_appointment(item_id, appointment_data):
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
items = db['items']
# Format the appointment data for storage
# Ensure date is a datetime object for MongoDB storage
appointment_date = appointment_data['date']
if isinstance(appointment_date, datetime.date) and not isinstance(appointment_date, datetime.datetime):
# Convert date to datetime for MongoDB compatibility
appointment_date = datetime.datetime.combine(appointment_date, datetime.time())
next_appointment = {
'date': appointment_date,
'end_date': appointment_data.get('end_date', appointment_date),
'start_period': appointment_data['start_period'],
'end_period': appointment_data['end_period'],
'user': appointment_data['user'],
'notes': appointment_data.get('notes', ''),
'appointment_id': appointment_data['appointment_id'],
'scheduled_at': datetime.datetime.now()
}
update_data = {
'NextAppointment': next_appointment,
'LastUpdated': datetime.datetime.now()
}
# If clearing the appointment
if appointment_data is None:
update_query = {
'$unset': {'NextAppointment': ""},
'$set': {'LastUpdated': datetime.datetime.now()}
}
else:
# Create a copy so we don't mutate the original dictionary passed in
data_to_save = appointment_data.copy()
# Encrypt the user field if it exists to match the decryption logic at the top
if 'user' in data_to_save and data_to_save['user']:
data_to_save['user'] = dp.encrypt_text(data_to_save['user'])
update_query = {
'$set': {
'NextAppointment': data_to_save,
'LastUpdated': datetime.datetime.now()
}
}
result = items.update_one(
{'_id': ObjectId(item_id)},
{'$set': update_data}
update_query
)
client.close()
return result.modified_count > 0
except Exception as e:
@@ -1041,10 +1079,10 @@ def update_item_next_appointment(item_id, appointment_data):
def clear_item_next_appointment(item_id):
"""
Clear the next appointment information from an item.
Args:
item_id (str): ID of the item to update
Returns:
bool: True if successful, False otherwise
"""
@@ -1052,12 +1090,12 @@ def clear_item_next_appointment(item_id):
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
items = db['items']
result = items.update_one(
{'_id': ObjectId(item_id)},
{'$unset': {'NextAppointment': ""}, '$set': {'LastUpdated': datetime.datetime.now()}}
)
client.close()
return result.modified_count > 0
except Exception as e:
@@ -1068,7 +1106,7 @@ def clear_item_next_appointment(item_id):
def get_items_with_appointments():
"""
Retrieve all items that have scheduled appointments.
Returns:
list: List of items with NextAppointment field
"""
@@ -1076,7 +1114,7 @@ def get_items_with_appointments():
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
items = db['items']
items_return = items.find({'NextAppointment': {'$exists': True}, 'Deleted': {'$ne': True}})
items_list = []
for item in items_return:
@@ -1088,31 +1126,25 @@ def get_items_with_appointments():
print(f"Error retrieving items with appointments: {e}")
return []
def get_current_status(item_id):
def get_current_status(item_id, decrypt=True):
"""
Retrieve the current status of an item, including availability and user.
Args:
item_id (str): ID of the item to check
Returns:
dict: Current status of the item or None if not found
Retrieve the current status of an item, decrypting the user field if present.
"""
oid = _to_object_id(item_id)
if not oid:
return None
try:
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
items = db['items']
item = items.find_one({'_id': ObjectId(item_id)}, {'Verfuegbar': 1, 'User': 1})
item = items.find_one({'_id': oid}, {'Verfuegbar': 1, 'User': 1})
if item:
# Convert ObjectId to string for consistency
item['_id'] = str(item['_id'])
client.close()
if decrypt:
decrypt_item_user_data(item)
return item
else:
client.close()
return None
return None
except Exception as e:
print(f"Error retrieving current status: {e}")
print(f"Error retrieving current status for item {item_id}: {e}")
return None
+14 -8
View File
@@ -220,15 +220,15 @@ SSL_CERT = _get(_conf, ['ssl', 'cert'], DEFAULTS['ssl']['cert'])
SSL_KEY = _get(_conf, ['ssl', 'key'], DEFAULTS['ssl']['key'])
# Email settings
EMAIL_ENABLED = _get(_conf, ['email', 'enabled'], False)
EMAIL_SMTP_HOST = _get(_conf, ['email', 'smtp_host'], 'smtp.gmail.com')
EMAIL_SMTP_PORT = int(_get(_conf, ['email', 'smtp_port'], 587))
EMAIL_USE_TLS = bool(_get(_conf, ['email', 'use_tls'], True))
EMAIL_USERNAME = _get(_conf, ['email', 'username'], '')
EMAIL_PASSWORD = _get(_conf, ['email', 'password'], '')
EMAIL_ENABLED = bool(os.getenv('EMAIL_ENABLED', False))
EMAIL_SMTP_HOST = str(os.getenv('EMAIL_SMTP_HOST', False))
EMAIL_SMTP_PORT = int(os.getenv('EMAIL_SMTP_PORT', 587))
EMAIL_USE_TLS = True
EMAIL_USERNAME = str(os.getenv('EMAIL_USERNAME', False))
EMAIL_PASSWORD = str(os.getenv('EMAIL_PASSWORD', False))
EMAIL_FROM_ADDRESS = _get(_conf, ['email', 'from_address'], EMAIL_USERNAME)
EMAIL_DEFAULT_SENDER_NAME = _get(_conf, ['email', 'default_sender_name'], 'Inventarsystem')
EMAIL_TIMEOUT_SECONDS = int(_get(_conf, ['email', 'timeout_seconds'], 30))
EMAIL_DEFAULT_SENDER_NAME = "Invario Inventarsystem Sender"
EMAIL_TIMEOUT_SECONDS = 20
# School periods
SCHOOL_PERIODS = _get(_conf, ['schoolPeriods'], DEFAULTS['schoolPeriods'])
@@ -278,6 +278,7 @@ INVENTORY_MODULE_ENABLED = _TenantAwareBool('inventory', _get(_conf, ['modules',
TERMINPLAN_MODULE_ENABLED = _TenantAwareBool('terminplan', _get(_conf, ['modules', 'terminplan', 'enabled'], DEFAULTS['modules']['terminplan']['enabled']))
LIBRARY_MODULE_ENABLED = _TenantAwareBool('library', _get(_conf, ['modules', 'library', 'enabled'], DEFAULTS['modules']['library']['enabled']))
STUDENT_CARDS_MODULE_ENABLED = _TenantAwareBool('student_cards', _get(_conf, ['modules', 'student_cards', 'enabled'], DEFAULTS['modules']['student_cards']['enabled']))
MAIL_ADD_ON_ENABLED = _TenantAwareBool('mail', _get(_conf, ['email', 'enabled'], False))
def _match_inventory(path):
if not path: return False
@@ -297,11 +298,16 @@ def _match_student_cards(path):
if not path: return False
return path.startswith(('/student_cards'))
def _match_mail(path):
if not path: return False
return path.startswith(('/configure'))
# Register core modules into the pipeline
MODULES.register('inventory', INVENTORY_MODULE_ENABLED, _match_inventory)
MODULES.register('terminplan', TERMINPLAN_MODULE_ENABLED, _match_terminplan)
MODULES.register('library', LIBRARY_MODULE_ENABLED, _match_library)
MODULES.register('student_cards', STUDENT_CARDS_MODULE_ENABLED, _match_student_cards)
MODULES.register('mail', MAIL_ADD_ON_ENABLED, _match_mail)
STUDENT_DEFAULT_BORROW_DAYS = int(_get(_conf, ['modules', 'student_cards', 'default_borrow_days'], DEFAULTS['modules']['student_cards']['default_borrow_days']))
STUDENT_MAX_BORROW_DAYS = int(_get(_conf, ["modules", "student_cards", "max_borrow_days"], DEFAULTS["modules"]["student_cards"]["max_borrow_days"]))
+135 -252
View File
@@ -20,6 +20,7 @@ import string
from bson.objectid import ObjectId
import Web.modules.database.settings as cfg
from Web.modules.database.settings import MongoClient
import Web.modules.inventarsystem.data_protection as dp
import hmac
import os
@@ -109,13 +110,6 @@ def build_username_from_name(first_name, last_name=''):
"""
Build a deterministic username abbreviation from first and last name.
Uses 3 letters from each name and stores it lowercase.
Args:
first_name (str): First name
last_name (str): Last name (optional)
Returns:
str: Generated username
"""
alias = build_name_synonym(first_name, last_name)
return alias.lower()
@@ -324,7 +318,6 @@ def get_effective_permissions(username):
return build_default_permission_payload('full_access')
preset_key = user.get('PermissionPreset')
print(preset_key)
payload = build_default_permission_payload(preset_key)
payload['actions'] = _normalize_bool_map(user.get('ActionPermissions', {}), payload['actions'])
payload['pages'] = _normalize_bool_map(user.get('PagePermissions', {}), payload['pages'])
@@ -352,10 +345,10 @@ def update_user_permissions(username, preset_key, action_permissions=None, page_
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = _get_tenant_db(client)
users = db['users']
result = users.update_one({'Username': username}, {'$set': update_data})
result = users.update_one({'Username': dp.encrypt_text(username)}, {'$set': update_data})
if result.matched_count == 0:
result = users.update_one({'username': username}, {'$set': update_data})
result = users.update_one({'username': dp.encrypt_text(username)}, {'$set': update_data})
client.close()
return result.matched_count > 0
@@ -367,7 +360,7 @@ def get_favorites(username):
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = _get_tenant_db(client)
users = db['users']
user = users.find_one({'Username': username}) or users.find_one({'username': username})
user = users.find_one({'Username': dp.encrypt_text(username)}) or users.find_one({'username': dp.encrypt_text(username)})
client.close()
if not user:
return []
@@ -382,7 +375,7 @@ def add_favorite(username, item_id):
db = _get_tenant_db(client)
users = db['users']
users.update_one(
{'$or': [{'Username': username}, {'username': username}]},
{'$or': [{'Username': dp.encrypt_text(username)}, {'username': dp.encrypt_text(username)}]},
{'$addToSet': {'favorites': ObjectId(item_id)}}
)
client.close()
@@ -397,7 +390,7 @@ def remove_favorite(username, item_id):
db = _get_tenant_db(client)
users = db['users']
users.update_one(
{'$or': [{'Username': username}, {'username': username}]},
{'$or': [{'Username': dp.encrypt_text(username)}, {'username': dp.encrypt_text(username)}]},
{'$pull': {'favorites': ObjectId(item_id)}}
)
client.close()
@@ -406,16 +399,9 @@ def remove_favorite(username, item_id):
return False
def check_password_strength(password):
"""
Check if a password meets minimum security requirements.
Args:
password (str): Password to check
Returns:
bool: True if password is strong enough, False otherwise
"""
if password is None:
return False
@@ -435,19 +421,15 @@ def check_password_strength(password):
def hashing(password, salt=None):
"""
Hasht ein Passwort mit scrypt.
- Wenn kein Salt übergeben wird, wird ein sicherer, zufälliger Salt generiert (für neue Passwörter).
- Format für neue Hashes: v1$<salt_hex>$<hash_hex>
Hasht ein Passwort mit scrypt.
"""
password_bytes = password.encode('utf-8') # Explizit UTF-8 für Plattformunabhängigkeit
password_bytes = password.encode('utf-8')
if salt is None:
# Neuer Benutzer / Passwortänderung -> Dynamischer Salt
random_salt = os.urandom(16)
hashed = hashlib.scrypt(password_bytes, salt=random_salt, n=16384, r=8, p=1)
return f"v1${random_salt.hex()}${hashed.hex()}"
else:
# Bestehender Benutzer (wird zur Verifizierung aufgerufen)
hashed = hashlib.scrypt(password_bytes, salt=salt, n=16384, r=8, p=1)
return hashed.hex()
@@ -455,25 +437,20 @@ def hashing(password, salt=None):
def verify_password(provided_password, stored_password_string):
"""
Verifiziert ein Passwort gegen einen gespeicherten Hash-String.
Unterstützt das alte Format (statischer Salt) und das neue Format (v1$...).
"""
if not stored_password_string:
return False
# Überprüfung für das neue, sichere Format
if stored_password_string.startswith("v1$"):
try:
_, salt_hex, hash_hex = stored_password_string.split("$")
salt_bytes = bytes.fromhex(salt_hex)
# Berechne den Hash des eingegebenen Passworts mit dem extrahierten Salt
calculated_hash = hashing(provided_password, salt=salt_bytes)
# Timing-Attack-sicherer Vergleich
return hmac.compare_digest(calculated_hash, hash_hex)
except (ValueError, TypeError):
logger.error("Ungültiges Hash-Format in der Datenbank entdeckt.")
return False
else:
# Abwärtskompatibilität: Altes Format mit statischem Salt b'some_salt'
old_static_salt = b'some_salt'
calculated_hash = hashing(provided_password, salt=old_static_salt)
return hmac.compare_digest(calculated_hash, stored_password_string)
@@ -494,22 +471,26 @@ def check_nm_pwd(username, password):
try:
db = client[db_name]
users = db['users']
query = {'$or': [{'Username': username}, {'username': username}]}
query = {'$or': [{'Username': dp.encrypt_text(username)}, {'username': dp.encrypt_text(username)}]}
user_record = users.find_one(query)
if user_record is None:
logger.warning("Kein Benutzer für %r in DB %r gefunden.", username, db_name)
return None
query = {'$or': [{'Username': username}, {'username': username}]}
user_record_fallback = users.find_one(query)
if user_record_fallback is None:
logger.warning("Kein Benutzer für %r in DB %r gefunden.", dp.encrypt_text(username), db_name)
return None
else:
user_record = user_record_fallback
stored_password = user_record.get('Password') or user_record.get('password')
if not verify_password(password, stored_password):
logger.warning("Falsches Passwort für Benutzer %r in DB %r.", username, db_name)
logger.warning("Falsches Passwort für Benutzer %r in DB %r.", dp.encrypt_text(username), db_name)
return None
# Automatische Migration alter Hashes auf das neue Format
if not stored_password.startswith("v1$"):
if stored_password and not stored_password.startswith("v1$"):
users.update_one({'_id': user_record['_id']}, {'$set': {'Password': hashing(password)}})
return user_record
@@ -531,40 +512,35 @@ def add_user(
):
"""
Add a new user to the database.
Args:
username (str): Username for the new user
password (str): Password for the new user
Returns:
bool: True if user was added successfully, False if password was too weak
"""
if not check_password_strength(password):
return False
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
try:
db = _get_tenant_db(client)
users = db['users']
if not check_password_strength(password):
return False
permission_defaults = build_default_permission_payload(permission_preset)
if isinstance(action_permissions, dict):
for key, value in action_permissions.items():
permission_defaults['actions'][str(key)] = bool(value)
if isinstance(page_permissions, dict):
for key, value in page_permissions.items():
permission_defaults['pages'][str(key)] = bool(value)
if permission_preset == "full_access":
can_admin_preset_based = True
else:
can_admin_preset_based = False
safe_name = name.strip() if name else ''
safe_last_name = last_name.strip() if last_name else ''
user_doc = {
'Username': username,
'Username': dp.encrypt_text(username),
'Password': hashing(password),
'Admin': can_admin_preset_based,
'Admin': (permission_preset == "full_access"),
'active_ausleihung': None,
'name': name.strip() if name else '',
'last_name': last_name.strip() if last_name else '',
'name': dp.encrypt_text(safe_name) if safe_name else '',
'last_name': dp.encrypt_text(safe_last_name) if safe_last_name else '',
'IsStudent': bool(is_student),
'PermissionPreset': permission_defaults['preset'],
'ActionPermissions': permission_defaults['actions'],
@@ -601,7 +577,7 @@ def student_card_exists(student_card_id):
def get_user_by_student_card(student_card_id):
"""Return user by student card id or None."""
"""Return user dict by student card id or None."""
normalized = normalize_student_card_id(student_card_id)
if not normalized:
return None
@@ -610,65 +586,44 @@ def get_user_by_student_card(student_card_id):
users = db['student_cards']
found_user = users.find_one({'SchülerName': normalized})
client.close()
# Do not call dp.decrypt_text() here because found_user is a MongoDB dictionary.
return found_user
def make_admin(username):
"""
Grant administrator privileges to a user.
Args:
username (str): Username of the user to promote
Returns:
bool: True if user was promoted successfully
"""
"""Grant administrator privileges to a user."""
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = _get_tenant_db(client)
users = db['users']
result = users.update_one({'Username': username}, {'$set': {'Admin': True}})
result = users.update_one({'Username': dp.encrypt_text(username)}, {'$set': {'Admin': True}})
if result.matched_count == 0:
result = users.update_one({'username': username}, {'$set': {'Admin': True}})
result = users.update_one({'username': dp.encrypt_text(username)}, {'$set': {'Admin': True}})
client.close()
return result.matched_count > 0
def remove_admin(username):
"""
Remove administrator privileges from a user.
Args:
username (str): Username of the user to demote
Returns:
bool: True if user was demoted successfully
"""
"""Remove administrator privileges from a user."""
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = _get_tenant_db(client)
users = db['users']
result = users.update_one({'Username': username}, {'$set': {'Admin': False}})
result = users.update_one({'Username': dp.encrypt_text(username)}, {'$set': {'Admin': False}})
if result.matched_count == 0:
result = users.update_one({'username': username}, {'$set': {'Admin': False}})
result = users.update_one({'username': dp.encrypt_text(username)}, {'$set': {'Admin': False}})
client.close()
return result.matched_count > 0
def get_user(username):
"""
Retrieve a specific user by username.
Args:
username (str): Username to search for
Returns:
dict: User document or None if not found
"""
"""Retrieve a specific user by username."""
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
try:
def find_in_db(database_name):
db = client[database_name]
users = db['users']
return users.find_one({'Username': username}) or users.find_one({'username': username})
return users.find_one({'Username': dp.encrypt_text(username)}) or users.find_one({'username': dp.encrypt_text(username)}) or users.find_one({'username': username}) or users.find_one({'Username': username})
# Try current tenant first when available
tenant_db, tenant_id = _resolve_request_tenant_db()
if tenant_db:
user = find_in_db(tenant_db)
@@ -681,7 +636,6 @@ def get_user(username):
)
return None
# Fallback to default configured database
user = find_in_db(cfg.MONGODB_DB)
if user:
return user
@@ -692,147 +646,89 @@ def get_user(username):
def check_admin(username):
"""
Check if a user has administrator privileges.
Args:
username (str): Username to check
Returns:
bool: True if user is an administrator, False otherwise
"""
"""Check if a user has administrator privileges."""
user = get_user(username)
return bool(user and user.get('Admin', False))
def update_active_ausleihung(username, id_item, ausleihung):
"""
Update a user's active borrowing record.
Args:
username (str): Username of the user
id_item (str): ID of the borrowed item
ausleihung (str): ID of the borrowing record
Returns:
bool: True if successful
"""
"""Update a user's active borrowing record."""
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = _get_tenant_db(client)
users = db['users']
users.update_one({'Username': username}, {'$set': {'active_ausleihung': {'Item': id_item, 'Ausleihung': ausleihung}}})
result = users.update_one(
{'Username': dp.encrypt_text(username)},
{'$set': {'active_ausleihung': {'Item': id_item, 'Ausleihung': ausleihung}}}
)
if result.matched_count == 0:
users.update_one(
{'username': dp.encrypt_text(username)},
{'$set': {'active_ausleihung': {'Item': id_item, 'Ausleihung': ausleihung}}}
)
client.close()
return True
def get_active_ausleihung(username):
"""
Get a user's active borrowing record.
Args:
username (str): Username of the user
Returns:
dict: Active borrowing information or None
"""
"""Get a user's active borrowing record."""
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = _get_tenant_db(client)
users = db['users']
user = users.find_one({'Username': username})
return user['active_ausleihung']
user = users.find_one({'Username': dp.encrypt_text(username)}) or users.find_one({'username': dp.encrypt_text(username)})
client.close()
if not user:
return None
return user.get('active_ausleihung')
def has_active_borrowing(username):
"""
Check if a user currently has an active borrowing.
Args:
username (str): Username to check
Returns:
bool: True if user has an active borrowing, False otherwise
"""
"""Check if a user currently has an active borrowing."""
try:
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = _get_tenant_db(client)
users = db['users']
user = users.find_one({'username': username})
if not user:
user = users.find_one({'Username': username})
if not user:
client.close()
return False
has_active = user.get('active_borrowing', False)
user = users.find_one({'username': dp.encrypt_text(username)}) or users.find_one({'Username': dp.encrypt_text(username)})
client.close()
return has_active
if not user:
return False
return user.get('active_borrowing', False)
except Exception as e:
return False
def delete_user(username):
"""
Delete a user from the database.
Administrative function for removing user accounts.
Args:
username (str): Username of the account to delete
Returns:
bool: True if user was deleted successfully, False otherwise
"""
"""Delete a user from the database."""
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = _get_tenant_db(client)
users = db['users']
result = users.delete_one({'username': username})
client.close()
result = users.delete_one({'username': dp.encrypt_text(username)})
if result.deleted_count == 0:
# Try with different field name
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = _get_tenant_db(client)
users = db['users']
result = users.delete_one({'Username': username})
client.close()
result = users.delete_one({'Username': dp.encrypt_text(username)})
client.close()
return result.deleted_count > 0
def update_active_borrowing(username, item_id, status):
"""
Update a user's active borrowing status.
Args:
username (str): Username of the user
item_id (str): ID of the borrowed item or None if returning
status (bool): True if borrowing, False if returning
Returns:
bool: True if successful, False on error
"""
"""Update a user's active borrowing status."""
try:
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = _get_tenant_db(client)
users = db['users']
result = users.update_one(
{'username': username},
{'$set': {
'active_borrowing': status,
'borrowed_item': item_id if status else None
}}
)
update_data = {'$set': {'active_borrowing': status, 'borrowed_item': item_id if status else None}}
result = users.update_one({'username': dp.encrypt_text(username)}, update_data)
if result.matched_count == 0:
result = users.update_one(
{'Username': username},
{'$set': {
'active_borrowing': status,
'borrowed_item': item_id if status else None
}}
)
result = users.update_one({'Username': dp.encrypt_text(username)}, update_data)
client.close()
return result.modified_count > 0
except Exception as e:
@@ -840,43 +736,37 @@ def update_active_borrowing(username, item_id, status):
def get_name(username):
"""
Retrieve the name that is assosiated with the username.
Returns:
str: String of name
"""
"""Retrieve the name that is associated with the username."""
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = _get_tenant_db(client)
users = db['users']
user = users.find_one({'Username': username})
name = user.get("name")
return name
user = users.find_one({'Username': dp.encrypt_text(username)}) or users.find_one({'username': dp.encrypt_text(username)})
client.close()
if not user or not user.get("name"):
return ""
return dp.decrypt_text(user.get("name"))
def get_last_name(username):
"""
Retrieve the last_name that is assosiated with the username.
Returns:
str: String of last_name
"""
"""Retrieve the last_name that is associated with the username."""
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = _get_tenant_db(client)
users = db['users']
user = users.find_one({'Username': username})
name = user.get("last_name")
return name
user = users.find_one({'Username': dp.encrypt_text(username)}) or users.find_one({'username': dp.encrypt_text(username)})
client.close()
if not user or not user.get("last_name"):
return ""
return dp.decrypt_text(user.get("last_name"))
def get_all_users():
"""
Retrieve all users from the database.
Administrative function for user management.
Returns:
list: List of all user documents
"""
"""Retrieve all users from the database."""
try:
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = _get_tenant_db(client)
@@ -887,65 +777,58 @@ def get_all_users():
except Exception as e:
return []
def update_password(username, new_password):
"""
Update a user's password with a new one.
Args:
username (str): Username of the user
new_password (str): New password to set
Returns:
bool: True if password was updated successfully, False otherwise
"""
"""Update a user's password with a new one."""
try:
if not check_password_strength(new_password):
return False
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = _get_tenant_db(client)
users = db['users']
# Hash the new password
hashed_password = hashing(new_password)
# Update the user's password
result = users.update_one(
{'Username': username},
{'Username': dp.encrypt_text(username)},
{'$set': {'Password': hashed_password}}
)
if result.matched_count == 0:
result = users.update_one(
{'username': dp.encrypt_text(username)},
{'$set': {'Password': hashed_password}}
)
client.close()
return result.modified_count > 0
except Exception as e:
print(f"Error updating password: {e}")
return False
def update_user_name(username, name, last_name):
"""
Update a user's name and last name.
Args:
username (str): Username of the user
name (str): New first name
last_name (str): New last name
Returns:
bool: True if updated successfully, False otherwise
"""
"""Update a user's name and last name."""
try:
name_alias = build_name_synonym(name, last_name)
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = _get_tenant_db(client)
users = db['users']
safe_name = dp.encrypt_text(name.strip()) if name else ''
safe_last_name = dp.encrypt_text(last_name.strip()) if last_name else ''
result = users.update_one(
{'Username': username},
{'$set': {'name': name_alias, 'last_name': ''}}
{'Username': dp.encrypt_text(username)},
{'$set': {'name': safe_name, 'last_name': safe_last_name}}
)
if result.matched_count == 0:
result = users.update_one(
{'username': dp.encrypt_text(username)},
{'$set': {'name': safe_name, 'last_name': safe_last_name}}
)
client.close()
return True
except Exception as e:
print(f"Error updating user name: {e}")
return False
return False
+78 -31
View File
@@ -1,51 +1,98 @@
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from modules.module_registry import ModuleRegistry as mr
from email.mime.text import MIMEText
import smtplib
import time
import Web.modules.database.settings as cfg
def _build_smtp_client():
smtp = smtplib.SMTP(cfg.EMAIL_SMTP_HOST, cfg.EMAIL_SMTP_PORT, timeout=cfg.EMAIL_TIMEOUT_SECONDS)
smtp = smtplib.SMTP(
cfg.EMAIL_SMTP_HOST,
cfg.EMAIL_SMTP_PORT,
timeout=cfg.EMAIL_TIMEOUT_SECONDS,
)
smtp.ehlo()
if cfg.EMAIL_USE_TLS:
smtp.starttls()
smtp.ehlo()
if cfg.EMAIL_USERNAME:
smtp.login(cfg.EMAIL_USERNAME, cfg.EMAIL_PASSWORD or '')
smtp.login(cfg.EMAIL_USERNAME, cfg.EMAIL_PASSWORD or "")
return smtp
def send(email: list, subject: str, note: str, sender: str) -> bool:
"""
Sends the email with the link to the Clients
Input:
- email: Email list of all the addresses to send the link to ["","",""]
- subject: Subject of the email
- note: Note that is send with the Emails
def send(email: list | str, subject: str, note: str, sender: str) -> bool:
"""Sends the email with the link to the Clients."""
if not cfg.MODULES.is_enabled("mail"):
print("Debug: Module not enabled")
return False
if isinstance(email, str):
email = [email]
body_message = note
HTML_SIGNATURE = f"""
<table cellpadding="0" cellspacing="0" border="0" style="font-family: Arial, Helvetica, sans-serif; font-size: 13px; color: #333333; line-height: 1.5;">
<tr>
<td>
<p style="margin:0 0 12px 0;">Mit freundlichen Grüßen</p>
<p style="margin:0;"><strong style="font-size:16px;">Automatisierter Email Verteiler für die Schule: {cfg.get_school_info().get("name")}</strong><br></p><br>
<p style="margin:12px 0 0 0;"><strong>Invario UG</strong><br>Am Sportplatz 10<br>83052 Bruckmühl</p>
</td>
</tr>
</table>
"""
text_content = f"{body_message}\n\nMit freundlichen Grüßen\n{sender}\n"
html_content = f"""
<html>
<body>
<p>{body_message}</p>
<br>
{HTML_SIGNATURE}
</body>
</html>
"""
mails_per_second = 10
interval = 1.0 / mails_per_second
Output:
- bool: true if the sending worked and false if it didnt
"""
if not mr.registry.is_enabled('mail'):
return False
else:
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender or cfg.EMAIL_FROM_ADDRESS or cfg.EMAIL_USERNAME
msg['To'] = ', '.join(email) if isinstance(email, (list, tuple)) else str(email)
msg.attach(MIMEText(note))
smtp = None
try:
smtp = _build_smtp_client()
smtp.sendmail(from_addr=msg['From'], to_addrs=email, msg=msg.as_string())
return True
except Exception:
return False
smtp = _build_smtp_client()
for i, recipient in enumerate(email):
start_time = time.time()
msg = MIMEMultipart("alternative")
msg["Subject"] = str(subject)
msg["From"] = f"{sender} <{cfg.EMAIL_USERNAME}>"
msg["To"] = str(recipient)
msg.attach(MIMEText(text_content, "plain"))
msg.attach(MIMEText(html_content, "html"))
smtp.sendmail(
from_addr=cfg.EMAIL_USERNAME,
to_addrs=[recipient],
msg=msg.as_string()
)
elapsed_time = time.time() - start_time
sleep_time = interval - elapsed_time
if sleep_time > 0 and i < len(email) - 1:
time.sleep(sleep_time)
return True
except Exception as e:
print(f"Debug: Fehler beim Senden der E-Mail: {e}")
return False
finally:
try:
if smtp:
smtp.quit()
except Exception:
pass
try:
smtp.quit()
except Exception:
pass
+3 -3
View File
@@ -22,7 +22,7 @@ def _resolve_public_base_url() -> str:
subdomain = ''
if tenant_context:
subdomain = getattr(tenant_context, 'subdomain', '') or getattr(tenant_context, 'tenant_id', '') or ''
return f"https://{subdomain}.invario.eu" if subdomain else "https://invario.eu"
return (f"https://{subdomain}.invario-software.de") if subdomain else "https://invario-software.de"
def _current_tenant_id() -> str:
@@ -252,8 +252,8 @@ def new(date_start: str, date_end: str, time_span: list, slots, slot_length, use
if calendar_link:
email_body += f"\n\nKalendereintrag: {calendar_link}"
if normalized_mail and cfg.EMAIL_ENABLED:
mail_service.send(normalized_mail, subject, email_body)
#if normalized_mail and cfg.EMAIL_ENABLED:
mail_service.send(normalized_mail, subject, email_body, f"Terminplanungssystem {cfg.SCHOOL_INFO_DEFAULT.get("name")}")
return {
'appointment_id': id_str,
+80 -58
View File
@@ -20,40 +20,53 @@ logger = logging.getLogger(__name__)
# VAPID keys for push notifications
VAPID_PUBLIC_KEY = os.getenv('VAPID_PUBLIC_KEY', '')
VAPID_PRIVATE_KEY = os.getenv('VAPID_PRIVATE_KEY', '')
VAPID_SUBJECT = os.getenv('VAPID_SUBJECT', f'mailto:admin@{os.getenv("SERVER_NAME", "localhost")}')
VAPID_SUBJECT = os.getenv('VAPID_SUBJECT', f'mailto:support@invario-software.de')
# VAPID keys file paths
VAPID_PRIVATE_PEM = os.path.join(os.path.dirname(__file__), 'vapid_private.pem')
VAPID_PUBLIC_PEM = os.path.join(os.path.dirname(__file__), 'vapid_public.pem')
# Auto-generate VAPID keys if none are provided
if not VAPID_PUBLIC_KEY or not VAPID_PRIVATE_KEY:
try:
from py_vapid import Vapid, b64urlencode
from cryptography.hazmat.primitives import serialization
# Load or auto-generate VAPID keys
try:
from py_vapid import Vapid, b64urlencode
from cryptography.hazmat.primitives import serialization
if not os.path.exists(VAPID_PRIVATE_PEM) or not os.path.exists(VAPID_PUBLIC_PEM):
vapid = Vapid()
if not os.path.exists(VAPID_PRIVATE_PEM):
vapid.generate_keys()
vapid.save_key(VAPID_PRIVATE_PEM)
vapid.save_public_key(VAPID_PUBLIC_PEM)
logger.info("Auto-generated new VAPID keys")
else:
vapid = Vapid.from_file(VAPID_PRIVATE_PEM)
raw_pub = vapid.public_key.public_bytes(
serialization.Encoding.X962,
serialization.PublicFormat.UncompressedPoint
)
VAPID_PUBLIC_KEY = b64urlencode(raw_pub).decode('utf-8')
VAPID_PRIVATE_KEY = VAPID_PRIVATE_PEM
except Exception as e:
logger.error(f'Could not load or generate VAPID keys: {e}')
vapid.generate_keys()
vapid.save_key(VAPID_PRIVATE_PEM)
vapid.save_public_key(VAPID_PUBLIC_PEM)
logger.info("Auto-generated new VAPID keys")
else:
vapid = Vapid.from_file(VAPID_PRIVATE_PEM)
raw_pub = vapid.public_key.public_bytes(
serialization.Encoding.X962,
serialization.PublicFormat.UncompressedPoint
)
encoded_pub = b64urlencode(raw_pub)
if isinstance(encoded_pub, bytes):
VAPID_PUBLIC_KEY = encoded_pub.decode('utf-8')
else:
VAPID_PUBLIC_KEY = encoded_pub
VAPID_PRIVATE_KEY = VAPID_PRIVATE_PEM
except Exception as e:
logger.error(f'Could not load or generate VAPID keys: {e}')
VAPID_PUBLIC_KEY = os.getenv('VAPID_PUBLIC_KEY', '')
VAPID_PRIVATE_KEY = os.getenv('VAPID_PRIVATE_KEY', '')
VAPID_SUBJECT = os.getenv('VAPID_SUBJECT', 'mailto:support@invario-software.de')
# Push service endpoint (typically Firebase or Web Push Service)
FCM_API_KEY = os.getenv('FCM_API_KEY', '') # Firebase API key
FCM_API_KEY = os.getenv('FCM_API_KEY', '')
def _get_vapid_public():
return VAPID_PUBLIC_KEY
def _get_username_hash(username):
"""Generates a deterministic hash for database lookups."""
if not username:
@@ -109,29 +122,33 @@ def get_user_subscriptions(username):
def save_push_subscription(username, subscription_obj):
"""
Save a new push subscription for a user with field-level encryption.
"""
import traceback # Hilft uns, Fehler genau zu sehen
try:
print("--- DEBUG PUSH PAYLOAD ---")
print(subscription_obj)
endpoint = subscription_obj.get('endpoint')
if not endpoint:
logger.warning('Invalid subscription object: missing endpoint')
keys = subscription_obj.get('keys', {})
if not endpoint or not keys.get('p256dh') or not keys.get('auth'):
print(
f"DEBUG FEHLER: Keys fehlen! Endpoint: {bool(endpoint)}, p256dh: {bool(keys.get('p256dh'))}, auth: {bool(keys.get('auth'))}")
return False
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
subs_col = get_push_subscriptions_collection(db)
# Create unique hash of subscription using plaintext data to avoid duplicates
sub_hash = hashlib.shake_256(
f"{username}:{endpoint}".encode('utf-8')
).hexdigest()
).hexdigest(32)
# Check if subscription already exists by Hash
existing = subs_col.find_one({
'SubscriptionHash': sub_hash
})
if existing:
subs_col.update_one(
{'_id': existing['_id']},
@@ -143,10 +160,10 @@ def save_push_subscription(username, subscription_obj):
logger.info('Updated existing push subscription')
client.close()
return True
# Format keys as JSON string for your encrypt_text module
keys_str = json.dumps(subscription_obj.get('keys', {}))
# Save new subscription, encrypting sensitive fields
subscription_doc = {
'UsernameHash': _get_username_hash(username),
@@ -159,39 +176,37 @@ def save_push_subscription(username, subscription_obj):
'LastUsed': datetime.datetime.now(),
'UserAgent': subscription_obj.get('userAgent', ''),
}
subs_col.insert_one(subscription_doc)
logger.info('Saved new encrypted push subscription')
client.close()
return True
except Exception as e:
logger.error(f'Error saving push subscription: {e}')
print(f"DEBUG ABSTURZ in save_push_subscription: {e}")
traceback.print_exc()
return False
def remove_push_subscription(username, endpoint):
"""
Remove a push subscription by making it inactive.
"""
try:
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
subs_col = get_push_subscriptions_collection(db)
# Recreate the deterministic hash to find the specific subscription
sub_hash = hashlib.shake_256(
f"{username}:{endpoint}".encode('utf-8')
).hexdigest()
).hexdigest(32)
result = subs_col.update_one(
{'SubscriptionHash': sub_hash},
{'$set': {'IsActive': False}}
)
client.close()
return result.modified_count > 0
return result.matched_count > 0
except Exception as e:
logger.error(f'Error removing push subscription: {e}')
return False
@@ -299,8 +314,8 @@ def _send_fcm_notification(subscription, payload):
def _send_web_push_notification(subscription, payload):
try:
from pywebpush import webpush
from pywebpush import webpush, WebPushException
webpush(
subscription_info={
'endpoint': subscription['Endpoint'],
@@ -310,18 +325,25 @@ def _send_web_push_notification(subscription, payload):
vapid_private_key=VAPID_PRIVATE_KEY,
vapid_claims={'sub': VAPID_SUBJECT},
timeout=10,
ttl=3600
ttl=3600
)
return True
except ImportError:
logger.warning('pywebpush not installed. pip install pywebpush')
return False
except Exception as e:
logger.error(f'Web push error: {e}')
return False
# HÄRTUNG: Spezifische WebPush-Fehler abfangen
except WebPushException as ex:
# HTTP 404 (Not Found) oder 410 (Gone) bedeuten: Abo existiert nicht mehr
if ex.response is not None and ex.response.status_code in [404, 410]:
logger.info(f"Subscription expired or revoked (Code {ex.response.status_code}). Marking inactive.")
return False # False signalisiert der übergeordneten Funktion, das Abo zu deaktivieren
logger.error(f'Web push failed with code {ex.response.status_code if ex.response else "Unknown"}: {ex}')
return False
except Exception as e:
logger.error(f'Unexpected Web push error: {e}')
return False
def _mark_subscription_inactive(subscription_id):
try:
+3 -1
View File
@@ -1,4 +1,5 @@
flask
flask-wtf
werkzeug
gunicorn
pymongo
@@ -15,4 +16,5 @@ openpyxl
cryptography>=42.0.0
pywebpush
py-vapid>=1.9.0
beautifulsoup4
beautifulsoup4
pywebpush
+26 -17
View File
@@ -25,7 +25,7 @@ class PushNotificationManager {
* Initialize push notification system
* Must be called after page load
*/
async init() {
async init(providedKey = null) {
if (!this.isSupported) {
console.log('Push notifications not supported in this browser');
return false;
@@ -49,11 +49,18 @@ class PushNotificationManager {
}
}
// Fetch VAPID public key from server
// Wenn der Key direkt aus dem Template übergeben wurde, nutze diesen (spart einen Request)
if (providedKey) {
this.vapidKey = providedKey;
return true;
}
// Ansonsten: Fetch VAPID public key from server
const keyResponse = await fetch('/api/push/vapid-key');
if (keyResponse.ok) {
const keyData = await keyResponse.json();
this.vapidKey = keyData.vapid_key;
// WICHTIG: Muss exakt mit dem Python-JSON-Key übereinstimmen!
this.vapidKey = keyData.publicKey;
} else {
console.warn('Failed to fetch VAPID key');
return false;
@@ -154,20 +161,22 @@ class PushNotificationManager {
try {
const subscription = await this.serviceWorkerRegistration.pushManager.getSubscription();
if (!subscription) {
console.warn('No active push subscription');
return false;
}
// Remove subscription on server
const success = await this.removeSubscriptionFromServer(subscription);
// Unsubscribe from push service
if (success) {
await subscription.unsubscribe();
return true;
}
return false;
// Best-Effort: Server benachrichtigen (Eigener try/catch Block!)
try {
await this.removeSubscriptionFromServer(subscription);
} catch (serverError) {
// Fehler vom Server ignorieren wir absichtlich.
// Das Skript läuft weiter, statt hier abzubrechen!
console.warn('Server-Abmeldung fehlgeschlagen, lösche lokal trotzdem:', serverError);
}
// WICHTIG: Das hier wird jetzt garantiert ausgeführt
await subscription.unsubscribe();
return true;
} catch (error) {
console.error('Failed to unsubscribe from push notifications:', error);
return false;
@@ -324,7 +333,7 @@ const pushNotificationManager = new PushNotificationManager();
/**
* Show notification subscription UI (typically in settings)
*/
function showPushNotificationSettings() {
function showPushNotificationSettings(vapidPublicKey) {
const container = document.getElementById('push-notification-settings');
if (!container) return;
@@ -350,9 +359,9 @@ function showPushNotificationSettings() {
container.innerHTML = html;
// Set up button handler
// Set up button handler and pass the VAPID public key to init()
const toggleBtn = document.getElementById('toggle-push-btn');
pushNotificationManager.init().then(() => {
pushNotificationManager.init(vapidPublicKey).then(() => {
updatePushStatus();
});
+29 -20
View File
@@ -1148,7 +1148,7 @@
{% if current_permissions.pages.get('tutorial_page', False) %}
<li><a class="dropdown-item" href="{{ url_for('tutorial_page') }}">Tutorial</a></li>
{% endif %}
{% if current_permissions.pages.get('admin_school_settings', False) %}
{% if current_permissions.actions.get('can_manage_settings', False) %}
<li><a class="dropdown-item" href="{{ url_for('admin_school_settings') }}">Schulstammdaten</a></li>
{% endif %}
{% if current_permissions.actions.get('can_view_logs', False) or current_permissions.pages.get('admin_audit_dashboard', False) %}
@@ -1257,7 +1257,7 @@
{% if current_permissions.pages.get('manage_locations', False) %}
<li><a class="dropdown-item" href="{{ url_for('manage_locations') }}">Orte verwalten</a></li>
{% endif %}
{% if current_permissions.pages.get('admin_school_settings', False) %}
{% if current_permissions.actions.get('can_manage_settings', False) %}
<li><a class="dropdown-item" href="{{ url_for('admin_school_settings') }}">Schulstammdaten</a></li>
{% endif %}
{% if current_permissions.pages.get('admin_borrowings', False) %}
@@ -1375,9 +1375,11 @@
<li><a class="dropdown-item" href="{{ url_for('library_loans_admin') }}">Ausleihen / Defekte Items</a></li>
{% endif %}
{% if student_cards_module_enabled %}
{% if current_permissions.actions.get('can_manage_users', False) %}
<li><a class="dropdown-item" href="{{ url_for('student_cards_admin') }}">Bibliotheksausweis</a></li>
{% endif %}
{% if current_permissions.pages.get('admin_school_settings', False) %}
{% endif %}
{% if current_permissions.actions.get('can_manage_settings', False) %}
<li><a class="dropdown-item" href="{{ url_for('admin_school_settings') }}">Schulstammdaten</a></li>
{% endif %}
<li><hr class="dropdown-divider"></li>
@@ -1619,11 +1621,10 @@
<div id="cookie-banner" role="dialog" aria-live="polite" aria-label="Cookie-Hinweis">
<div class="cb-inner">
<div class="cb-text">
Wir verwenden technisch notwendige Cookies, um Ihre Sitzung zu verwalten und die Anwendung bereitzustellen. Bitte akzeptieren Sie Cookies, um fortzufahren.
Wir verwenden ausschließlich technisch notwendige Cookies, um Ihre Sitzung zu verwalten und die Anwendung bereitzustellen. Bitte bestätigen Sie dies, um fortzufahren.
</div>
<div class="cb-actions">
<button class="btn-decline" id="cookie-decline">Ablehnen</button>
<button class="btn-accept" id="cookie-accept">Akzeptieren</button>
<button class="btn-accept" id="cookie-accept">Notwendige Cookies akzeptieren</button>
</div>
</div>
</div>
@@ -1697,7 +1698,7 @@
<option value="Orte verwalten"></option>
{% endif %}
{% if current_permissions.pages.get('admin_school_settings', False) %}
{% if current_permissions.actions.get('can_manage_settings', False) %}
<option value="Schulstammdaten"></option>
{% endif %}
@@ -1728,31 +1729,39 @@
(function(){
function getCookie(name){
const v = document.cookie.split(';').map(s=>s.trim());
for(const c of v){ if(c.startsWith(name+'=')) return decodeURIComponent(c.split('=')[1]); }
for(const c of v){
if(c.startsWith(name+'=')) return decodeURIComponent(c.split('=')[1]);
}
return null;
}
function setCookie(name, value, days){
const d = new Date(); d.setTime(d.getTime() + (days*24*60*60*1000));
const d = new Date();
d.setTime(d.getTime() + (days*24*60*60*1000));
document.cookie = name + '=' + encodeURIComponent(value) + ';expires=' + d.toUTCString() + ';path=/;SameSite=Lax';
}
function showBanner(){ var el = document.getElementById('cookie-banner'); if(el) el.style.display = 'block'; }
function hideBanner(){ var el = document.getElementById('cookie-banner'); if(el) el.style.display = 'none'; }
// If not decided yet, show banner and block app until decision
function showBanner(){
var el = document.getElementById('cookie-banner');
if(el) el.style.display = 'block';
}
function hideBanner(){
var el = document.getElementById('cookie-banner');
if(el) el.style.display = 'none';
}
// Prüfen, ob der Nutzer bereits zugestimmt hat
const consent = getCookie('cookie_consent');
if(!consent){
showBanner();
// Optionally blur content until consent
document.body.style.filter = 'none';
}
// Nur noch der Akzeptieren-Button für vitale Cookies ist vorhanden
document.getElementById('cookie-accept')?.addEventListener('click', function(){
setCookie('cookie_consent','accepted',365);
setCookie('cookie_consent', 'vital_accepted', 365);
hideBanner();
});
document.getElementById('cookie-decline')?.addEventListener('click', function(){
setCookie('cookie_consent','declined',365);
window.location.href = 'https://www.ecosia.org/';
});
const username = {{ (session['username'] if 'username' in session else '')|tojson }};
const isTutorialPage = window.location.pathname === {{ url_for('tutorial_page')|tojson }};
@@ -1814,7 +1823,7 @@
{ label: 'Orte verwalten', keywords: ['orte verwalten', 'orte', 'location'], url: {{ url_for('manage_locations')|tojson }} },
{% endif %}
{% if current_permissions.pages.get('admin_school_settings', False) %}
{% if current_permissions.actions.get('can_manage_settings', False) %}
{ label: 'Schulstammdaten', keywords: ['schule', 'settings', 'stammdaten', 'school settings'], url: {{ url_for('admin_school_settings')|tojson }} },
{% endif %}
+30 -15
View File
@@ -520,7 +520,16 @@
window.openDamageReportPrompt = openDamageReportPrompt;
function openDamageInvoiceModal(row, description) {
if (!damageInvoiceModal || !damageInvoiceForm) {
const modal = document.getElementById('damage-invoice-modal');
const form = document.getElementById('damage-invoice-form');
const inputItem = document.getElementById('damage-invoice-item');
const inputBorrower = document.getElementById('damage-invoice-borrower');
const inputCode = document.getElementById('damage-invoice-code');
const inputAmount = document.getElementById('damage-invoice-amount');
const inputReason = document.getElementById('damage-invoice-reason');
if (!modal || !form) {
console.error("Modal oder Formular nicht gefunden.");
return;
}
@@ -530,23 +539,29 @@
const itemCode = row.dataset.itemCode || '';
const itemCost = row.dataset.itemCost || '';
damageInvoiceForm.action = "{{ url_for('admin_create_invoice', borrow_id='__BORROW_ID__') }}".replace('__BORROW_ID__', borrowId);
damageInvoiceItem.value = itemName;
damageInvoiceBorrower.value = borrower;
damageInvoiceCode.value = itemCode;
damageInvoiceAmount.value = String(itemCost).replace(' EUR', '').trim();
damageInvoiceReason.value = description || `Schaden gemeldet für ${itemName}`;
damageInvoiceModal.style.display = 'block';
damageInvoiceAmount.focus();
form.action = "{{ url_for('admin_create_invoice', borrow_id='__BORROW_ID__') }}".replace('__BORROW_ID__', borrowId);
inputItem.value = itemName;
inputBorrower.value = borrower;
inputCode.value = itemCode;
inputAmount.value = String(itemCost).replace(' EUR', '').trim();
inputReason.value = description || `Schaden gemeldet für ${itemName}`;
modal.style.display = 'block';
inputAmount.focus();
}
function closeDamageInvoiceModal() {
const modal = document.getElementById('damage-invoice-modal');
if (modal) {
modal.style.display = 'none';
}
}
window.openDamageInvoiceModal = openDamageInvoiceModal;
function closeDamageInvoiceModal() {
if (damageInvoiceModal) {
damageInvoiceModal.style.display = 'none';
}
}
window.closeDamageInvoiceModal = closeDamageInvoiceModal;
if (damageInvoiceModal) {
damageInvoiceModal.addEventListener('click', function(event) {
+7 -6
View File
@@ -1371,7 +1371,8 @@
await loadLibraryItems(); // Daten neu laden
// renderTable(); // Ggf. Tabelle neu rendern
} else {
alert('Fehler: ' + result.message);
await loadLibraryItems();
closeEditLibraryModal();
}
} catch (error) {
console.error('Update failed:', error);
@@ -1416,8 +1417,8 @@
<div>
<label for="editLibraryType">Medientyp</label>
<select id="editLibraryType" style="width: 100%;">
<option value="book">Buch</option>
<option value="schoolbook">Schulbuch</option>
<option value="Buch">Buch</option>
<option value="Schulbuch">Schulbuch</option>
<option value="cd">CD</option>
<option value="dvd">DVD</option>
<option value="other">Sonstige Medien</option>
@@ -1451,14 +1452,14 @@
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; border-bottom: 1px solid #eee; padding-bottom: 10px;">
<strong style="color: #0ea5e9;">Gruppen-Range (Total: <span id="editLibraryGroupCount"></span>)</strong>
</div>
<p style="margin: 5px 0; font-size: 12px; color: #555;">
Alle Codes in dieser Gruppe:
</p>
<!-- Hier wird die Liste als Komma-Text eingefügt -->
<div id="editLibraryAllCodes" style="font-family: monospace; font-size: 14px; font-weight: bold; color: #333; margin-top: 5px;"></div>
<div style="margin-top: 15px; font-size: 11px; background: #e0f2fe; padding: 8px; border-radius: 4px;">
<strong>Hinweis:</strong> Änderungen an Titel/Ort/Beschreibung werden auf <strong>alle</strong> Exemplare der Range übertragen.
</div>
+1 -1
View File
@@ -89,7 +89,7 @@
<script>
document.addEventListener('DOMContentLoaded', function() {
if (typeof showPushNotificationSettings === 'function') {
showPushNotificationSettings();
showPushNotificationSettings('{{ vapid_public_key }}');
}
});
</script>
+2 -6
View File
@@ -25,9 +25,6 @@
<div class="content">
<div class="form-card">
<form method="POST" action="{{ url_for('register') }}">
<!-- CSRF-Schutz (Zwingend erforderlich für POST) -->
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<div class="form-group">
<label for="name">Vorname</label>
@@ -65,17 +62,16 @@
<div class="input-container">
<span class="input-icon">🔒</span>
<!-- HTML5 Pattern blockiert unsichere Passwörter vor dem Absenden -->
<input type="password"
<input
id="password"
name="password"
placeholder="Geben Sie ein sicheres Passwort ein"
required
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{12,}">
</div>
<button type="button" class="btn-secondary" id="toggle-pw-btn" onclick="togglePasswordVisibility()" title="Passwort anzeigen/verbergen">👁️</button>
</div>
<div class="pw-actions">
<button type="button" class="btn-secondary" onclick="generateSecurePassword()">🎲 Automatisches Passwort generieren</button>
<button type="button" class="btn-secondary" onclick="generateSecurePassword()">Passwort generieren</button>
</div>
</div>
+3 -3
View File
@@ -20,14 +20,14 @@
"key": "Web/certs/key.pem"
},
"email": {
"enabled": false,
"smtp_host": "smtp.gmail.com",
"enabled": true,
"smtp_host": "",
"smtp_port": 587,
"use_tls": true,
"username": "",
"password": "",
"from_address": "",
"default_sender_name": "Invario Inventarprogramm",
"default_sender_name": "Invario Email Service",
"timeout_seconds": 30
},
"images": {
+2 -30
View File
@@ -82,7 +82,6 @@ while i < len(lines):
stripped = line.lstrip(" ")
indent = leading_spaces(line)
# Check if we're starting the app service
if not in_app_service and re.match(r"^\s*app:\s*$", line):
in_app_service = True
app_indent = indent
@@ -92,9 +91,7 @@ while i < len(lines):
i += 1
continue
# Check if we've exited the app service (found another top-level service)
if in_app_service and indent <= app_indent and re.match(r"^[A-Za-z0-9_-]+:\s*$", stripped):
# We've left the app service - insert image if we haven't already
if build_found and app_service_indent is not None:
out.append(f"{' ' * app_service_indent}image: {target_image}\n")
in_app_service = False
@@ -102,24 +99,20 @@ while i < len(lines):
i += 1
continue
# Process lines within the app service
if in_app_service:
if app_service_indent is None and indent > app_indent:
app_service_indent = indent
# Check for image key (already has an image, don't add)
if re.match(rf"^\s+image:\s*", line):
in_app_service = False
out.append(line)
i += 1
continue
# Check for build block
if re.match(rf"^\s+build:\s*$", line):
build_found = True
out.append(line)
i += 1
# Skip all lines that are part of the build block (indented more than app_service_indent)
while i < len(lines):
next_line = lines[i]
next_indent = leading_spaces(next_line)
@@ -130,12 +123,10 @@ while i < len(lines):
break
continue
# Insert image after build block before first property
if build_found and app_service_indent is not None and indent == app_service_indent:
# Check if this is a property line (not build)
if not re.match(rf"^\s+build:", line):
out.append(f"{' ' * app_service_indent}image: {target_image}\n")
build_found = False # Mark that we've inserted the image
build_found = False
out.append(line)
i += 1
@@ -144,7 +135,6 @@ while i < len(lines):
out.append(line)
i += 1
# If we ended while still in the app service, append image at the end
if in_app_service and build_found and app_service_indent is not None:
out.append(f"{' ' * app_service_indent}image: {target_image}\n")
@@ -377,18 +367,12 @@ with open(meta_file, 'r', encoding='utf-8') as f:
data = json.load(f)
tag = data.get('tag_name', '').strip()
url = ''
image_url = ''
for asset in data.get('assets', []):
if asset.get('name') == asset_name:
url = asset.get('browser_download_url', '').strip()
break
for asset in data.get('assets', []):
if asset.get('name') == f'inventarsystem-image-{tag}.tar.gz':
image_url = asset.get('browser_download_url', '').strip()
break
print(tag)
print(url)
print(image_url)
PY
}
@@ -401,7 +385,7 @@ main() {
need_cmd python3
need_cmd curl
local meta_file tag bundle_url image_url
local meta_file tag bundle_url
TMP_DIR="$(mktemp -d)"
meta_file="$TMP_DIR/release.json"
trap cleanup_tmp_dir EXIT
@@ -409,7 +393,6 @@ main() {
mapfile -t release_info < <(latest_tag_and_bundle_url "$meta_file")
tag="${release_info[0]:-}"
bundle_url="${release_info[1]:-}"
image_url="${release_info[2]:-}"
if [ -z "$tag" ] || [ -z "$bundle_url" ]; then
echo "Error: latest release metadata is incomplete."
@@ -425,17 +408,6 @@ main() {
pin_compose_app_image "$tag"
if [ -z "$image_url" ]; then
echo "Error: release image asset is missing"
exit 1
fi
curl -fL "$image_url" -o "$TMP_DIR/inventarsystem-image-$tag.tar.gz"
sudo docker load -i "$TMP_DIR/inventarsystem-image-$tag.tar.gz" >/dev/null
# Tagge das geladene Gitea-Image als latest
sudo docker tag "git.invario-software.eu/invario/inventarsystem:$tag" "git.invario-software.eu/invario/inventarsystem:latest" >/dev/null 2>&1 || true
if [ ! -f "$PROJECT_DIR/start.sh" ]; then
echo "Error: release bundle is missing start.sh"
exit 1
+5 -4
View File
@@ -200,6 +200,7 @@ sys.path.insert(0, "/app")
sys.path.insert(0, "/app/Web")
from Web.modules.database import settings
from pymongo import MongoClient
import Web.modules.inventarsystem.data_protection as dp
tenant_id = sys.argv[1].lower()
mode = sys.argv[2]
@@ -244,14 +245,14 @@ page_permissions = {
"manage_locations": True,
}
if db.users.count_documents({"Username": "admin"}) == 0:
if db.users.count_documents({"Username": dp.encrypt_text("admin")}) == 0:
db.users.insert_one({
"Username": "admin",
"Username": dp.encrypt_text("admin"),
"Password": hashed_pw_string,
"Admin": True,
"active_ausleihung": None,
"name": "Admin",
"last_name": "User",
"name": dp.encrypt_text("Admin"),
"last_name": dp.encrypt_text("User"),
"IsStudent": False,
"PermissionPreset": "full_access",
"ActionPermissions": action_permissions,
+3 -1
View File
@@ -1,4 +1,5 @@
flask
flask-wtf
werkzeug
gunicorn
pymongo==4.6.3
@@ -15,4 +16,5 @@ openpyxl
cryptography>=42.0.0
pywebpush
py-vapid>=1.9.0
beautifulsoup4
beautifulsoup4
pywebpush
+3
View File
@@ -1,6 +1,9 @@
#!/usr/bin/env bash
set -euo pipefail
sudo find /tmp -maxdepth 1 -name "tmp.*" -exec rm -rf {} +
echo "Cleaning up old temporary files in /tmp..."
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
cd "$SCRIPT_DIR"
+7 -44
View File
@@ -6,7 +6,6 @@ cd "$SCRIPT_DIR"
ENV_FILE="$SCRIPT_DIR/.docker-build.env"
APP_IMAGE_REPO="git.invario-software.eu/invario/inventarsystem"
DIST_DIR="$SCRIPT_DIR/dist"
RUNTIME_COMPOSE_OVERRIDE_FILE="$SCRIPT_DIR/.docker-compose.runtime.override.yml"
SUDO=""
@@ -279,52 +278,19 @@ EOF
fi
}
ensure_app_image_loaded() {
ensure_app_image_ready() {
if docker image inspect "$APP_IMAGE_VALUE" >/dev/null 2>&1; then
return 0
fi
local image_archive
image_archive="$(find_local_dist_image_archive || true)"
if [ -n "$image_archive" ]; then
echo "Loading app image from local dist artifact: $image_archive"
if docker load -i "$image_archive" >/dev/null 2>&1 && docker image inspect "$APP_IMAGE_VALUE" >/dev/null 2>&1; then
return 0
fi
echo "Warning: failed to load expected app image from $image_archive"
fi
echo "Error: local app image not found: $APP_IMAGE_VALUE"
echo "Run ./update.sh so the nightly updater loads the release image first."
exit 1
}
find_local_dist_image_archive() {
local tag archive
if [ ! -d "$DIST_DIR" ]; then
return 1
fi
tag="${APP_IMAGE_VALUE##*:}"
for archive in \
"$DIST_DIR/inventarsystem-image-$tag.tar.gz" \
"$DIST_DIR/inventarsystem-image-$tag.tar" \
"$DIST_DIR/inventarsystem-image.tar.gz" \
"$DIST_DIR/inventarsystem-image.tar"; do
if [ -f "$archive" ]; then
echo "$archive"
return 0
fi
done
archive="$(find "$DIST_DIR" -maxdepth 1 -type f \( -name 'inventarsystem-image-*.tar.gz' -o -name 'inventarsystem-image-*.tar' \) | sort | tail -n1)"
if [ -n "$archive" ]; then
echo "$archive"
echo "Attempting to pull registry image: $APP_IMAGE_VALUE"
if docker pull "$APP_IMAGE_VALUE" >/dev/null 2>&1; then
return 0
fi
return 1
echo "Error: app image not found locally and pull failed: $APP_IMAGE_VALUE"
echo "Run ./update.sh to pull the latest release image from the registry."
exit 1
}
configure_nuitka_mode() {
@@ -605,7 +571,6 @@ verify_stack_health() {
fi
compose_args+=(--env-file "$ENV_FILE")
# Try health check with optional restart on first failure
while [[ $retry_count -lt 2 ]]; do
echo "Waiting for containers to become healthy... (attempt $((retry_count + 1))/2)"
for _ in $(seq 1 60); do
@@ -623,7 +588,6 @@ verify_stack_health() {
sleep 2
done
# First failure: attempt recovery by restarting containers
if [[ $retry_count -eq 0 ]]; then
echo "Health check failed. Attempting to restart containers..."
docker compose "${compose_args[@]}" ps || true
@@ -636,7 +600,6 @@ verify_stack_health() {
fi
done
# Final failure
echo "Error: stack health check failed after restart attempt."
docker compose "${compose_args[@]}" ps || true
docker compose "${compose_args[@]}" logs --tail=120 app redis mongodb || true
@@ -654,7 +617,7 @@ resolve_app_image
configure_host_ports
ensure_min_docker_disk_space
detect_server_capacity
ensure_app_image_loaded
ensure_app_image_ready
write_env_file
write_runtime_compose_override
+31 -151
View File
@@ -2,7 +2,7 @@
set -euo pipefail
# Release-only updater for Docker deployment.
# Updates are pulled exclusively from Gitea Releases assets.
# Updates pull the deployment bundle from Gitea and the Docker Image via 'docker pull'.
PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_DIR="$PROJECT_DIR/logs"
@@ -11,13 +11,10 @@ STATE_FILE="$PROJECT_DIR/.release-version"
REPO_SLUG="Invario/Inventarsystem"
API_URL="https://git.invario-software.eu/api/v1/repos/$REPO_SLUG/releases/latest"
BUNDLE_ASSET="inventarsystem-docker-bundle.tar.gz"
APP_IMAGE_ASSET_PREFIX="inventarsystem-image-"
ENV_FILE="$PROJECT_DIR/.docker-build.env"
APP_IMAGE_REPO="git.invario-software.eu/invario/inventarsystem"
DIST_DIR="$PROJECT_DIR/dist"
COMPOSE_FILE="docker-compose-multitenant.yml"
MIN_ROOT_FREE_MB="${INVENTAR_MIN_ROOT_FREE_MB:-2048}"
DIST_KEEP_COUNT="${INVENTAR_DIST_KEEP_COUNT:-2}"
MODE="release"
mkdir -p "$LOG_DIR"
@@ -109,36 +106,6 @@ ensure_min_root_disk_space() {
fi
}
cleanup_old_dist_artifacts() {
local keep_count
keep_count="$DIST_KEEP_COUNT"
if [ ! -d "$DIST_DIR" ]; then
return 0
fi
if ! [[ "$keep_count" =~ ^[0-9]+$ ]]; then
keep_count=2
fi
mapfile -t archives < <(find "$DIST_DIR" -maxdepth 1 -type f \( -name 'inventarsystem-image-*.tar.gz' -o -name 'inventarsystem-image-*.tar' \) -printf '%T@ %p\n' | sort -nr | awk '{print $2}')
if [ "${#archives[@]}" -le "$keep_count" ]; then
return 0
fi
local index old_archive deleted=0
for (( index=keep_count; index<${#archives[@]}; index++ )); do
old_archive="${archives[$index]}"
if rm -f "$old_archive"; then
deleted=$((deleted + 1))
fi
done
if [ "$deleted" -gt 0 ]; then
log_message "Cleaned up $deleted old dist image archive(s)"
fi
}
cleanup_docker_dangling_images() {
if docker image prune -f >> "$LOG_FILE" 2>&1; then
log_message "Cleaned up dangling Docker images"
@@ -153,7 +120,6 @@ Usage: $0 [options]
Options:
--multitenant Use docker-compose-multitenant.yml (default)
development Install development build from Gitea Registry or local dist
-h, --help Show this help message
EOF
}
@@ -165,10 +131,6 @@ parse_args() {
COMPOSE_FILE="docker-compose-multitenant.yml"
shift
;;
development|dev)
MODE="development"
shift
;;
-h|--help)
usage
exit 0
@@ -216,14 +178,12 @@ create_backup() {
}
fetch_release_metadata() {
local meta_file
meta_file="$1"
local meta_file="$1"
curl -fsSL "$API_URL" -o "$meta_file"
}
parse_latest_tag() {
local meta_file
meta_file="$1"
local meta_file="$1"
python3 - <<'PY' "$meta_file"
import json, sys
with open(sys.argv[1], 'r', encoding='utf-8') as f:
@@ -233,9 +193,8 @@ PY
}
parse_asset_url() {
local meta_file asset_name
meta_file="$1"
asset_name="$2"
local meta_file="$1"
local asset_name="$2"
python3 - <<'PY' "$meta_file" "$asset_name"
import json, sys
meta_file, asset_name = sys.argv[1], sys.argv[2]
@@ -248,31 +207,6 @@ for asset in data.get('assets', []):
PY
}
load_release_image() {
local meta_file tag image_asset image_url tmp_dir archive
meta_file="$1"
tag="$2"
image_asset="${APP_IMAGE_ASSET_PREFIX}${tag}.tar.gz"
image_url="$(parse_asset_url "$meta_file" "$image_asset")"
if [ -z "$image_url" ]; then
log_message "ERROR: Release image asset not found: $image_asset"
return 1
fi
tmp_dir="$(mktemp -d)"
archive="$tmp_dir/$image_asset"
trap 'rm -rf "${tmp_dir:-}"' RETURN
log_message "Loading app image from release asset $image_asset"
curl -fL "$image_url" -o "$archive"
docker load -i "$archive" >> "$LOG_FILE" 2>&1
docker tag "$APP_IMAGE_REPO:$tag" "$APP_IMAGE_REPO:latest" >> "$LOG_FILE" 2>&1 || true
trap - RETURN
}
refresh_runtime_scripts_from_main() {
local start_url stop_url restart_url update_url
start_url="https://git.invario-software.eu/$REPO_SLUG/raw/branch/main/start.sh"
@@ -285,61 +219,13 @@ refresh_runtime_scripts_from_main() {
curl -fsSL "$restart_url" -o "$PROJECT_DIR/restart.sh" || log_message "WARNING: Could not refresh restart.sh from main"
curl -fsSL "$update_url" -o "$PROJECT_DIR/update.sh" || log_message "WARNING: Could not refresh update.sh from main"
chmod +x "$PROJECT_DIR/start.sh" "$PROJECT_DIR/stop.sh" "$PROJECT_DIR/restart.sh" "$PROJECT_DIR/update.sh"
}
find_local_dist_image_archive() {
local tag="$1"
local archive
if [ ! -d "$DIST_DIR" ]; then
return 1
fi
for archive in \
"$DIST_DIR/inventarsystem-image-$tag.tar.gz" \
"$DIST_DIR/inventarsystem-image-$tag.tar" \
"$DIST_DIR/inventarsystem-image.tar.gz" \
"$DIST_DIR/inventarsystem-image.tar"; do
if [ -f "$archive" ]; then
echo "$archive"
return 0
fi
done
archive="$(find "$DIST_DIR" -maxdepth 1 -type f \( -name 'inventarsystem-image-*.tar.gz' -o -name 'inventarsystem-image-*.tar' \) | sort | tail -n1)"
if [ -n "$archive" ]; then
echo "$archive"
return 0
fi
return 1
}
load_local_dist_image() {
local tag="$1"
local archive
archive="$(find_local_dist_image_archive "$tag" || true)"
if [ -z "$archive" ]; then
return 1
fi
log_message "Loading app image from local dist artifact: $archive"
if docker load -i "$archive" >> "$LOG_FILE" 2>&1; then
docker tag "$APP_IMAGE_REPO:$tag" "$APP_IMAGE_REPO:latest" >> "$LOG_FILE" 2>&1 || true
return 0
fi
log_message "WARNING: Failed to load local dist artifact: $archive"
return 1
chmod +x "$PROJECT_DIR/start.sh" "$PROJECT_DIR/stop.sh" "$PROJECT_DIR/restart.sh" "$PROJECT_DIR/update.sh" 2>/dev/null || true
}
download_and_extract_bundle() {
local url tmp_dir archive
url="$1"
tmp_dir="$2"
archive="$tmp_dir/$BUNDLE_ASSET"
local url="$1"
local tmp_dir="$2"
local archive="$tmp_dir/$BUNDLE_ASSET"
curl -fL "$url" -o "$archive"
tar -xzf "$archive" -C "$tmp_dir"
@@ -375,19 +261,15 @@ download_and_extract_bundle() {
# Ensure executable permissions on all copied scripts
chmod +x "$PROJECT_DIR/start.sh" "$PROJECT_DIR/stop.sh" "$PROJECT_DIR/restart.sh" "$PROJECT_DIR/update.sh" "$PROJECT_DIR/backup.sh" "$PROJECT_DIR/manage-tenant.sh" "$PROJECT_DIR/run-tenant-cmd.sh" 2>/dev/null || true
chmod +x "$PROJECT_DIR"/manage-tenant.sh "$PROJECT_DIR"/run-tenant-cmd.sh 2>/dev/null || true
if [ ! -f "$PROJECT_DIR/config.json" ] && [ -f "$tmp_dir/config.json" ]; then
cp -f "$tmp_dir/config.json" "$PROJECT_DIR/config.json"
log_message "Installed default config.json from release bundle"
fi
chmod +x "$PROJECT_DIR/start.sh" "$PROJECT_DIR/stop.sh" "$PROJECT_DIR/restart.sh" "$PROJECT_DIR/update.sh" "$PROJECT_DIR/backup.sh" "$PROJECT_DIR/manage-tenant.sh" "$PROJECT_DIR/run-tenant-cmd.sh" 2>/dev/null || true
}
deploy() {
local tag="$1"
local meta_file="$2"
local app_image="${APP_IMAGE_REPO}:${tag}"
local compose_path
@@ -410,17 +292,14 @@ EOF
printf '\nINVENTAR_APP_IMAGE=%s\n' "$app_image" >> "$ENV_FILE"
fi
if ! load_local_dist_image "$tag"; then
if ! load_release_image "$meta_file" "$tag"; then
log_message "Falling back to tagged Gitea Registry image $app_image"
if ! docker pull "$app_image" >> "$LOG_FILE" 2>&1; then
log_message "Falling back to local Docker build for $app_image"
docker build -t "$app_image" "$PROJECT_DIR" >> "$LOG_FILE" 2>&1
fi
fi
log_message "Pulling Gitea Registry image $app_image"
if ! docker pull "$app_image" >> "$LOG_FILE" 2>&1; then
log_message "Falling back to local Docker build for $app_image"
docker build -t "$app_image" "$PROJECT_DIR" >> "$LOG_FILE" 2>&1
fi
docker compose -f "$compose_path" --env-file "$ENV_FILE" pull app mongodb >> "$LOG_FILE" 2>&1
# Image wurde oben gepullt, Stack hochfahren
docker compose -f "$compose_path" --env-file "$ENV_FILE" pull mongodb redis >> "$LOG_FILE" 2>&1 || true
docker compose -f "$compose_path" --env-file "$ENV_FILE" up -d --remove-orphans >> "$LOG_FILE" 2>&1
docker tag "$app_image" "$APP_IMAGE_REPO:latest" >> "$LOG_FILE" 2>&1 || true
}
@@ -460,9 +339,12 @@ cleanup_server_space() {
else
log_message "WARNING: Docker system prune failed"
fi
# Clean up old dist artifacts
cleanup_old_dist_artifacts
# Clean up log files older than 7 days
# Delete legacy dist folder if it exists
if [ -d "$PROJECT_DIR/dist" ]; then
rm -rf "$PROJECT_DIR/dist" || true
log_message "Legacy dist folder removed"
fi
# Clean up old log files older than 7 days
if find "$LOG_DIR" -type f -name '*.log' -mtime +7 -exec rm -f {} +; then
log_message "Old log files (older than 7 days) cleaned up"
else
@@ -511,17 +393,14 @@ EOF
printf '\nINVENTAR_APP_IMAGE=%s\n' "$app_image" >> "$ENV_FILE"
fi
# Try local dist first, then pull from Gitea Registry
if ! load_local_dist_image "$tag"; then
log_message "Attempting to pull development image $app_image"
if ! docker pull "$app_image" >> "$LOG_FILE" 2>&1; then
log_message "ERROR: Could not obtain development image $app_image"
exit 1
fi
log_message "Attempting to pull development image $app_image"
if ! docker pull "$app_image" >> "$LOG_FILE" 2>&1; then
log_message "ERROR: Could not obtain development image $app_image"
exit 1
fi
# Bring up stack
docker compose -f "$compose_path" --env-file "$ENV_FILE" pull app mongodb >> "$LOG_FILE" 2>&1 || true
docker compose -f "$compose_path" --env-file "$ENV_FILE" pull mongodb redis >> "$LOG_FILE" 2>&1 || true
docker compose -f "$compose_path" --env-file "$ENV_FILE" up -d --remove-orphans >> "$LOG_FILE" 2>&1
if ! verify_stack_health; then
@@ -581,7 +460,7 @@ EOF
if [ "$current_tag" = "$latest_tag" ]; then
log_message "Already on latest release ($latest_tag). Refreshing containers from prebuilt image."
deploy "$latest_tag" "$meta_file"
deploy "$latest_tag"
if verify_stack_health; then
log_message "Container refresh completed"
else
@@ -611,18 +490,19 @@ EOF
log_message "Updating from release $latest_tag"
download_and_extract_bundle "$bundle_url" "$tmp_dir"
refresh_runtime_scripts_from_main
deploy "$latest_tag" "$meta_file"
deploy "$latest_tag"
if ! verify_stack_health; then
log_message "ERROR: Updated stack failed health check"
exit 1
fi
echo "$latest_tag" > "$STATE_FILE"
cleanup_old_dist_artifacts
cleanup_docker_dangling_images
log_message "Update completed successfully to release $latest_tag"
sudo ./opt/Inventarsystem/restart.sh
if [ -x "./opt/Inventarsystem/restart.sh" ]; then
sudo ./opt/Inventarsystem/restart.sh
fi
echo "Restart of the Server Completed"
}