mirror of
https://github.com/gtsteffaniak/filebrowser.git
synced 2026-11-26 16:39:41 -05:00
Compare commits
64
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c815a9f623 | ||
|
|
1d5026984b | ||
|
|
7e80179e74 | ||
|
|
4a7390b0dc | ||
|
|
50d3513880 | ||
|
|
9a0cd4552d | ||
|
|
b0aa189d34 | ||
|
|
fa0900d4f8 | ||
|
|
b57c3adaa1 | ||
|
|
282fd6f227 | ||
|
|
9f156fdefb | ||
|
|
cb7ad4af92 | ||
|
|
d896858bcd | ||
|
|
712ad91f20 | ||
|
|
cfa1537e2e | ||
|
|
d4e0c38f06 | ||
|
|
305a54ffb6 | ||
|
|
3acdde80ea | ||
|
|
a3d8833a2e | ||
|
|
421fd126c8 | ||
|
|
dfdc422ccf | ||
|
|
114d2136bb | ||
|
|
cfc4a1be78 | ||
|
|
d172c0fa4e | ||
|
|
fe1984f234 | ||
|
|
27bfee087c | ||
|
|
dc96f9d0ae | ||
|
|
24c83842a5 | ||
|
|
bd822497e1 | ||
|
|
ea9d2fe6df | ||
|
|
11e0681562 | ||
|
|
51d8df62b5 | ||
|
|
328872a620 | ||
|
|
093acb91b1 | ||
|
|
3de0848fef | ||
|
|
ff829772d5 | ||
|
|
8da3a8d14c | ||
|
|
49ad06fecd | ||
|
|
24ca0297ad | ||
|
|
36e826af7f | ||
|
|
53f2f3c87c | ||
|
|
02650e62c4 | ||
|
|
909987a2cf | ||
|
|
b1f97d3afa | ||
|
|
8faaeb39db | ||
|
|
91566b2721 | ||
|
|
04911ca7b0 | ||
|
|
19ae24637d | ||
|
|
d5354e556c | ||
|
|
ff77854ed6 | ||
|
|
d53b769e61 | ||
|
|
0a9af58b07 | ||
|
|
b111ec66ec | ||
|
|
9622f1226c | ||
|
|
9d1e9e0d72 | ||
|
|
90110ac999 | ||
|
|
81cbaf7766 | ||
|
|
40374752a3 | ||
|
|
c667218e30 | ||
|
|
183d2d89e2 | ||
|
|
9c1d1a58cd | ||
|
|
c4a5b0dcf9 | ||
|
|
7ae5a0fdcb | ||
|
|
f73ab72d46 |
No files matched your search
@@ -1,5 +1,6 @@
|
||||
backend/**.db
|
||||
backend/tmp
|
||||
backend/backend*
|
||||
backend/vendor/**
|
||||
frontend/dist/**
|
||||
frontend/node_modules/**
|
||||
@@ -81,7 +81,7 @@ jobs:
|
||||
file: ./_docker/Dockerfile.playwright-noauth
|
||||
push: false
|
||||
push_pr_to_registry:
|
||||
name: Push PR
|
||||
name: Build docker image
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -104,10 +104,10 @@ jobs:
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: ./_docker/Dockerfile
|
||||
file: ./_docker/Dockerfile.slim
|
||||
push: false # Do not push the image for now
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
build-args: |
|
||||
VERSION=${{ steps.meta.outputs.version }}
|
||||
REVISION=${{ steps.meta.outputs.revision }}
|
||||
REVISION=${{ steps.meta.outputs.revision }}
|
||||
@@ -15,17 +15,18 @@ jobs:
|
||||
go-version: 'stable'
|
||||
- working-directory: backend
|
||||
run: go test -race -v ./...
|
||||
lint-backend:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: 'stable'
|
||||
- uses: golangci/golangci-lint-action@v5
|
||||
with:
|
||||
version: 'v1.64'
|
||||
working-directory: backend
|
||||
# golanci-lint is currently disabled due to slowness
|
||||
# lint-backend:
|
||||
# runs-on: ubuntu-latest
|
||||
# steps:
|
||||
# - uses: actions/checkout@v4
|
||||
# - uses: actions/setup-go@v5
|
||||
# with:
|
||||
# go-version: 'stable'
|
||||
# - uses: golangci/golangci-lint-action@v5
|
||||
# with:
|
||||
# version: 'v1.64'
|
||||
# working-directory: backend
|
||||
format-backend:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
@@ -55,7 +55,7 @@ jobs:
|
||||
build-args: |
|
||||
VERSION=${{ fromJSON(steps.meta.outputs.json).labels['org.opencontainers.image.version'] }}
|
||||
REVISION=${{ fromJSON(steps.meta.outputs.json).labels['org.opencontainers.image.revision'] }}
|
||||
platforms: linux/amd64
|
||||
platforms: linux/amd64,linux/arm64
|
||||
file: ./_docker/Dockerfile
|
||||
push: true
|
||||
tags: ${{ steps.modify-json.outputs.cleaned_tag }}
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
name: Manual Docker Build
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
branch:
|
||||
description: "Tag or Branch (format: v0.0.0-beta)"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
push_release_to_registry:
|
||||
name: Push release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
token: ${{ secrets.PAT }} # Uses the Personal Access Token
|
||||
ref: "${{ github.event.inputs.branch }}"
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3.0.0
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3.0.0
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{github.actor}}
|
||||
password: ${{ secrets.PAT }}
|
||||
- name: Extract metadata (tags, labels) for Docker and GHCR
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: |
|
||||
gtstef/filebrowser
|
||||
ghcr.io/gtsteffaniak/filebrowser
|
||||
tags: |
|
||||
type=raw,value=${{ github.event.inputs.branch }}
|
||||
- name: Modify tags (strip 'v' and add 'beta'/'stable' if needed)
|
||||
id: modify-json
|
||||
run: |
|
||||
JSON='${{ steps.meta.outputs.json }}'
|
||||
MODIFIED_JSON=$(echo "$JSON" | jq '
|
||||
.tags |= map(sub(":v"; ":")) |
|
||||
if any(.tags[]; test("beta")) then
|
||||
.tags += [
|
||||
"gtstef/filebrowser:beta",
|
||||
"ghcr.io/gtsteffaniak/filebrowser:beta",
|
||||
"gtstef/filebrowser:latest",
|
||||
"ghcr.io/gtsteffaniak/filebrowser:latest"
|
||||
]
|
||||
else . end |
|
||||
if any(.tags[]; test("stable")) then
|
||||
.tags += [
|
||||
"gtstef/filebrowser:stable",
|
||||
"ghcr.io/gtsteffaniak/filebrowser:stable",
|
||||
"gtstef/filebrowser:latest",
|
||||
"ghcr.io/gtsteffaniak/filebrowser:latest"
|
||||
]
|
||||
else . end
|
||||
')
|
||||
TAGS_CSV=$(echo "$MODIFIED_JSON" | jq -r '.tags | join(",")')
|
||||
echo "$TAGS_CSV" > modified_tags.txt # Optional debug output
|
||||
echo "cleaned_tag=$TAGS_CSV" >> $GITHUB_OUTPUT
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
build-args: |
|
||||
VERSION=${{ fromJSON(steps.meta.outputs.json).labels['org.opencontainers.image.version'] }}
|
||||
REVISION=${{ fromJSON(steps.meta.outputs.json).labels['org.opencontainers.image.revision'] }}
|
||||
platforms: linux/amd64,linux/arm64,linux/arm/v7
|
||||
file: ./_docker/Dockerfile
|
||||
push: true
|
||||
tags: ${{ steps.modify-json.outputs.cleaned_tag }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
- name: Modify version names
|
||||
id: modify-json-media
|
||||
run: |
|
||||
JSON='${{ steps.meta.outputs.json }}'
|
||||
MODIFIED_JSON=$(echo "$JSON" | jq '
|
||||
.tags |= map(
|
||||
sub(":v"; ":") + "-media"
|
||||
) |
|
||||
if any(.tags[]; test("beta-media")) then
|
||||
.tags += [
|
||||
"gtstef/filebrowser:beta-media",
|
||||
"ghcr.io/gtsteffaniak/filebrowser:beta-media",
|
||||
"gtstef/filebrowser:media",
|
||||
"ghcr.io/gtsteffaniak/filebrowser:media"
|
||||
]
|
||||
else . end |
|
||||
if any(.tags[]; test("stable-media")) then
|
||||
.tags += [
|
||||
"gtstef/filebrowser:stable-media",
|
||||
"ghcr.io/gtsteffaniak/filebrowser:stable-media",
|
||||
"gtstef/filebrowser:media",
|
||||
"ghcr.io/gtsteffaniak/filebrowser:media"
|
||||
]
|
||||
else . end
|
||||
')
|
||||
TAGS_CSV=$(echo "$MODIFIED_JSON" | jq -r '.tags | join(",")')
|
||||
echo "$TAGS_CSV" > modified_tags.txt # Optional debug output
|
||||
echo "cleaned_tag=$TAGS_CSV" >> $GITHUB_OUTPUT
|
||||
- name: Build and push media image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
build-args: |
|
||||
VERSION=${{ fromJSON(steps.meta.outputs.json).labels['org.opencontainers.image.version'] }}
|
||||
REVISION=${{ fromJSON(steps.meta.outputs.json).labels['org.opencontainers.image.revision'] }}
|
||||
file: ./_docker/Dockerfile.media
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.modify-json-media.outputs.cleaned_tag }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
@@ -20,8 +20,9 @@ jobs:
|
||||
- name: Install dependencies and build frontend
|
||||
run: npm i && npm run build
|
||||
working-directory: frontend
|
||||
- name: Install UPX
|
||||
run: sudo apt-get install -y upx
|
||||
- name: Install OS Requirements
|
||||
run: sudo apt update && sudo apt install -y upx build-essential musl-tools
|
||||
- uses: goto-bus-stop/setup-zig@v2
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@v6
|
||||
with:
|
||||
@@ -63,7 +64,10 @@ jobs:
|
||||
run: |
|
||||
JSON='${{ steps.meta.outputs.json }}'
|
||||
MODIFIED_JSON=$(echo "$JSON" | jq '
|
||||
.tags |= map(sub(":v"; ":")) |
|
||||
.tags |= map(
|
||||
sub(":v"; ":") # Strip the 'v'
|
||||
| select(test(":latest") | not)
|
||||
) |
|
||||
if any(.tags[]; test("beta")) then
|
||||
.tags += [
|
||||
"gtstef/filebrowser:beta",
|
||||
@@ -91,8 +95,73 @@ jobs:
|
||||
build-args: |
|
||||
VERSION=${{ fromJSON(steps.meta.outputs.json).labels['org.opencontainers.image.version'] }}
|
||||
REVISION=${{ fromJSON(steps.meta.outputs.json).labels['org.opencontainers.image.revision'] }}
|
||||
platforms: linux/amd64,linux/arm64,linux/arm/v7
|
||||
platforms: linux/amd64,linux/arm64
|
||||
file: ./_docker/Dockerfile
|
||||
push: true
|
||||
tags: ${{ steps.modify-json.outputs.cleaned_tag }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
push_slim_release_to_registry:
|
||||
name: Push slim release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3.0.0
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3.0.0
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{github.actor}}
|
||||
password: ${{ secrets.PAT }}
|
||||
- name: Extract metadata (tags, labels) for Docker and GHCR
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: |
|
||||
gtstef/filebrowser
|
||||
ghcr.io/gtsteffaniak/filebrowser
|
||||
- name: Modify tags (strip 'v' and add 'slim' if needed)
|
||||
id: modify-json-slim
|
||||
run: |
|
||||
JSON='${{ steps.meta.outputs.json }}'
|
||||
MODIFIED_JSON=$(echo "$JSON" | jq '
|
||||
.tags |= map(
|
||||
sub(":v"; ":") # Strip the 'v'
|
||||
| select(test(":latest") | not) # Remove the "latest" tag
|
||||
| . + "-slim" # Append "-slim" to the versioned tag
|
||||
) |
|
||||
if any(.tags[]; test("beta")) then
|
||||
.tags += [
|
||||
"gtstef/filebrowser:beta-slim",
|
||||
"ghcr.io/gtsteffaniak/filebrowser:beta-slim"
|
||||
]
|
||||
else . end |
|
||||
if any(.tags[]; test("stable")) then
|
||||
.tags += [
|
||||
"gtstef/filebrowser:stable-slim",
|
||||
"ghcr.io/gtsteffaniak/filebrowser:stable-slim"
|
||||
]
|
||||
else . end
|
||||
')
|
||||
TAGS_CSV=$(echo "$MODIFIED_JSON" | jq -r '.tags | join(",")')
|
||||
echo "cleaned_tag=$TAGS_CSV" >> $GITHUB_OUTPUT
|
||||
- name: Build and push slim image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
build-args: |
|
||||
VERSION=${{ fromJSON(steps.meta.outputs.json).labels['org.opencontainers.image.version'] }}
|
||||
REVISION=${{ fromJSON(steps.meta.outputs.json).labels['org.opencontainers.image.revision'] }}
|
||||
platforms: linux/amd64,linux/arm64,linux/arm/v7
|
||||
file: ./_docker/Dockerfile.slim
|
||||
push: true
|
||||
tags: ${{ steps.modify-json-slim.outputs.cleaned_tag }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
@@ -10,6 +10,7 @@ rice-box.go
|
||||
/backend/filebrowser.exe
|
||||
/backend/backend.exe
|
||||
/backend/tmp
|
||||
/backend/dist
|
||||
/frontend/dist
|
||||
/frontend/pkg
|
||||
/frontend/test-results
|
||||
@@ -19,6 +20,7 @@ rice-box.go
|
||||
/backend/vendor
|
||||
/backend/*.cov
|
||||
/backend/test_config.yaml
|
||||
/backend/generated.yaml
|
||||
/backend/srv
|
||||
/backend/http/dist
|
||||
/backend/http/embed/*
|
||||
|
||||
+124
@@ -2,6 +2,130 @@
|
||||
|
||||
All notable changes to this project will be documented in this file. For commit guidelines, please refer to [Standard Version](https://github.com/conventional-changelog/standard-version).
|
||||
|
||||
## v0.7.7-beta
|
||||
|
||||
This release cleans up some of the native preview (image preview) feature logic. And adds simple docx and epub viewers as well. Going through all of this, I think I know how I can add full-fledge google doc and microsoft office viewer support (no edit). But, for now "onlyOffice" remains the most comprehensive solution with most compatibility and ability to fully edit. One day, I think I will be able to integrate a minimal license-free server into the docker image. But that's something for another time.
|
||||
|
||||
Native preview (image preview) support is also available for linux arm64 and amd64 binaries, and windows exe.
|
||||
|
||||
**New Features**:
|
||||
- since theres a wider kind of document preview types, a new disableOfficePreviewExt option has been added.
|
||||
- native (and simple) docx and epub viewers.
|
||||
- Other documents like xlsx get full size image preview when opened and no onlyoffice support.
|
||||
|
||||
**Notes**:
|
||||
- all text mimetype files have preview support.
|
||||
- high-quality preview image sizes bumped from 512x512 to 640x640 to help make text previews readable.
|
||||
- no config is allowed and defaults to on source at current directory.
|
||||
|
||||
**BugFixes**:
|
||||
- fix otp clearing on user save https://github.com/gtsteffaniak/filebrowser/issues/699
|
||||
- admin special characters and general login improvements https://github.com/gtsteffaniak/filebrowser/issues/594
|
||||
- updated editor caching behavior https://github.com/gtsteffaniak/filebrowser/issues/701
|
||||
- move/copy file path issue and overwrite https://github.com/gtsteffaniak/filebrowser/issues/687
|
||||
- fix popup preview loading on safari
|
||||
- `preview.highQuality` only affects gallery view mode. popop preview is always high quality, and icons are always low quality.
|
||||
|
||||
## v0.7.6-beta
|
||||
|
||||
**New Features**:
|
||||
- native document preview generation enabled for certain document types on the regular docker image (no office integration needed)
|
||||
- supported native document preview types:
|
||||
- ".pdf", // PDF
|
||||
- ".xps", // XPS
|
||||
- ".epub", // EPUB
|
||||
- ".mobi", // MOBI
|
||||
- ".fb2", // FB2
|
||||
- ".cbz", // CBZ
|
||||
- ".svg", // SVG
|
||||
- ".txt", // TXT
|
||||
- ".docx", // DOCX
|
||||
- ".ppt", // PPT
|
||||
- ".pptx", // PPTX
|
||||
- ".xlsx", // exel XLSX
|
||||
- ".hwp", // HWP
|
||||
- ".hwp", // HWPX
|
||||
- proxy logout redirectUrl support via `auth.methods.proxy.logoutRedirectUrl` https://github.com/gtsteffaniak/filebrowser/issues/684
|
||||
|
||||
**Notes**:
|
||||
- image loading placeholders added and remain if image can't be loaded.
|
||||
- no more arm32 support on main image -- use a `slim` tagged image.
|
||||
|
||||
**BugFixes**:
|
||||
- onlyoffice and other cache issues https://github.com/gtsteffaniak/filebrowser/issues/686
|
||||
- gallery size indicator centering https://github.com/gtsteffaniak/filebrowser/issues/652
|
||||
|
||||
## v0.7.5-beta
|
||||
|
||||
**New Features**
|
||||
- new `./filebrowser.exe setup` command for creating a config.yaml on first run. https://github.com/gtsteffaniak/filebrowser/issues/675
|
||||
- new 2FA/OTP support for password-based users.
|
||||
- `auth.password.enforcedOtp` option to enforce 2FA usage for password users.
|
||||
|
||||
**Notes**:
|
||||
- logging uses localtime, optional UTC config added https://github.com/gtsteffaniak/filebrowser/issues/665
|
||||
- generated config example now includes defaults https://github.com/gtsteffaniak/filebrowser/issues/590
|
||||
- `server.debugMedia` config option added to help debug ffmpeg issues in the future (don't enable unless debugging an issue)
|
||||
- more translations additions from english settings https://github.com/gtsteffaniak/filebrowser/issues/653
|
||||
- visual tweaks https://github.com/gtsteffaniak/filebrowser/issues/652
|
||||
- enhanced markdown viewer with code view spec
|
||||
|
||||
**BugFixes**:
|
||||
- long video names ffmpeg issue fixed https://github.com/gtsteffaniak/filebrowser/issues/669
|
||||
- certain files not passing content https://github.com/gtsteffaniak/filebrowser/issues/657
|
||||
- https://github.com/gtsteffaniak/filebrowser/issues/668
|
||||
- allow edit markdown files
|
||||
- rename button doesn't close prompt https://github.com/gtsteffaniak/filebrowser/issues/664
|
||||
- webm video preview issue https://github.com/gtsteffaniak/filebrowser/issues/673
|
||||
- fix signup issue https://github.com/gtsteffaniak/filebrowser/issues/648
|
||||
- fix default source bug
|
||||
- https://github.com/gtsteffaniak/filebrowser/issues/666
|
||||
- fix 500 error for subtitle videos https://github.com/gtsteffaniak/filebrowser/issues/678
|
||||
- spaces and special characters in source name issue https://github.com/gtsteffaniak/filebrowser/issues/679
|
||||
|
||||

|
||||
|
||||
## v0.7.4-beta
|
||||
|
||||
**Notes**:
|
||||
- Updated German translation. https://github.com/gtsteffaniak/filebrowser/pull/644
|
||||
|
||||
**BugFixes**:
|
||||
- windows control click https://github.com/gtsteffaniak/filebrowser/issues/642
|
||||
- create user issue https://github.com/gtsteffaniak/filebrowser/issues/647
|
||||
|
||||
## v0.7.3-beta
|
||||
|
||||
Note: OIDC changes require config update.
|
||||
|
||||
**New Features**
|
||||
- Added code highlights to text editor and enabled text editor for all asci files under 25MB
|
||||
- Motion previews for videos -- cycles screenshots of vidoes. https://github.com/gtsteffaniak/filebrowser/issues/588
|
||||
- Optionally reset default admin username/password on startup, to guarentee a username/password on startup if needed. Use by setting `auth.resetAdminOnStart` true https://github.com/gtsteffaniak/filebrowser/issues/625
|
||||
|
||||
**Notes**:
|
||||
- Updated translations everywhere. https://github.com/gtsteffaniak/filebrowser/issues/627
|
||||
- Office viewer is now full-screen with floating close button. https://github.com/gtsteffaniak/filebrowser/issues/542
|
||||
- OIDC config additions
|
||||
- `issuerUrl` required now to get relevant oidc configurations.
|
||||
- `disableVerifyTLS` optionally, disable verifying HTTPS provider endpoints.
|
||||
- `logoutRedirectUrl` optionally, redirect the user to this URL on logout.
|
||||
- other URL config parameters are no longer accepted -- replace with issuerUrl.
|
||||
- Aadmins allowed to change user login methods in user settings when creating or updating users.
|
||||
- https://github.com/gtsteffaniak/filebrowser/issues/618
|
||||
- https://github.com/gtsteffaniak/filebrowser/issues/617
|
||||
- Hide header when showing only office https://github.com/gtsteffaniak/filebrowser/issues/542
|
||||
|
||||
**BugFixes**:
|
||||
- Editor save shows notification
|
||||
- Preview settings resetting on startup
|
||||
- Not all languages show correctly https://github.com/gtsteffaniak/filebrowser/issues/623
|
||||
- scopes sometimes reset on startup https://github.com/gtsteffaniak/filebrowser/issues/636
|
||||
- Update save password option
|
||||
- https://github.com/gtsteffaniak/filebrowser/issues/587
|
||||
- https://github.com/gtsteffaniak/filebrowser/issues/619
|
||||
- https://github.com/gtsteffaniak/filebrowser/issues/615
|
||||
|
||||
## v0.7.2-beta
|
||||
|
||||
The `media` tags introduced in 0.7.0 have been removed -- all docker images have media enabled now.
|
||||
|
||||
@@ -16,12 +16,12 @@
|
||||
</div>
|
||||
|
||||
> [!WARNING]
|
||||
> There is no stable version -- planned for 2025.
|
||||
> There is no stable version -- planned for 2025. ([Read more](https://github.com/gtsteffaniak/filebrowser/discussions/628))
|
||||
|
||||
FileBrowser Quantum is a massive fork of the file browser open-source project with the following changes:
|
||||
|
||||
1. ✅ Multiple sources support
|
||||
2. ✅ Login support for OIDC, password, and proxy.
|
||||
2. ✅ Login support for OIDC, password + 2FA, and proxy.
|
||||
3. ✅ Revamped UI
|
||||
4. ✅ Simplified configuration via `config.yaml` config file.
|
||||
5. ✅ Ultra-efficient [indexing](https://github.com/gtsteffaniak/filebrowser/wiki/Indexing) and real-time updates
|
||||
@@ -55,7 +55,7 @@ This repo will always be free and open-source.
|
||||
|
||||
For more, see the [Q&A Wiki](https://github.com/gtsteffaniak/filebrowser/wiki/Q&A)
|
||||
|
||||
## Look
|
||||
## The UI
|
||||
|
||||
The UI has a simple three-component navigation system:
|
||||
|
||||
@@ -74,7 +74,9 @@ a pop-up menu.
|
||||
|
||||
## Install and Configuration
|
||||
|
||||
See the [Configuration Wiki](https://github.com/gtsteffaniak/filebrowser/wiki/Configuration)
|
||||
Check out the [Getting Started Wiki](https://github.com/gtsteffaniak/filebrowser/wiki/Getting-Started)
|
||||
|
||||
For help configuring your filebrowser see [Configuration Wiki](https://github.com/gtsteffaniak/filebrowser/wiki/Configuration-And-Examples)
|
||||
|
||||
## Command Line Usage
|
||||
|
||||
@@ -84,13 +86,9 @@ See the [CLI Wiki](https://github.com/gtsteffaniak/filebrowser/wiki/CLI)
|
||||
|
||||
See the [API Wiki](https://github.com/gtsteffaniak/filebrowser/wiki/API)
|
||||
|
||||
## Configuration
|
||||
|
||||
Configuration is done via the `config.yaml`, see the [Configuration Wiki](https://github.com/gtsteffaniak/filebrowser/wiki/Configuration) for available configuration options and other help.
|
||||
|
||||
## Office File Support
|
||||
|
||||
See [Office Support Wiki](https://github.com/gtsteffaniak/filebrowser/wiki/Office-Support#adding-open-office-integration-for-docker) on how to enable office file editing and office related features.
|
||||
See [Office Support Wiki](https://github.com/gtsteffaniak/filebrowser/wiki/Office-Support#adding-open-office-integration-for-docker) on how to enable office file editing and office-related features.
|
||||
|
||||
## Migration from the original filebrowser
|
||||
|
||||
@@ -100,19 +98,19 @@ See the [Migration Wiki](https://github.com/gtsteffaniak/filebrowser/wiki/Migrat
|
||||
|
||||
Application Name | <img width="48" src="https://github.com/user-attachments/assets/59986a2a-f960-4536-aa35-4a9a7c98ad48" > Quantum | <img width="48" src="https://github.com/filebrowser/filebrowser/blob/master/frontend/public/img/logo.svg" > Filebrowser | <img width="48" src="https://github.com/mickael-kerjean/filestash/blob/master/public/assets/logo/app_icon.png?raw=true" > Filestash | <img width="48" src="https://avatars.githubusercontent.com/u/19211038?s=200&v=4" > Nextcloud | <img width="48" src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/da/Google_Drive_logo.png/480px-Google_Drive_logo.png" > Google_Drive | <img width="48" src="https://avatars.githubusercontent.com/u/6422152?v=4" > FileRun
|
||||
--- | --- | --- | --- | --- | --- | --- |
|
||||
Filesystem support | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
Filesystem support | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ |
|
||||
Linux | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ |
|
||||
Windows | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
Mac | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
Windows | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ |
|
||||
Mac | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ |
|
||||
Self hostable | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ |
|
||||
Has Stable Release? | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
S3 support | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ |
|
||||
S3 support | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ |
|
||||
webdav support | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ |
|
||||
FTP support | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ |
|
||||
Dedicated docs site? | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ |
|
||||
Multiple sources at once | ✅ | ❌ | ✅ | ✅ | ❌ | ✅ |
|
||||
Docker image size | 200 MB (with ffmpeg) | 31 MB | 240 MB (main image) | 250 MB | ❌ | > 2 GB |
|
||||
Min. Memory Requirements | 256 MB | 128 MB | 128 MB (main image) | 128 MB | ❌ | 4 GB |
|
||||
Min. Memory Requirements | 256 MB | 128 MB | 128 MB (main image) | 512 MB | ❌ | 512 MB |
|
||||
has standalone binary | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
price | free | free | free | free tier | free tier | $99+ |
|
||||
rich media preview | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
@@ -127,7 +125,7 @@ LDAP sign-on support | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ |
|
||||
Long-live API key support | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ |
|
||||
API documentation page | ✅ | ❌ | ✅ | ✅ | ❌ | ✅ |
|
||||
Mobile App | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ |
|
||||
open source? | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ |
|
||||
open source? | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
tags support | ❌ | ❌ | ❌ | ✅ | ❌ | ✅ |
|
||||
shareable web links? | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
Event-based notifications | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ |
|
||||
@@ -148,4 +146,4 @@ Can archive selected files | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ |
|
||||
Can browse archive files | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ |
|
||||
Can convert documents | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ |
|
||||
Can convert videos | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
Can convert photos | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
Can convert photos | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
+10
-26
@@ -1,16 +1,18 @@
|
||||
FROM golang:1.24-alpine AS base
|
||||
FROM gtstef/ffmpeg:7.1.1-decode AS ffmpeg
|
||||
FROM golang:alpine AS base
|
||||
ARG VERSION
|
||||
ARG REVISION
|
||||
WORKDIR /app
|
||||
COPY ./backend ./
|
||||
#RUN swag init --output swagger/docs
|
||||
RUN ln -s swagger /usr/local/go/src/
|
||||
RUN go build -ldflags="-w -s \
|
||||
RUN apk update && apk add --no-cache gcc musl-dev upx
|
||||
ENV CGO_ENABLED=1
|
||||
RUN go build -tags mupdf,musl -ldflags="-w -s \
|
||||
-X 'github.com/gtsteffaniak/filebrowser/backend/common/version.Version=${VERSION}' \
|
||||
-X 'github.com/gtsteffaniak/filebrowser/backend/common/version.CommitSHA=${REVISION}'" \
|
||||
-o filebrowser .
|
||||
RUN upx filebrowser
|
||||
|
||||
FROM node:slim AS nbuild
|
||||
FROM node:lts-slim AS nbuild
|
||||
WORKDIR /app
|
||||
COPY ./frontend/package.json ./
|
||||
RUN npm i --maxsockets 1
|
||||
@@ -18,40 +20,22 @@ COPY ./frontend/ ./
|
||||
RUN npm run build-docker
|
||||
|
||||
FROM alpine:latest
|
||||
|
||||
RUN apk add --no-cache curl xz && \
|
||||
ARCH=$(uname -m) && \
|
||||
case "$ARCH" in \
|
||||
x86_64) URL="https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-amd64-static.tar.xz" ;; \
|
||||
aarch64) URL="https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-arm64-static.tar.xz" ;; \
|
||||
armv7l) URL="https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-armhf-static.tar.xz" ;; \
|
||||
*) echo "Unsupported architecture: $ARCH" && exit 1 ;; \
|
||||
esac && \
|
||||
mkdir -p /tmp/ffmpeg && \
|
||||
curl -L "$URL" | tar -xJ -C /tmp/ffmpeg && \
|
||||
mv /tmp/ffmpeg/ffmpeg-*/ffmpeg /usr/local/bin/ && \
|
||||
mv /tmp/ffmpeg/ffmpeg-*/ffprobe /usr/local/bin/ && \
|
||||
chmod +x /usr/local/bin/ffmpeg /usr/local/bin/ffprobe && \
|
||||
rm -rf /tmp/ffmpeg && \
|
||||
apk del curl xz && \
|
||||
rm -rf /var/cache/apk/*
|
||||
COPY --from=ffmpeg [ "/ffmpeg", "/ffprobe", "/usr/local/bin/" ]
|
||||
|
||||
ENV FILEBROWSER_FFMPEG_PATH="/usr/local/bin/"
|
||||
ENV FILEBROWSER_NO_EMBEDED="true"
|
||||
ENV PATH="$PATH:/home/filebrowser"
|
||||
RUN apk --no-cache add ca-certificates mailcap
|
||||
RUN apk --no-cache add ca-certificates mailcap tzdata
|
||||
RUN adduser -D -s /bin/true -u 1000 filebrowser
|
||||
USER filebrowser
|
||||
WORKDIR /home/filebrowser
|
||||
COPY --from=base --chown=filebrowser:1000 /app/filebrowser* ./
|
||||
COPY --from=base --chown=filebrowser:1000 /app/filebrowser ./
|
||||
COPY --from=base --chown=filebrowser:1000 /app/config.media.yaml ./config.yaml
|
||||
COPY --from=nbuild --chown=filebrowser:1000 /app/dist/ ./http/dist/
|
||||
|
||||
## sanity checks
|
||||
RUN [ "filebrowser", "version" ]
|
||||
RUN [ "ffmpeg", "-version" ]
|
||||
RUN [ "ffprobe", "-version" ]
|
||||
|
||||
USER root
|
||||
# exposing default port for auto discovery.
|
||||
EXPOSE 80
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
FROM golang:alpine AS base
|
||||
ARG VERSION
|
||||
ARG REVISION
|
||||
WORKDIR /app
|
||||
COPY ./backend ./
|
||||
RUN apk update && apk add upx
|
||||
RUN go build -ldflags="-w -s \
|
||||
-X 'github.com/gtsteffaniak/filebrowser/backend/common/version.Version=${VERSION}' \
|
||||
-X 'github.com/gtsteffaniak/filebrowser/backend/common/version.CommitSHA=${REVISION}'" \
|
||||
-o filebrowser .
|
||||
RUN upx filebrowser
|
||||
|
||||
FROM node:lts-slim AS nbuild
|
||||
WORKDIR /app
|
||||
COPY ./frontend/package.json ./
|
||||
RUN npm i --maxsockets 1
|
||||
COPY ./frontend/ ./
|
||||
RUN npm run build-docker
|
||||
|
||||
FROM alpine:latest
|
||||
ENV FILEBROWSER_NO_EMBEDED="true"
|
||||
ENV PATH="$PATH:/home/filebrowser"
|
||||
RUN apk --no-cache add ca-certificates mailcap tzdata
|
||||
RUN adduser -D -s /bin/true -u 1000 filebrowser
|
||||
USER filebrowser
|
||||
WORKDIR /home/filebrowser
|
||||
COPY --from=base --chown=filebrowser:1000 /app/filebrowser ./
|
||||
COPY --from=base --chown=filebrowser:1000 /app/config.yaml ./config.yaml
|
||||
COPY --from=nbuild --chown=filebrowser:1000 /app/dist/ ./http/dist/
|
||||
## sanity checks
|
||||
RUN [ "filebrowser", "version" ]
|
||||
USER root
|
||||
# exposing default port for auto discovery.
|
||||
EXPOSE 80
|
||||
ENTRYPOINT [ "./filebrowser" ]
|
||||
@@ -23,6 +23,7 @@ auth:
|
||||
enabled: true
|
||||
header: "X-Username"
|
||||
createUser: true
|
||||
logoutRedirectUrl: "https://localhost/api/auth/logout2"
|
||||
|
||||
userDefaults:
|
||||
darkMode: true
|
||||
|
||||
+52
-14
@@ -3,8 +3,12 @@ project_name: filebrowser
|
||||
version: 2
|
||||
|
||||
builds:
|
||||
# Build configuration for darwin and linux
|
||||
- id: default
|
||||
# Build configuration for linux amd64
|
||||
- id: linux-amd64
|
||||
env:
|
||||
- CGO_ENABLED=1
|
||||
tags:
|
||||
- mupdf
|
||||
ldflags: &ldflags
|
||||
- -s -w -X github.com/gtsteffaniak/filebrowser/backend/common/version.Version={{ .Version }} -X github.com/gtsteffaniak/filebrowser/backend/common/version.CommitSHA={{ .ShortCommit }}
|
||||
main: main.go
|
||||
@@ -13,8 +17,38 @@ builds:
|
||||
- linux
|
||||
goarch:
|
||||
- amd64
|
||||
- arm
|
||||
hooks:
|
||||
post:
|
||||
- upx {{ .Path }}
|
||||
|
||||
# Build configuration for linux arm64
|
||||
- id: linux-arm64
|
||||
ldflags: *ldflags
|
||||
main: main.go
|
||||
binary: filebrowser
|
||||
env:
|
||||
- CGO_ENABLED=1
|
||||
- CC=zig cc -target aarch64-linux-musl
|
||||
tags:
|
||||
- mupdf
|
||||
- musl
|
||||
goos:
|
||||
- linux
|
||||
goarch:
|
||||
- arm64
|
||||
hooks:
|
||||
post:
|
||||
- upx {{ .Path }}
|
||||
|
||||
# Build configuration for linux
|
||||
- id: linux-arm32
|
||||
ldflags: *ldflags
|
||||
main: main.go
|
||||
binary: filebrowser
|
||||
goos:
|
||||
- linux
|
||||
goarch:
|
||||
- arm
|
||||
goarm:
|
||||
- "6"
|
||||
- "7"
|
||||
@@ -24,6 +58,11 @@ builds:
|
||||
|
||||
# Build configuration for windows without arm
|
||||
- id: windows
|
||||
env:
|
||||
- CGO_ENABLED=1
|
||||
- CC=zig cc -target x86_64-windows
|
||||
tags:
|
||||
- mupdf
|
||||
ldflags: *ldflags
|
||||
main: main.go
|
||||
binary: filebrowser
|
||||
@@ -35,6 +74,16 @@ builds:
|
||||
post:
|
||||
- upx {{ .Path }} # Compress the binary with UPX
|
||||
|
||||
# Build configuration for freebsd without arm & upx
|
||||
- id: freeBSD and freebsd-arm
|
||||
ldflags: *ldflags
|
||||
main: main.go
|
||||
binary: filebrowser
|
||||
goos:
|
||||
- freebsd
|
||||
goarch:
|
||||
- amd64
|
||||
|
||||
# Build configuration for macos without upx
|
||||
- id: macos
|
||||
ldflags: *ldflags
|
||||
@@ -43,17 +92,7 @@ builds:
|
||||
goos:
|
||||
- darwin
|
||||
goarch:
|
||||
- amd64
|
||||
- arm64
|
||||
|
||||
# Build configuration for freebsd without arm & upx
|
||||
- id: freeBSD
|
||||
ldflags: *ldflags
|
||||
main: main.go
|
||||
binary: filebrowser
|
||||
goos:
|
||||
- freebsd
|
||||
goarch:
|
||||
- amd64
|
||||
|
||||
archives:
|
||||
@@ -67,4 +106,3 @@ archives:
|
||||
|
||||
checksum:
|
||||
disable: true
|
||||
|
||||
@@ -31,10 +31,6 @@ type FileCache struct {
|
||||
|
||||
// NewFileCache creates a new FileCache
|
||||
func NewFileCache(dir string) (*FileCache, error) {
|
||||
if err := os.MkdirAll(filepath.Join(dir, "thumbnails", "video"), 0700); err != nil {
|
||||
return nil, fmt.Errorf("can't make directory %s: %v", dir, err)
|
||||
}
|
||||
|
||||
return &FileCache{dir: dir}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -9,22 +9,22 @@ import (
|
||||
"fmt"
|
||||
"hash"
|
||||
"io"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/cache"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/errors"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
func FileInfoFaster(opts iteminfo.FileOptions) (iteminfo.ExtendedFileInfo, error) {
|
||||
@@ -68,16 +68,17 @@ func FileInfoFaster(opts iteminfo.FileOptions) (iteminfo.ExtendedFileInfo, error
|
||||
if !exists {
|
||||
return response, fmt.Errorf("could not get metadata for path: %v", opts.Path)
|
||||
}
|
||||
if opts.Content && strings.HasPrefix(info.Type, "text") {
|
||||
// Check file size
|
||||
if info.Size > 50*1024*1024 { // 50 megabytes in bytes
|
||||
logger.Debug(fmt.Sprintf("Reading large text file contents: "+info.Path, info.Name))
|
||||
if opts.Content {
|
||||
if info.Size < 20*1024*1024 { // 20 megabytes in bytes
|
||||
content, err := getContent(realPath)
|
||||
if err != nil {
|
||||
logger.Debugf("could not get content for file: "+info.Path, info.Name, err)
|
||||
return response, err
|
||||
}
|
||||
response.Content = content
|
||||
} else {
|
||||
logger.Debug("skipping large text file contents (20MB limit): "+info.Path, info.Name)
|
||||
}
|
||||
content, err := getContent(realPath)
|
||||
if err != nil {
|
||||
return response, err
|
||||
}
|
||||
response.Content = content
|
||||
}
|
||||
response.FileInfo = *info
|
||||
response.RealPath = realPath
|
||||
@@ -95,11 +96,11 @@ func FileInfoFaster(opts iteminfo.FileOptions) (iteminfo.ExtendedFileInfo, error
|
||||
}
|
||||
|
||||
func generateOfficeId(realPath string) string {
|
||||
key, ok := cache.OnlyOffice.Get(realPath).(string)
|
||||
key, ok := utils.OnlyOfficeCache.Get(realPath).(string)
|
||||
if !ok {
|
||||
timestamp := strconv.FormatInt(time.Now().UnixMilli(), 10)
|
||||
documentKey := utils.HashSHA256(realPath + timestamp)
|
||||
cache.OnlyOffice.Set(realPath, documentKey)
|
||||
utils.OnlyOfficeCache.Set(realPath, documentKey)
|
||||
return documentKey
|
||||
}
|
||||
return key
|
||||
@@ -268,19 +269,128 @@ func WriteFile(opts iteminfo.FileOptions, in io.Reader) error {
|
||||
return idx.RefreshFileInfo(opts)
|
||||
}
|
||||
|
||||
// addContent reads and sets content based on the file type.
|
||||
// getContent reads and returns the file content if it's considered an editable text file.
|
||||
func getContent(realPath string) (string, error) {
|
||||
const headerSize = 4096
|
||||
// Thresholds for detecting binary-like content (these can be tuned)
|
||||
const maxNullBytesInHeaderAbs = 10 // Max absolute null bytes in header
|
||||
const maxNullByteRatioInHeader = 0.1 // Max 10% null bytes in header
|
||||
const maxNullByteRatioInFile = 0.05 // Max 5% null bytes in the entire file
|
||||
const maxNonPrintableRuneRatio = 0.05 // Max 5% non-printable runes in the entire file
|
||||
|
||||
// Open file
|
||||
f, err := os.Open(realPath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// Read header
|
||||
headerBytes := make([]byte, headerSize)
|
||||
n, err := f.Read(headerBytes)
|
||||
if err != nil && err != io.EOF {
|
||||
return "", err
|
||||
}
|
||||
actualHeader := headerBytes[:n]
|
||||
|
||||
// --- Start of new heuristic checks ---
|
||||
|
||||
if n > 0 {
|
||||
// 1. Basic Check: Is the header valid UTF-8?
|
||||
// If not, it's unlikely an editable UTF-8 text file.
|
||||
if !utf8.Valid(actualHeader) {
|
||||
return "", nil // Not an error, just not the text file we want
|
||||
}
|
||||
|
||||
// 2. Check for excessive null bytes in the header
|
||||
nullCountInHeader := 0
|
||||
for _, b := range actualHeader {
|
||||
if b == 0x00 {
|
||||
nullCountInHeader++
|
||||
}
|
||||
}
|
||||
// Reject if too many nulls absolutely or relatively in the header
|
||||
if nullCountInHeader > 0 { // Only perform check if there are any nulls
|
||||
if nullCountInHeader > maxNullBytesInHeaderAbs ||
|
||||
(float64(nullCountInHeader)/float64(n) > maxNullByteRatioInHeader) {
|
||||
return "", nil // Too many nulls in header
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Check for other non-text ASCII control characters in the header
|
||||
// (C0 controls excluding \t, \n, \r)
|
||||
for _, b := range actualHeader {
|
||||
if b < 0x20 && b != '\t' && b != '\n' && b != '\r' {
|
||||
return "", nil // Found problematic control character
|
||||
}
|
||||
// C1 control characters (0x80-0x9F) would be caught by utf8.Valid if part of invalid sequences,
|
||||
// or by the non-printable rune check later if they form valid (but undesirable) codepoints.
|
||||
}
|
||||
|
||||
// Optional: Use http.DetectContentType for an additional check on the header
|
||||
// contentType := http.DetectContentType(actualHeader)
|
||||
// if !strings.HasPrefix(contentType, "text/") && contentType != "application/octet-stream" {
|
||||
// // If it's clearly a non-text MIME type (e.g., "image/jpeg"), reject it.
|
||||
// // "application/octet-stream" is ambiguous, so we rely on other heuristics.
|
||||
// return "", nil
|
||||
// }
|
||||
}
|
||||
// --- End of new heuristic checks for header ---
|
||||
|
||||
// Now read the full file (original logic)
|
||||
content, err := os.ReadFile(realPath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Handle empty file (original logic - returns specific string)
|
||||
if len(content) == 0 {
|
||||
return "empty-file-x6OlSil", nil
|
||||
}
|
||||
|
||||
stringContent := string(content)
|
||||
|
||||
// 4. Final UTF-8 validation for the entire file
|
||||
// (This is crucial as the header might be fine, but the rest of the file isn't)
|
||||
if !utf8.ValidString(stringContent) {
|
||||
return "", nil
|
||||
}
|
||||
if stringContent == "" {
|
||||
return "empty-file-x6OlSil", nil
|
||||
|
||||
// 5. Check for excessive null bytes in the entire file content
|
||||
if len(content) > 0 { // Check only for non-empty files
|
||||
totalNullCount := 0
|
||||
for _, b := range content {
|
||||
if b == 0x00 {
|
||||
totalNullCount++
|
||||
}
|
||||
}
|
||||
if float64(totalNullCount)/float64(len(content)) > maxNullByteRatioInFile {
|
||||
return "", nil // Too many nulls in the entire file
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Check for excessive non-printable runes in the entire file content
|
||||
// (Excluding tab, newline, carriage return, which are common in text files)
|
||||
if len(stringContent) > 0 { // Check only for non-empty strings
|
||||
nonPrintableRuneCount := 0
|
||||
totalRuneCount := 0
|
||||
for _, r := range stringContent {
|
||||
totalRuneCount++
|
||||
// unicode.IsPrint includes letters, numbers, punctuation, symbols, and spaces.
|
||||
// It excludes control characters. We explicitly allow \t, \n, \r.
|
||||
if !unicode.IsPrint(r) && r != '\t' && r != '\n' && r != '\r' {
|
||||
nonPrintableRuneCount++
|
||||
}
|
||||
}
|
||||
|
||||
if totalRuneCount > 0 { // Avoid division by zero
|
||||
if float64(nonPrintableRuneCount)/float64(totalRuneCount) > maxNonPrintableRuneRatio {
|
||||
return "", nil // Too many non-printable runes
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The file has passed all checks and is considered editable text.
|
||||
return stringContent, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
package fileutils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
// MoveFile moves a file from src to dst.
|
||||
@@ -23,14 +22,14 @@ func MoveFile(src, dst string) error {
|
||||
// fallback
|
||||
err = CopyFile(src, dst)
|
||||
if err != nil {
|
||||
logger.Error(fmt.Sprintf("CopyFile failed %v %v %v ", src, dst, err))
|
||||
logger.Errorf("CopyFile failed %v %v %v ", src, dst, err)
|
||||
return err
|
||||
}
|
||||
|
||||
go func() {
|
||||
err = os.RemoveAll(src)
|
||||
if err != nil {
|
||||
logger.Error(fmt.Sprintf("os.Remove failed %v %v ", src, err))
|
||||
logger.Errorf("os.Remove failed %v %v ", src, err)
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -181,14 +180,14 @@ func ClearCacheDir() {
|
||||
cacheDir := settings.Config.Server.CacheDir
|
||||
entries, err := os.ReadDir(cacheDir)
|
||||
if err != nil {
|
||||
logger.Error(fmt.Sprintf("failed clear cache dir: %v", err))
|
||||
logger.Errorf("failed clear cache dir: %v", err)
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
path := filepath.Join(cacheDir, entry.Name())
|
||||
err = os.RemoveAll(path)
|
||||
if err != nil {
|
||||
logger.Error(fmt.Sprintf("failed clear cache dir: %v", err))
|
||||
logger.Errorf("failed clear cache dir: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,9 +9,9 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/errors"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
type hookCred struct {
|
||||
@@ -32,7 +32,6 @@ type HookAuth struct {
|
||||
// Auth authenticates the user via a json in content body.
|
||||
func (a *HookAuth) Auth(r *http.Request, usr *users.Storage) (*users.User, error) {
|
||||
var cred hookCred
|
||||
|
||||
if r.Body == nil {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
@@ -52,6 +51,8 @@ func (a *HookAuth) Auth(r *http.Request, usr *users.Storage) (*users.User, error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
logger.Debugf("hook auth %v", action)
|
||||
|
||||
switch action {
|
||||
case "auth":
|
||||
u, err := a.SaveUser()
|
||||
@@ -167,7 +168,7 @@ func (a *HookAuth) SaveUser() (*users.User, error) {
|
||||
}
|
||||
u = a.GetUser(d)
|
||||
|
||||
err = a.Users.Save(u, false)
|
||||
err = a.Users.Save(u, false, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
+37
-24
@@ -8,38 +8,26 @@ import (
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/errors"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
type jsonCred struct {
|
||||
Password string `json:"password"`
|
||||
Username string `json:"username"`
|
||||
ReCaptcha string `json:"recaptcha"`
|
||||
}
|
||||
|
||||
// JSONAuth is a json implementation of an Auther.
|
||||
type JSONAuth struct {
|
||||
ReCaptcha *ReCaptcha `json:"recaptcha" yaml:"recaptcha"`
|
||||
}
|
||||
|
||||
// Auth authenticates the user via a json in content body.
|
||||
func (a JSONAuth) Auth(r *http.Request, userStore *users.Storage) (*users.User, error) {
|
||||
var cred jsonCred
|
||||
|
||||
if r.Body == nil {
|
||||
logger.Error("nil body error")
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
err := json.NewDecoder(r.Body).Decode(&cred)
|
||||
if err != nil {
|
||||
logger.Error("decode body error")
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
func (auther JSONAuth) Auth(r *http.Request, userStore *users.Storage) (*users.User, error) {
|
||||
username := r.URL.Query().Get("username")
|
||||
recaptcha := r.URL.Query().Get("recaptcha")
|
||||
password := r.Header.Get("X-Password")
|
||||
totpCode := r.Header.Get("X-Secret")
|
||||
|
||||
// If ReCaptcha is enabled, check the code.
|
||||
if a.ReCaptcha != nil && len(a.ReCaptcha.Secret) > 0 {
|
||||
ok, err := a.ReCaptcha.Ok(cred.ReCaptcha) //nolint:govet
|
||||
if auther.ReCaptcha != nil && len(auther.ReCaptcha.Secret) > 0 {
|
||||
ok, err := auther.ReCaptcha.Ok(recaptcha) //nolint:govet
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -49,16 +37,41 @@ func (a JSONAuth) Auth(r *http.Request, userStore *users.Storage) (*users.User,
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
}
|
||||
u, err := userStore.Get(cred.Username)
|
||||
|
||||
user, err := userStore.Get(username)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to get user from store: %v", err)
|
||||
}
|
||||
err = users.CheckPwd(cred.Password, u.Password)
|
||||
err = users.CheckPwd(password, user.Password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return u, nil
|
||||
// check for OTP for password
|
||||
if user.TOTPSecret != "" {
|
||||
if totpCode == "" {
|
||||
return nil, errors.ErrNoTotpProvided
|
||||
}
|
||||
err = VerifyTotpCode(user, totpCode, userStore)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if user.LoginMethod != users.LoginMethodPassword {
|
||||
logger.Warningf("user %s is not allowed to login with password authentication, bypassing and updating login method", user.Username)
|
||||
user.LoginMethod = users.LoginMethodPassword
|
||||
// Perform the user update
|
||||
err = userStore.Update(user, true, "LoginMethod")
|
||||
if err != nil {
|
||||
logger.Debug(err.Error())
|
||||
}
|
||||
//http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
|
||||
//return
|
||||
}
|
||||
|
||||
return user, nil
|
||||
|
||||
}
|
||||
|
||||
// LoginPage tells that json auth doesn't require a login page.
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
// StorageBackend is a storage backend for auth storage.
|
||||
@@ -35,6 +39,10 @@ func NewStorage(back StorageBackend, userStore *users.Storage) (*Storage, error)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
encryptionKey, err = base64.StdEncoding.DecodeString(settings.Config.Auth.TotpSecret)
|
||||
if err != nil {
|
||||
logger.Warning("failed to decode TOTP secret, using default key. This is insecure and should be fixed.")
|
||||
}
|
||||
return store, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
"github.com/gtsteffaniak/go-cache/cache"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
"github.com/pquerna/otp"
|
||||
"github.com/pquerna/otp/totp"
|
||||
)
|
||||
|
||||
// Constants for TOTP (Time-based One-Time Password) configuration.
|
||||
const (
|
||||
// IssuerName is the name of the application or service.
|
||||
IssuerName = "FileBrowser Quantum"
|
||||
|
||||
// TokenValidTime defines the total duration a token is considered valid.
|
||||
// Note: The actual validation window might be slightly longer depending on the period.
|
||||
TokenValidTime = time.Minute * 2
|
||||
|
||||
// TOTPPeriod is the standard duration in seconds that a TOTP code is valid.
|
||||
TOTPPeriod uint = 30
|
||||
|
||||
// TOTPSecretSize is the byte length of the shared secret.
|
||||
TOTPSecretSize uint = 20
|
||||
|
||||
// TOTPDigits specifies the number of digits in the OTP code.
|
||||
TOTPDigits = otp.DigitsSix
|
||||
|
||||
// TOTPAlgorithm is the hashing algorithm to use.
|
||||
TOTPAlgorithm = otp.AlgorithmSHA1
|
||||
)
|
||||
|
||||
var (
|
||||
// TOTPSkew allows for a certain number of periods of clock drift.
|
||||
// We calculate it to best match the TokenValidTime.
|
||||
// (2 * Skew + 1) * Period >= TokenValidTime
|
||||
// For a 2-minute (120s) window with a 30s period, we need a Skew of 2.
|
||||
// (2*2 + 1) * 30s = 150s (2.5 minutes). This is the closest we can get.
|
||||
TOTPSkew uint = uint(TokenValidTime.Seconds()) / (2 * uint(TOTPPeriod))
|
||||
encryptionKey []byte
|
||||
TotpCache = cache.NewCache(5 * time.Minute)
|
||||
)
|
||||
|
||||
func GenerateOtpForUser(user *users.User, userStore *users.Storage) (string, error) {
|
||||
// Generate a new TOTP key using the defined constants.
|
||||
key, err := totp.Generate(totp.GenerateOpts{
|
||||
Issuer: IssuerName,
|
||||
AccountName: user.Username,
|
||||
Period: TOTPPeriod,
|
||||
SecretSize: TOTPSecretSize,
|
||||
Digits: TOTPDigits,
|
||||
Algorithm: TOTPAlgorithm,
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error generating TOTP key: %w", err)
|
||||
}
|
||||
|
||||
secretText := key.Secret()
|
||||
nonce := ""
|
||||
if settings.Config.Auth.TotpSecret != "" {
|
||||
// If an encryption key is provided, encrypt the secret.
|
||||
secretText, nonce, err = encryptSecret(secretText, encryptionKey)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to encrypt TOTP secret: %w", err)
|
||||
}
|
||||
}
|
||||
// set cache so verify can attempt to use it but not require it for user yet.
|
||||
TotpCache.Set(user.Username, secretText+"||"+nonce)
|
||||
url := "otpauth://totp/FileBrowser%20Quantum?secret=" + secretText
|
||||
return url, nil
|
||||
}
|
||||
|
||||
// encryptSecret uses AES-GCM to encrypt a plaintext secret.
|
||||
// It returns the base64-encoded ciphertext and nonce, or an error.
|
||||
func encryptSecret(secret string, key []byte) (string, string, error) {
|
||||
if len(key) != 32 {
|
||||
return "", "", fmt.Errorf("invalid encryption key length: must be 32 bytes")
|
||||
}
|
||||
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
nonce := make([]byte, gcm.NonceSize())
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
ciphertext := gcm.Seal(nil, nonce, []byte(secret), nil)
|
||||
|
||||
return base64.StdEncoding.EncodeToString(ciphertext), base64.StdEncoding.EncodeToString(nonce), nil
|
||||
}
|
||||
|
||||
// decryptSecret uses AES-GCM to decrypt a ciphertext using its key and nonce.
|
||||
// It returns the plaintext secret or an error.
|
||||
func decryptSecret(b64Ciphertext, b64Nonce string) (string, error) {
|
||||
if len(encryptionKey) != 32 {
|
||||
return "", fmt.Errorf("invalid encryption key length: must be 32 bytes")
|
||||
}
|
||||
|
||||
ciphertext, err := base64.StdEncoding.DecodeString(b64Ciphertext)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to decode ciphertext: %w", err)
|
||||
}
|
||||
|
||||
nonce, err := base64.StdEncoding.DecodeString(b64Nonce)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to decode nonce: %w", err)
|
||||
}
|
||||
|
||||
block, err := aes.NewCipher(encryptionKey)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
|
||||
if err != nil {
|
||||
// This error often means the key is wrong or the data is corrupt
|
||||
return "", fmt.Errorf("failed to decrypt secret: %w", err)
|
||||
}
|
||||
|
||||
return string(plaintext), nil
|
||||
}
|
||||
|
||||
func VerifyTotpCode(user *users.User, code string, userStore *users.Storage) error {
|
||||
// get data from cache
|
||||
cachedSecret, found := TotpCache.Get(user.Username).(string)
|
||||
if !found && user.TOTPSecret == "" {
|
||||
return fmt.Errorf("OTP token not found in cache, please generate a new one")
|
||||
}
|
||||
totpSecret := user.TOTPSecret // The encrypted or plaintext secret
|
||||
totpNonce := user.TOTPNonce // The nonce if encrypted, or empty if plaintext
|
||||
if found {
|
||||
splitSecret := strings.Split(cachedSecret, "||")
|
||||
if len(splitSecret) < 2 {
|
||||
return fmt.Errorf("invalid cached OTP token format")
|
||||
}
|
||||
totpSecret = splitSecret[0]
|
||||
totpNonce = splitSecret[1]
|
||||
}
|
||||
secretToValidate := totpSecret
|
||||
if settings.Config.Auth.TotpSecret != "" {
|
||||
// If an encryption key is configured, we must decrypt the secret first.
|
||||
if totpNonce == "" {
|
||||
return fmt.Errorf("secret is encrypted but nonce is missing")
|
||||
}
|
||||
decryptedSecret, err := decryptSecret(totpSecret, totpNonce)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decrypt TOTP secret: %w", err)
|
||||
}
|
||||
secretToValidate = decryptedSecret
|
||||
}
|
||||
// --- END: ADD THIS DECRYPTION LOGIC ---
|
||||
|
||||
// Validate the token using the (now plaintext) secret.
|
||||
valid, err := totp.ValidateCustom(code, secretToValidate, time.Now().UTC(), totp.ValidateOpts{
|
||||
Period: TOTPPeriod,
|
||||
Skew: TOTPSkew,
|
||||
Digits: TOTPDigits,
|
||||
Algorithm: TOTPAlgorithm,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Errorf("error during TOTP validation: %v", err)
|
||||
}
|
||||
if !valid {
|
||||
return fmt.Errorf("invalid OTP token")
|
||||
}
|
||||
if totpSecret != "" {
|
||||
user.TOTPSecret = totpSecret // The encrypted or plaintext secret
|
||||
user.TOTPNonce = totpNonce // The nonce if encrypted, or empty if plaintext
|
||||
user.OtpEnabled = true // Enable OTP for the user
|
||||
// save user
|
||||
if err := userStore.Update(user, user.Permissions.Admin, "TOTPSecret", "TOTPNonce"); err != nil {
|
||||
logger.Error("error updating user with OTP token:", err)
|
||||
return fmt.Errorf("error updating user with OTP token: %w", err)
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("opt secret is empty, cannot enable TOTP")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -2,65 +2,82 @@
|
||||
== Running benchmark ==
|
||||
/usr/local/go/bin/go
|
||||
? github.com/gtsteffaniak/filebrowser/backend [no test files]
|
||||
PASS
|
||||
ok github.com/gtsteffaniak/filebrowser/backend/adapters/fs/diskcache 0.004s
|
||||
PASS
|
||||
ok github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files 0.006s
|
||||
PASS
|
||||
ok github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils 0.003s
|
||||
? github.com/gtsteffaniak/filebrowser/backend/auth [no test files]
|
||||
? github.com/gtsteffaniak/filebrowser/backend/cmd [no test files]
|
||||
PASS
|
||||
ok github.com/gtsteffaniak/filebrowser/backend/adapters/fs/diskcache 0.005s
|
||||
? github.com/gtsteffaniak/go-cache/cache [no test files]
|
||||
? github.com/gtsteffaniak/filebrowser/backend/common/errors [no test files]
|
||||
/home/graham/git/filebrowser /home/graham/git/filebrowser
|
||||
/home/graham/git/filebrowser/files/file.go /home/graham/git/filebrowser
|
||||
/home/graham/git/filebrowser/mnt/doesnt/exist /home/graham/git/filebrowser
|
||||
2025/01/04 14:04:55 Initializing index and assessing file system complexity
|
||||
2025/01/04 14:04:55 Starting full scan
|
||||
2025/01/04 14:04:55 Index assessment : complexity=simple directories=0 files=0
|
||||
2025/01/04 14:04:55 Time Spent Indexing : 0 seconds
|
||||
2025/01/04 14:04:55 Next scan in 1m0s
|
||||
2025/01/04 14:04:56 Initializing index and assessing file system complexity
|
||||
2025/01/04 14:04:56 Starting full scan
|
||||
2025/01/04 14:04:56 Index assessment : complexity=simple directories=0 files=0
|
||||
2025/01/04 14:04:56 Time Spent Indexing : 0 seconds
|
||||
2025/01/04 14:04:56 Next scan in 1m0s
|
||||
goos: linux
|
||||
goarch: amd64
|
||||
pkg: github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files
|
||||
cpu: 11th Gen Intel(R) Core(TM) i5-11320H @ 3.20GHz
|
||||
BenchmarkFillIndex-8 2025/01/04 14:04:57 Initializing index and assessing file system complexity
|
||||
2025/01/04 14:04:57 Starting full scan
|
||||
2025/01/04 14:04:57 Index assessment : complexity=simple directories=0 files=0
|
||||
2025/01/04 14:04:57 Time Spent Indexing : 0 seconds
|
||||
2025/01/04 14:04:57 Next scan in 1m0s
|
||||
10 3515090 ns/op 34273 B/op 451 allocs/op
|
||||
BenchmarkCheckIndexExclude-8 10 156.2 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkCheckIndexConditionsInclude-8 10 98.00 ns/op 0 B/op 0 allocs/op
|
||||
2025/01/04 14:04:58 Initializing index and assessing file system complexity
|
||||
2025/01/04 14:04:58 Starting full scan
|
||||
2025/01/04 14:04:58 Index assessment : complexity=simple directories=0 files=0
|
||||
2025/01/04 14:04:58 Time Spent Indexing : 0 seconds
|
||||
2025/01/04 14:04:58 Next scan in 1m0s
|
||||
BenchmarkSearchAllIndexes-8 2025/01/04 14:04:59 Initializing index and assessing file system complexity
|
||||
2025/01/04 14:04:59 Starting full scan
|
||||
2025/01/04 14:04:59 Index assessment : complexity=simple directories=0 files=0
|
||||
2025/01/04 14:04:59 Time Spent Indexing : 0 seconds
|
||||
2025/01/04 14:04:59 Next scan in 1m0s
|
||||
10 766822 ns/op 34230 B/op 900 allocs/op
|
||||
? github.com/gtsteffaniak/filebrowser/backend/common/logger [no test files]
|
||||
2025/05/11 20:42:56 Using OnlyOffice secret from FILEBROWSER_ONLYOFFICE_SECRET environment variable
|
||||
2025/05/11 20:42:56 Using OnlyOffice secret from FILEBROWSER_ONLYOFFICE_SECRET environment variable
|
||||
PASS
|
||||
ok github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files 5.094s
|
||||
ok github.com/gtsteffaniak/filebrowser/backend/common/settings 0.006s
|
||||
PASS
|
||||
ok github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils 0.002s
|
||||
PASS
|
||||
ok github.com/gtsteffaniak/filebrowser/backend/http 0.184s
|
||||
PASS
|
||||
ok github.com/gtsteffaniak/filebrowser/backend/preview/img 0.123s
|
||||
PASS
|
||||
ok github.com/gtsteffaniak/filebrowser/backend/runner 0.004s
|
||||
PASS
|
||||
ok github.com/gtsteffaniak/filebrowser/backend/common/settings 0.005s
|
||||
ok github.com/gtsteffaniak/filebrowser/backend/common/utils 0.003s
|
||||
? github.com/gtsteffaniak/filebrowser/backend/common/version [no test files]
|
||||
? github.com/gtsteffaniak/filebrowser/backend/database/share [no test files]
|
||||
? github.com/gtsteffaniak/filebrowser/backend/database/storage [no test files]
|
||||
? github.com/gtsteffaniak/filebrowser/backend/database/storage/bolt [no test files]
|
||||
PASS
|
||||
ok github.com/gtsteffaniak/filebrowser/backend/database/users 0.002s
|
||||
? github.com/gtsteffaniak/filebrowser/backend/events [no test files]
|
||||
2025/05/11 20:42:56 [DEBUG] Saving user [admin] changepass: true
|
||||
2025/05/11 20:42:56 [DEBUG] Saving user [non-admin] changepass: true
|
||||
PASS
|
||||
ok github.com/gtsteffaniak/filebrowser/backend/http 0.197s
|
||||
2025/05/11 20:42:57 initializing index: [test]
|
||||
2025/05/11 20:42:57 [DEBUG] Skipping source update event for mock index.
|
||||
2025/05/11 20:42:57 [DEBUG] Starting full scan for [test]
|
||||
2025/05/11 20:42:57 Index assessment : [test] complexity=simple directories=0 files=0
|
||||
2025/05/11 20:42:57 [DEBUG] Time spent indexing [test]: 0 seconds
|
||||
2025/05/11 20:42:57 [DEBUG] Skipping source update event for mock index.
|
||||
2025/05/11 20:42:57 [DEBUG] Next scan in 1m0s
|
||||
2025/05/11 20:42:58 initializing index: [test]
|
||||
2025/05/11 20:42:58 [DEBUG] Skipping source update event for mock index.
|
||||
2025/05/11 20:42:58 [DEBUG] Starting full scan for [test]
|
||||
2025/05/11 20:42:58 Index assessment : [test] complexity=simple directories=0 files=0
|
||||
2025/05/11 20:42:58 [DEBUG] Time spent indexing [test]: 0 seconds
|
||||
2025/05/11 20:42:58 [DEBUG] Skipping source update event for mock index.
|
||||
2025/05/11 20:42:58 [DEBUG] Next scan in 1m0s
|
||||
goos: linux
|
||||
goarch: amd64
|
||||
pkg: github.com/gtsteffaniak/filebrowser/backend/indexing
|
||||
cpu: 11th Gen Intel(R) Core(TM) i5-11320H @ 3.20GHz
|
||||
BenchmarkFillIndex-8 2025/05/11 20:42:59 initializing index: [test]
|
||||
2025/05/11 20:42:59 [DEBUG] Skipping source update event for mock index.
|
||||
2025/05/11 20:42:59 [DEBUG] Starting full scan for [test]
|
||||
2025/05/11 20:42:59 Index assessment : [test] complexity=simple directories=0 files=0
|
||||
2025/05/11 20:42:59 [DEBUG] Time spent indexing [test]: 0 seconds
|
||||
2025/05/11 20:42:59 [DEBUG] Skipping source update event for mock index.
|
||||
2025/05/11 20:42:59 [DEBUG] Next scan in 1m0s
|
||||
10 3548759 ns/op 38032 B/op 452 allocs/op
|
||||
BenchmarkCheckIndexExclude-8 10 172.6 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkCheckIndexConditionsInclude-8 10 118.2 ns/op 0 B/op 0 allocs/op
|
||||
2025/05/11 20:43:01 initializing index: [test]
|
||||
2025/05/11 20:43:01 [DEBUG] Skipping source update event for mock index.
|
||||
2025/05/11 20:43:01 [DEBUG] Starting full scan for [test]
|
||||
2025/05/11 20:43:01 Index assessment : [test] complexity=simple directories=0 files=0
|
||||
2025/05/11 20:43:01 [DEBUG] Time spent indexing [test]: 0 seconds
|
||||
2025/05/11 20:43:01 [DEBUG] Skipping source update event for mock index.
|
||||
2025/05/11 20:43:01 [DEBUG] Next scan in 1m0s
|
||||
BenchmarkSearchAllIndexes-8 2025/05/11 20:43:02 initializing index: [test]
|
||||
2025/05/11 20:43:02 [DEBUG] Skipping source update event for mock index.
|
||||
2025/05/11 20:43:02 [DEBUG] Starting full scan for [test]
|
||||
2025/05/11 20:43:02 Index assessment : [test] complexity=simple directories=0 files=0
|
||||
2025/05/11 20:43:02 [DEBUG] Time spent indexing [test]: 0 seconds
|
||||
2025/05/11 20:43:02 [DEBUG] Skipping source update event for mock index.
|
||||
2025/05/11 20:43:02 [DEBUG] Next scan in 1m0s
|
||||
10 781119 ns/op 38515 B/op 900 allocs/op
|
||||
PASS
|
||||
ok github.com/gtsteffaniak/filebrowser/backend/indexing 5.097s
|
||||
PASS
|
||||
ok github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo 0.005s
|
||||
PASS
|
||||
ok github.com/gtsteffaniak/filebrowser/backend/preview 0.128s
|
||||
? github.com/gtsteffaniak/filebrowser/backend/swagger/docs [no test files]
|
||||
PASS
|
||||
ok github.com/gtsteffaniak/filebrowser/backend/database/users 0.003s
|
||||
PASS
|
||||
ok github.com/gtsteffaniak/filebrowser/backend/common/utils 0.002s
|
||||
? github.com/gtsteffaniak/filebrowser/backend/common/version [no test files]
|
||||
? github.com/gtsteffaniak/filebrowser/backend/tools [no test files]
|
||||
+249
-10
@@ -1,16 +1,21 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/goccy/go-yaml"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/version"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/storage"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -19,6 +24,9 @@ var (
|
||||
|
||||
// return bool to indicate if the program should continue running
|
||||
func runCLI() bool {
|
||||
|
||||
generateYaml()
|
||||
|
||||
// Global flags
|
||||
var help bool
|
||||
// Override the default usage output to use generalUsage()
|
||||
@@ -56,6 +64,9 @@ func runCLI() bool {
|
||||
// Parse subcommand flags only if a subcommand is specified
|
||||
if len(os.Args) > 1 {
|
||||
switch os.Args[1] {
|
||||
case "setup":
|
||||
createConfig(configPath)
|
||||
return false
|
||||
case "set":
|
||||
err := setCmd.Parse(os.Args[2:])
|
||||
if err != nil {
|
||||
@@ -77,7 +88,8 @@ func runCLI() bool {
|
||||
user, err := store.Users.Get(username)
|
||||
if err != nil {
|
||||
newUser := users.User{
|
||||
Username: username,
|
||||
Username: username,
|
||||
LoginMethod: users.LoginMethodPassword,
|
||||
NonAdminEditable: users.NonAdminEditable{
|
||||
Password: password,
|
||||
},
|
||||
@@ -93,35 +105,262 @@ func runCLI() bool {
|
||||
|
||||
// Create the user logic
|
||||
if asAdmin {
|
||||
logger.Info(fmt.Sprintf("Creating user as admin: %s\n", username))
|
||||
logger.Infof("Creating user as admin: %s\n", username)
|
||||
} else {
|
||||
logger.Info(fmt.Sprintf("Creating non-admin user: %s\n", username))
|
||||
logger.Infof("Creating non-admin user: %s\n", username)
|
||||
}
|
||||
err = storage.CreateUser(newUser, asAdmin)
|
||||
if err != nil {
|
||||
logger.Error(fmt.Sprintf("could not create user: %v", err))
|
||||
logger.Errorf("could not create user: %v", err)
|
||||
}
|
||||
return false
|
||||
}
|
||||
if user.LoginMethod != users.LoginMethodPassword {
|
||||
logger.Warningf("user %s is not allowed to login with password authentication, bypassing and updating login method", user.Username)
|
||||
}
|
||||
user.Password = password
|
||||
user.TOTPSecret = "" // reset TOTP secret if it exists
|
||||
user.TOTPNonce = "" // reset TOTP nonce if it exists
|
||||
user.LoginMethod = users.LoginMethodPassword
|
||||
if asAdmin {
|
||||
user.Permissions.Admin = true
|
||||
}
|
||||
err = store.Users.Save(user, true)
|
||||
err = store.Users.Save(user, true, false)
|
||||
if err != nil {
|
||||
logger.Error(fmt.Sprintf("could not update user: %v", err))
|
||||
logger.Errorf("could not update user: %v", err)
|
||||
}
|
||||
fmt.Printf("successfully updated user: %s\n", username)
|
||||
return false
|
||||
|
||||
case "version":
|
||||
fmt.Printf(`FileBrowser Quantum - A modern web-based file manager
|
||||
Version : %v
|
||||
Commit : %v
|
||||
Release Info : https://github.com/gtsteffaniak/filebrowser/releases/tag/%v
|
||||
Version : %v
|
||||
Commit : %v
|
||||
Release Info : https://github.com/gtsteffaniak/filebrowser/releases/tag/%v
|
||||
`, version.Version, version.CommitSHA, version.Version)
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// UserDefaults defines default settings for new users.
|
||||
type UserDefaults struct {
|
||||
Permissions users.Permissions `yaml:"permissions"`
|
||||
}
|
||||
|
||||
// Frontend defines settings related to the web interface.
|
||||
type Frontend struct {
|
||||
Name string `yaml:"name,omitempty"`
|
||||
}
|
||||
|
||||
// Source defines a directory to be served.
|
||||
type Source struct {
|
||||
Name string `yaml:"name,omitempty"`
|
||||
Path string `yaml:"path"`
|
||||
}
|
||||
|
||||
// Server defines server-specific configurations.
|
||||
type Server struct {
|
||||
Port int `yaml:"port"`
|
||||
Database string `yaml:"database"`
|
||||
Sources []Source `yaml:"sources"`
|
||||
Logging []LogConfig `json:"logging"`
|
||||
}
|
||||
|
||||
type LogConfig struct {
|
||||
Levels string `json:"levels"` // separated list of log levels to enable. (eg. "info|warning|error|debug")
|
||||
ApiLevels string `json:"apiLevels"` // separated list of log levels to enable for the API. (eg. "info|warning|error")
|
||||
Output string `json:"output"` // output location. (eg. "stdout" or "path/to/file.log")
|
||||
NoColors bool `json:"noColors"` // disable colors in the output
|
||||
Utc bool `json:"utc"` // use UTC time in the output instead of local time
|
||||
}
|
||||
|
||||
type Auth struct {
|
||||
AdminUsername string `yaml:"adminUsername"`
|
||||
AdminPassword string `yaml:"adminPassword"`
|
||||
}
|
||||
|
||||
// Settings is the top-level configuration structure.
|
||||
type Settings struct {
|
||||
Server Server `yaml:"server"`
|
||||
Frontend Frontend `yaml:"frontend,omitempty"`
|
||||
Auth Auth `yaml:"auth"`
|
||||
UserDefaults UserDefaults `yaml:"userDefaults"`
|
||||
}
|
||||
|
||||
// askQuestion displays a prompt and reads a line of input from the user.
|
||||
// It returns the defaultValue if the user's input is empty.
|
||||
func askQuestion(reader *bufio.Reader, prompt string, defaultValue string) string {
|
||||
fmt.Printf("%s (default: %s): ", prompt, defaultValue)
|
||||
input, _ := reader.ReadString('\n')
|
||||
input = strings.TrimSpace(input)
|
||||
if input == "" {
|
||||
return defaultValue
|
||||
}
|
||||
return input
|
||||
}
|
||||
|
||||
// askYesNoQuestion prompts the user with a yes/no question and returns a boolean.
|
||||
// It retries until valid input ("yes", "y", "no", "n") is received.
|
||||
// The defaultValue must be "yes" or "no".
|
||||
func askYesNoQuestion(reader *bufio.Reader, prompt string, defaultValue string) bool {
|
||||
for {
|
||||
answer := askQuestion(reader, prompt, defaultValue)
|
||||
answer = strings.ToLower(answer)
|
||||
if answer == "yes" || answer == "y" {
|
||||
return true
|
||||
}
|
||||
if answer == "no" || answer == "n" {
|
||||
return false
|
||||
}
|
||||
fmt.Println("Error: Invalid input. Please enter 'yes' or 'no'.")
|
||||
}
|
||||
}
|
||||
|
||||
// createConfig orchestrates the configuration process by asking the user a series of questions.
|
||||
func createConfig(configpath string) {
|
||||
// check if config file exists
|
||||
if _, err := os.Stat("config.yaml"); err == nil {
|
||||
fmt.Println("Config file 'config.yaml' already exists, skipping setup.")
|
||||
return
|
||||
}
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
config := Settings{
|
||||
Server: Server{
|
||||
Logging: []LogConfig{
|
||||
{
|
||||
Levels: "info|warning|error",
|
||||
ApiLevels: "info|warning|error",
|
||||
Output: "stdout",
|
||||
NoColors: false,
|
||||
Utc: false,
|
||||
},
|
||||
},
|
||||
Sources: []Source{
|
||||
{
|
||||
Path: "",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Println("--- Starting Configuration Setup ---")
|
||||
realPath := ""
|
||||
// 1. Ask for the source filesystem path (with validation)
|
||||
for {
|
||||
config.Server.Sources[0].Path = askQuestion(reader, "What is the source filesystem path?", "./")
|
||||
// Convert relative path to absolute path
|
||||
absolutePath, err := filepath.Abs(config.Server.Sources[0].Path)
|
||||
if err == nil {
|
||||
var isDir bool
|
||||
// Resolve symlinks and get the real path
|
||||
realPath, isDir, _ = utils.ResolveSymlinks(absolutePath)
|
||||
if realPath != "" && isDir {
|
||||
break // Valid path found, exit loop
|
||||
}
|
||||
}
|
||||
fmt.Printf("Error: The path '%s' does not exist or isn't valid. Please try again.\n", config.Server.Sources[0].Path)
|
||||
}
|
||||
// 2. Ask for the source name
|
||||
defaultSourceName := filepath.Base(realPath)
|
||||
sourceName := askQuestion(reader, "What should the first source name be?", defaultSourceName)
|
||||
if sourceName != defaultSourceName {
|
||||
config.Server.Sources[0].Name = sourceName
|
||||
}
|
||||
|
||||
// 3. Ask for server port (with validation)
|
||||
for {
|
||||
portStr := askQuestion(reader, "What port should the server listen on?", "80")
|
||||
port, err := strconv.Atoi(portStr)
|
||||
if err == nil && (port >= 1 && port <= 65535) {
|
||||
config.Server.Port = port
|
||||
break // Port is valid, exit loop
|
||||
}
|
||||
fmt.Printf("Error: '%s' is not a valid port. Please enter a number between 1 and 65535.\n", portStr)
|
||||
}
|
||||
|
||||
for {
|
||||
levels := askQuestion(reader, "What should the log levels be?", "info|warning|error")
|
||||
checkLevels := SplitByMultiple(levels)
|
||||
invalidOptions := []string{}
|
||||
for _, level := range checkLevels {
|
||||
if !(level == "info" || level == "warning" || level == "error" || level == "debug") {
|
||||
invalidOptions = append(invalidOptions, level)
|
||||
}
|
||||
}
|
||||
if len(invalidOptions) == 0 {
|
||||
break
|
||||
}
|
||||
fmt.Printf("Error: invalid options given '%s'. valid options: 'info|warning|error|debug'.\n", invalidOptions)
|
||||
}
|
||||
|
||||
for {
|
||||
config.Server.Database = askQuestion(reader, "What should the file name and path be for the database?", "./database.db")
|
||||
if strings.HasSuffix(config.Server.Database, ".db") {
|
||||
break // Valid path found, exit loop
|
||||
}
|
||||
fmt.Printf("Error: '%s' is not a valid path. Please enter a path to a file ending in .db", config.Server.Database)
|
||||
}
|
||||
// 4. Ask for the application brand name
|
||||
config.Frontend.Name = askQuestion(reader, "What should the application brand name be?", "FileBrowser Quantum")
|
||||
|
||||
// 5. Ask for admin username and password
|
||||
config.Auth.AdminUsername = askQuestion(reader, "What should the default admin username be?", "admin")
|
||||
config.Auth.AdminPassword = askQuestion(reader, "What should the default admin password be?", "admin")
|
||||
|
||||
// 6. Ask boolean (Yes/No) questions using the helper
|
||||
config.UserDefaults.Permissions.Modify = askYesNoQuestion(reader, "Should a new user be able to modify content by default?", "no")
|
||||
config.UserDefaults.Permissions.Share = askYesNoQuestion(reader, "Should a new user be able to create shares by default?", "no")
|
||||
|
||||
fmt.Println("--- Configuration Complete ---")
|
||||
|
||||
// marshall yaml and write to file
|
||||
// Marshal the struct to YAML bytes
|
||||
yamlData, err := yaml.Marshal(&config)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Write the YAML data to the file
|
||||
err = os.WriteFile("config.yaml", yamlData, 0644) // 0644 provides read/write for owner, read for others
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// cleanup database if it exists
|
||||
if _, err := os.Stat(config.Server.Database); err == nil {
|
||||
response := askYesNoQuestion(reader, "Database specified already exists. Move databse file to backup to start fresh?", "no")
|
||||
if !response {
|
||||
return
|
||||
}
|
||||
// move database file to backup
|
||||
backupPath := config.Server.Database + ".bak"
|
||||
err = os.Rename(config.Server.Database, backupPath)
|
||||
if err != nil {
|
||||
fmt.Printf("Error moving database file to backup: %v\n", err)
|
||||
} else {
|
||||
fmt.Printf("Database file moved to backup: %s\n", backupPath)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func generateYaml() {
|
||||
if os.Getenv("FILEBROWSER_GENERATE_CONFIG") != "" {
|
||||
logger.Info("Generating config.yaml")
|
||||
settings.GenerateYaml()
|
||||
os.Exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
func SplitByMultiple(str string) []string {
|
||||
delimiters := []rune{'|', ',', ' '}
|
||||
return strings.FieldsFunc(str, func(r rune) bool {
|
||||
for _, d := range delimiters {
|
||||
if r == d {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
@@ -3,8 +3,8 @@ package cmd
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
// healthcheck attempt to save test file against configured url
|
||||
|
||||
+10
-9
@@ -8,13 +8,13 @@ import (
|
||||
"syscall"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/storage"
|
||||
fbhttp "github.com/gtsteffaniak/filebrowser/backend/http"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/preview"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/swagger/docs"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
"github.com/swaggo/swag"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/version"
|
||||
@@ -27,7 +27,7 @@ func getStore(configFile string) bool {
|
||||
settings.Initialize(configFile)
|
||||
s, hasDB, err := storage.InitializeDb(settings.Config.Server.Database)
|
||||
if err != nil {
|
||||
logger.Fatal(fmt.Sprintf("could not load db info: %v", err))
|
||||
logger.Fatalf("could not load db info: %v", err)
|
||||
}
|
||||
store = s
|
||||
return hasDB
|
||||
@@ -69,11 +69,12 @@ func StartFilebrowser() {
|
||||
for path, source := range settings.Config.Server.SourceMap {
|
||||
sourceList = append(sourceList, fmt.Sprintf("%v: %v", source.Name, path))
|
||||
}
|
||||
logger.Info(fmt.Sprintf("Initializing FileBrowser Quantum (%v)", version.Version))
|
||||
logger.Info(fmt.Sprintf("Using Config file : %v", configPath))
|
||||
logger.Info(fmt.Sprintf("Auth Methods : %v", settings.Config.Auth.AuthMethods))
|
||||
logger.Infof("Initializing FileBrowser Quantum (%v)", version.Version)
|
||||
logger.Infof("Using Config file : %v", configPath)
|
||||
logger.Infof("Auth Methods : %v", settings.Config.Auth.AuthMethods)
|
||||
logger.Info(database)
|
||||
logger.Info(fmt.Sprintf("Sources : %v", sourceList))
|
||||
logger.Infof("Sources : %v", sourceList)
|
||||
|
||||
serverConfig := settings.Config.Server
|
||||
swagInfo := docs.SwaggerInfo
|
||||
swagInfo.BasePath = serverConfig.BaseURL
|
||||
@@ -90,7 +91,7 @@ func StartFilebrowser() {
|
||||
// Start the rootCMD in a goroutine
|
||||
go func() {
|
||||
if err := rootCMD(ctx, store, &serverConfig, shutdownComplete); err != nil {
|
||||
logger.Fatal(fmt.Sprintf("Error starting filebrowser: %v", err))
|
||||
logger.Fatalf("Error starting filebrowser: %v", err)
|
||||
}
|
||||
close(done) // Signal that the server has stopped
|
||||
}()
|
||||
@@ -117,9 +118,9 @@ func rootCMD(ctx context.Context, store *storage.Storage, serverConfig *settings
|
||||
numWorkers := settings.Config.Server.NumImageProcessors
|
||||
ffpmpegPath := settings.Config.Integrations.Media.FfmpegPath
|
||||
// setup disk cache
|
||||
err := preview.Start(numWorkers, ffpmpegPath, cacheDir)
|
||||
err := preview.StartPreviewGenerator(numWorkers, ffpmpegPath, cacheDir)
|
||||
if err != nil {
|
||||
logger.Fatal(fmt.Sprintf("Error starting preview service: %v", err))
|
||||
logger.Fatalf("Error starting preview service: %v", err)
|
||||
}
|
||||
fbhttp.StartHttp(ctx, store, shutdownComplete)
|
||||
return nil
|
||||
|
||||
+50
-76
@@ -2,12 +2,12 @@ package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"reflect"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
var createBackup = []bool{}
|
||||
@@ -16,7 +16,7 @@ func validateUserInfo() {
|
||||
// update source info for users if names/sources/paths might have changed
|
||||
usersList, err := store.Users.Gets()
|
||||
if err != nil {
|
||||
logger.Fatal(fmt.Sprintf("could not load users: %v", err))
|
||||
logger.Fatalf("could not load users: %v", err)
|
||||
}
|
||||
for _, user := range usersList {
|
||||
updateUser := false
|
||||
@@ -41,101 +41,75 @@ func validateUserInfo() {
|
||||
logger.Warning("Incompatible user settings detected, creating backup of database before converting.")
|
||||
err = fileutils.CopyFile(settings.Config.Server.Database, fmt.Sprintf("%s.bak", settings.Config.Server.Database))
|
||||
if err != nil {
|
||||
logger.Fatal(fmt.Sprintf("Unable to create automatic backup of database due to error: %v", err))
|
||||
logger.Fatalf("Unable to create automatic backup of database due to error: %v", err)
|
||||
}
|
||||
}
|
||||
err := store.Users.Save(user, false)
|
||||
err := store.Users.Save(user, false, true)
|
||||
if err != nil {
|
||||
logger.Error(fmt.Sprintf("could not update user: %v", err))
|
||||
logger.Errorf("could not update user: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if settings.Config.Auth.ResetAdminOnStart {
|
||||
logger.Info("Resetting admin user to default username and password.")
|
||||
adminUser, err := store.Users.Get(1)
|
||||
if err != nil {
|
||||
logger.Fatalf("could not load admin user: %v", err)
|
||||
}
|
||||
adminUser.Username = settings.Config.Auth.AdminUsername
|
||||
adminUser.Password = settings.Config.Auth.AdminPassword
|
||||
adminUser.Permissions.Admin = true
|
||||
err = store.Users.Save(adminUser, true, true)
|
||||
if err != nil {
|
||||
logger.Errorf("could not Save admin user: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func updateUserScopes(user *users.User) bool {
|
||||
updateUser := false
|
||||
finalScopes := []users.SourceScope{}
|
||||
seenNames := make(map[string]bool)
|
||||
newScopes := []users.SourceScope{}
|
||||
seen := make(map[string]bool)
|
||||
|
||||
// Step 1: Start by including all existing scopes, updating Name if source.Path matches
|
||||
for _, existingScope := range user.Scopes {
|
||||
if existingScope.Scope != "/" {
|
||||
existingScope.Scope = strings.TrimSuffix(existingScope.Scope, "/")
|
||||
}
|
||||
if existingScope.Scope == "" {
|
||||
updateUser = true
|
||||
continue
|
||||
}
|
||||
if !seenNames[existingScope.Name] {
|
||||
finalScopes = append(finalScopes, existingScope)
|
||||
seenNames[existingScope.Name] = true
|
||||
}
|
||||
// Build map for existing scopes by Name
|
||||
existing := make(map[string]users.SourceScope)
|
||||
for _, s := range user.Scopes {
|
||||
existing[s.Name] = s
|
||||
}
|
||||
|
||||
// Step 2: Add missing scopes from SourceMap if admin or DefaultEnabled
|
||||
for _, source := range settings.Config.Server.SourceMap {
|
||||
if seenNames[source.Path] {
|
||||
// Preserve order by using Config.Server.Sources
|
||||
for _, src := range settings.Config.Server.Sources {
|
||||
realsource, ok := settings.Config.Server.NameToSource[src.Name]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// Check if scope exists already via path
|
||||
scopePath, _ := settings.GetScopeFromSourcePath(user.Scopes, source.Path)
|
||||
if scopePath == "" {
|
||||
// must be new scope for user
|
||||
// If user has no access, skip unless default-enabled
|
||||
if !source.Config.DefaultEnabled {
|
||||
continue
|
||||
}
|
||||
// Determine scope path
|
||||
if scopePath == "" {
|
||||
scopePath = source.Config.DefaultUserScope
|
||||
}
|
||||
if scopePath == "" {
|
||||
scopePath = "/"
|
||||
}
|
||||
if scopePath != "/" {
|
||||
scopePath = strings.TrimSuffix(scopePath, "/")
|
||||
existingScope, ok := existing[realsource.Path]
|
||||
if ok {
|
||||
// If scope is empty and there's a default, apply default
|
||||
if existingScope.Scope == "" {
|
||||
existingScope.Scope = src.Config.DefaultUserScope
|
||||
}
|
||||
} else if realsource.Config.DefaultEnabled {
|
||||
existingScope.Scope = realsource.Config.DefaultUserScope
|
||||
} else {
|
||||
continue
|
||||
}
|
||||
|
||||
// Add new scope
|
||||
finalScopes = append(finalScopes, users.SourceScope{
|
||||
Scope: scopePath,
|
||||
Name: source.Path,
|
||||
newScopes = append(newScopes, users.SourceScope{
|
||||
Name: realsource.Path,
|
||||
Scope: existingScope.Scope,
|
||||
})
|
||||
seenNames[source.Path] = true
|
||||
updateUser = true
|
||||
seen[realsource.Path] = true
|
||||
}
|
||||
|
||||
// Step 3: If no scopes, apply default
|
||||
if len(finalScopes) == 0 {
|
||||
defaultScope := users.SourceScope{
|
||||
Scope: settings.Config.Server.DefaultSource.Config.DefaultUserScope,
|
||||
Name: settings.Config.Server.DefaultSource.Path,
|
||||
}
|
||||
finalScopes = append(finalScopes, defaultScope)
|
||||
updateUser = true
|
||||
}
|
||||
|
||||
// Step 4: Assign only if different
|
||||
if !scopesEqual(user.Scopes, finalScopes) {
|
||||
user.Scopes = finalScopes
|
||||
updateUser = true
|
||||
}
|
||||
|
||||
return updateUser
|
||||
}
|
||||
|
||||
// scopesEqual does a deep comparison to avoid unnecessary writes
|
||||
func scopesEqual(a, b []users.SourceScope) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i := range a {
|
||||
if a[i].Scope != b[i].Scope || a[i].Name != b[i].Name {
|
||||
return false
|
||||
// Preserve user-defined scopes not matching current sources, append to end
|
||||
for _, s := range user.Scopes {
|
||||
if !seen[s.Name] {
|
||||
newScopes = append(newScopes, s)
|
||||
}
|
||||
}
|
||||
return true
|
||||
changed := !reflect.DeepEqual(user.Scopes, newScopes)
|
||||
user.Scopes = newScopes
|
||||
return changed
|
||||
}
|
||||
|
||||
// func to convert legacy user with perm key to permissions
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestUpdateUserScopes_Phases(t *testing.T) {
|
||||
|
||||
sourceA := settings.Source{Path: "/pathA", Name: "sourceA", Config: settings.SourceConfig{
|
||||
DefaultEnabled: false,
|
||||
DefaultUserScope: "/defaultA",
|
||||
}}
|
||||
sourceB := settings.Source{Path: "/pathB", Name: "sourceB", Config: settings.SourceConfig{DefaultEnabled: true, DefaultUserScope: "/defaultB"}}
|
||||
settings.Config.Server.Sources = []settings.Source{sourceA, sourceB}
|
||||
settings.Config.Server.DefaultSource = sourceB
|
||||
settings.Config.Server.SourceMap = map[string]settings.Source{
|
||||
"/pathA": sourceA,
|
||||
"/pathB": sourceB,
|
||||
}
|
||||
settings.Config.Server.NameToSource = map[string]settings.Source{
|
||||
"sourceA": sourceA,
|
||||
"sourceB": sourceB,
|
||||
}
|
||||
|
||||
// ---------------------
|
||||
// Test Cases Definition
|
||||
// ---------------------
|
||||
testCases := []struct {
|
||||
name string
|
||||
user *users.User
|
||||
expectedPhase1 []users.SourceScope
|
||||
expectedPhase2 []users.SourceScope
|
||||
}{
|
||||
{
|
||||
name: "Single valid scope",
|
||||
user: &users.User{
|
||||
Scopes: []users.SourceScope{
|
||||
{Scope: "/home", Name: "/pathA"},
|
||||
},
|
||||
},
|
||||
expectedPhase1: []users.SourceScope{
|
||||
{Scope: "/home", Name: "/pathA"},
|
||||
{Scope: "/defaultB", Name: "/pathB"},
|
||||
},
|
||||
expectedPhase2: []users.SourceScope{
|
||||
{Scope: "/home", Name: "/pathA"},
|
||||
{Scope: "/defaultB", Name: "/pathB"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Single empty scope path",
|
||||
user: &users.User{
|
||||
Scopes: []users.SourceScope{
|
||||
{Scope: "", Name: "/pathB"},
|
||||
},
|
||||
},
|
||||
expectedPhase1: []users.SourceScope{
|
||||
{Scope: "/defaultB", Name: "/pathB"},
|
||||
},
|
||||
expectedPhase2: []users.SourceScope{
|
||||
{Scope: "/defaultA", Name: "/pathA"},
|
||||
{Scope: "/defaultB", Name: "/pathB"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Two scopes, one includes username in path",
|
||||
user: &users.User{
|
||||
Username: "user123",
|
||||
Scopes: []users.SourceScope{
|
||||
{Scope: "/home/user123", Name: "/pathA"},
|
||||
{Scope: "/data", Name: "/pathB"},
|
||||
},
|
||||
},
|
||||
expectedPhase1: []users.SourceScope{
|
||||
{Scope: "/home/user123", Name: "/pathA"},
|
||||
{Scope: "/data", Name: "/pathB"},
|
||||
},
|
||||
expectedPhase2: []users.SourceScope{
|
||||
{Scope: "/home/user123", Name: "/pathA"},
|
||||
{Scope: "/data", Name: "/pathB"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Two scopes, one with empty name",
|
||||
user: &users.User{
|
||||
Scopes: []users.SourceScope{
|
||||
{Scope: "/home", Name: "/pathB"},
|
||||
{Scope: "/data", Name: "/somethingElse"},
|
||||
},
|
||||
},
|
||||
expectedPhase1: []users.SourceScope{
|
||||
{Scope: "/home", Name: "/pathB"},
|
||||
{Scope: "/data", Name: "/somethingElse"},
|
||||
},
|
||||
expectedPhase2: []users.SourceScope{
|
||||
{Scope: "/defaultA", Name: "/pathA"},
|
||||
{Scope: "/home", Name: "/pathB"},
|
||||
{Scope: "/data", Name: "/somethingElse"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "No scopes at all",
|
||||
user: &users.User{
|
||||
Scopes: []users.SourceScope{},
|
||||
},
|
||||
expectedPhase1: []users.SourceScope{
|
||||
{Scope: "/defaultB", Name: "/pathB"},
|
||||
},
|
||||
expectedPhase2: []users.SourceScope{
|
||||
{Scope: "/defaultA", Name: "/pathA"},
|
||||
{Scope: "/defaultB", Name: "/pathB"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "All user Scope and source change",
|
||||
user: &users.User{
|
||||
Username: "user123",
|
||||
Scopes: []users.SourceScope{
|
||||
{Scope: "/defaultC/user123", Name: "/pathC"},
|
||||
{Scope: "/defaultA/user123", Name: "/pathA"},
|
||||
{Scope: "/defaultB/user123", Name: "/pathB"},
|
||||
},
|
||||
},
|
||||
expectedPhase1: []users.SourceScope{
|
||||
{Scope: "/defaultA/user123", Name: "/pathA"},
|
||||
{Scope: "/defaultB/user123", Name: "/pathB"},
|
||||
{Scope: "/defaultC/user123", Name: "/pathC"},
|
||||
},
|
||||
expectedPhase2: []users.SourceScope{
|
||||
{Scope: "/defaultA/user123", Name: "/pathA"},
|
||||
{Scope: "/defaultB/user123", Name: "/pathB"},
|
||||
{Scope: "/defaultC/user123", Name: "/pathC"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// ---------------------
|
||||
// Phase 1 Tests
|
||||
// ---------------------
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name+"_Phase1", func(t *testing.T) {
|
||||
originalScopes := tc.user.Scopes
|
||||
updated := updateUserScopes(tc.user)
|
||||
assert.Equal(t, tc.expectedPhase1, tc.user.Scopes, "Phase1 scope mismatch for test case: %s", tc.name)
|
||||
assert.Equal(t, updated, !reflect.DeepEqual(originalScopes, tc.user.Scopes), "Phase2 scope change detection failed:\t %s vs expected:\t %s", tc.user.Scopes, tc.expectedPhase1)
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------
|
||||
// Phase 2: rename sources but keep same paths
|
||||
// ---------------------
|
||||
sourceA = settings.Source{Path: "/pathA", Name: "sourceA", Config: settings.SourceConfig{
|
||||
DefaultEnabled: true,
|
||||
DefaultUserScope: "/defaultA",
|
||||
CreateUserDir: true,
|
||||
}}
|
||||
sourceB = settings.Source{Path: "/pathB", Name: "sourceB", Config: settings.SourceConfig{DefaultEnabled: true, DefaultUserScope: "/defaultB"}}
|
||||
settings.Config.Server.Sources = []settings.Source{sourceA, sourceB}
|
||||
settings.Config.Server.DefaultSource = sourceB
|
||||
settings.Config.Server.SourceMap = map[string]settings.Source{
|
||||
"/pathA": sourceA,
|
||||
"/pathB": sourceB,
|
||||
}
|
||||
settings.Config.Server.NameToSource = map[string]settings.Source{
|
||||
"sourceA": sourceA,
|
||||
"sourceB": sourceB,
|
||||
}
|
||||
|
||||
// Run again without resetting user objects to test idempotency + renaming
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name+"_Phase2", func(t *testing.T) {
|
||||
originalScopes := tc.user.Scopes
|
||||
updated := updateUserScopes(tc.user)
|
||||
assert.Equal(t, tc.expectedPhase2, tc.user.Scopes, "Phase2 scope mismatch for test case: %s", tc.name)
|
||||
assert.Equal(t, updated, !reflect.DeepEqual(originalScopes, tc.user.Scopes), "Phase2 scope change detection failed:\t %s vs expected:\t %s", tc.user.Scopes, tc.expectedPhase1)
|
||||
|
||||
})
|
||||
}
|
||||
}
|
||||
Vendored
-88
@@ -1,88 +0,0 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
DiskUsage = NewCache(30*time.Second, 24*time.Hour)
|
||||
RealPath = NewCache(48*time.Hour, 72*time.Hour)
|
||||
SearchResults = NewCache(15*time.Second, 1*time.Hour)
|
||||
OnlyOffice = NewCache(48*time.Hour, 1*time.Hour)
|
||||
JwtCache = NewCache(1*time.Hour, 72*time.Hour)
|
||||
)
|
||||
|
||||
func NewCache(expires time.Duration, cleanup time.Duration) *KeyCache {
|
||||
newCache := KeyCache{
|
||||
data: make(map[string]cachedValue),
|
||||
expiresAfter: expires, // default
|
||||
}
|
||||
go newCache.cleanupExpiredJob(cleanup)
|
||||
return &newCache
|
||||
}
|
||||
|
||||
type KeyCache struct {
|
||||
data map[string]cachedValue
|
||||
mu sync.RWMutex
|
||||
expiresAfter time.Duration
|
||||
}
|
||||
|
||||
type cachedValue struct {
|
||||
value interface{}
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
func (c *KeyCache) Set(key string, value interface{}) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.data[key] = cachedValue{
|
||||
value: value,
|
||||
expiresAt: time.Now().Add(c.expiresAfter),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *KeyCache) Delete(key string) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
delete(c.data, key)
|
||||
}
|
||||
|
||||
func (c *KeyCache) SetWithExp(key string, value interface{}, exp time.Duration) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.data[key] = cachedValue{
|
||||
value: value,
|
||||
expiresAt: time.Now().Add(exp),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *KeyCache) Get(key string) interface{} {
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
cached, ok := c.data[key]
|
||||
if !ok || time.Now().After(cached.expiresAt) {
|
||||
return nil
|
||||
}
|
||||
return cached.value
|
||||
}
|
||||
|
||||
func (c *KeyCache) cleanupExpired() {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
now := time.Now()
|
||||
for key, cached := range c.data {
|
||||
if now.After(cached.expiresAt) {
|
||||
delete(c.data, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// should automatically run for all cache types as part of init.
|
||||
func (c *KeyCache) cleanupExpiredJob(frequency time.Duration) {
|
||||
ticker := time.NewTicker(frequency)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
c.cleanupExpired()
|
||||
}
|
||||
}
|
||||
@@ -18,4 +18,7 @@ var (
|
||||
ErrInvalidRequestParams = errors.New("invalid request params")
|
||||
ErrSourceIsParent = errors.New("source is parent")
|
||||
ErrRootUserDeletion = errors.New("user with id 1 can't be deleted")
|
||||
ErrNoTotpProvided = errors.New("OTP code is required for user")
|
||||
ErrNoTotpConfigured = errors.New("OTP is enforced, but user is not yet configured")
|
||||
ErrUnauthorized = errors.New("user unauthorized")
|
||||
)
|
||||
@@ -1,141 +0,0 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Logger wraps the standard log.Logger with log level functionality
|
||||
type Logger struct {
|
||||
logger *log.Logger
|
||||
levels []LogLevel
|
||||
apiLevels []LogLevel
|
||||
stdout bool
|
||||
disabled bool
|
||||
debugEnabled bool
|
||||
disabledAPI bool
|
||||
colors bool
|
||||
}
|
||||
|
||||
var stdOutLoggerExists bool
|
||||
|
||||
// NewLogger creates a new Logger instance with separate file and stdout loggers
|
||||
func NewLogger(filepath string, levels, apiLevels []LogLevel, noColors bool) (*Logger, error) {
|
||||
var fileWriter io.Writer = io.Discard
|
||||
stdout := filepath == ""
|
||||
// Configure file logging
|
||||
if !stdout {
|
||||
file, err := os.OpenFile(filepath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open log file: %v", err)
|
||||
}
|
||||
fileWriter = file
|
||||
}
|
||||
var flags int
|
||||
if slices.Contains(levels, DEBUG) {
|
||||
flags |= log.Lshortfile
|
||||
}
|
||||
logger := log.New(os.Stdout, "", flags)
|
||||
if filepath != "" {
|
||||
logger = log.New(fileWriter, "", flags)
|
||||
}
|
||||
if stdout {
|
||||
stdOutLoggerExists = true
|
||||
}
|
||||
return &Logger{
|
||||
logger: logger,
|
||||
levels: levels,
|
||||
apiLevels: apiLevels,
|
||||
disabled: slices.Contains(levels, DISABLED),
|
||||
debugEnabled: slices.Contains(levels, DEBUG),
|
||||
disabledAPI: slices.Contains(apiLevels, DISABLED),
|
||||
colors: !noColors,
|
||||
stdout: stdout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// SetupLogger configures the logger with file and stdout options and their respective log levels
|
||||
func SetupLogger(output, levels, apiLevels string, noColors bool) error {
|
||||
upperLevels := []LogLevel{}
|
||||
for _, level := range SplitByMultiple(levels) {
|
||||
if level == "" {
|
||||
break
|
||||
}
|
||||
upperLevel := strings.ToUpper(level)
|
||||
if upperLevel == "WARNING" || upperLevel == "WARN" {
|
||||
upperLevel = "WARN "
|
||||
}
|
||||
if upperLevel == "INFO" {
|
||||
upperLevel = "INFO "
|
||||
}
|
||||
// Convert level strings to LogLevel
|
||||
level, ok := stringToLevel[upperLevel]
|
||||
if !ok {
|
||||
loggers = []*Logger{}
|
||||
return fmt.Errorf("invalid file log level: %s", upperLevel)
|
||||
}
|
||||
upperLevels = append(upperLevels, level)
|
||||
}
|
||||
if len(upperLevels) == 0 {
|
||||
upperLevels = []LogLevel{INFO, ERROR, WARNING}
|
||||
}
|
||||
upperApiLevels := []LogLevel{}
|
||||
for _, level := range SplitByMultiple(apiLevels) {
|
||||
if level == "" {
|
||||
break
|
||||
}
|
||||
upperLevel := strings.ToUpper(level)
|
||||
if upperLevel == "WARNING" || upperLevel == "WARN" {
|
||||
upperLevel = "WARN "
|
||||
}
|
||||
if upperLevel == "INFO" {
|
||||
upperLevel = "INFO "
|
||||
}
|
||||
// Convert level strings to LogLevel
|
||||
level, ok := stringToLevel[strings.ToUpper(upperLevel)]
|
||||
if !ok {
|
||||
return fmt.Errorf("invalid api log level: %s", upperLevel)
|
||||
}
|
||||
upperApiLevels = append(upperApiLevels, level)
|
||||
}
|
||||
if len(upperApiLevels) == 0 {
|
||||
upperApiLevels = []LogLevel{INFO, ERROR, WARNING}
|
||||
}
|
||||
if slices.Contains(upperLevels, DISABLED) && slices.Contains(upperApiLevels, DISABLED) {
|
||||
// both disabled, not creating a logger
|
||||
loggers = []*Logger{}
|
||||
return nil
|
||||
}
|
||||
outputStdout := strings.ToUpper(output)
|
||||
if outputStdout == "STDOUT" {
|
||||
output = ""
|
||||
}
|
||||
if output == "" && stdOutLoggerExists {
|
||||
// stdout logger already exists... don't create another
|
||||
return fmt.Errorf("stdout logger already exists, could not set config levels=[%v] apiLevels=[%v] noColors=[%v]", levels, apiLevels, noColors)
|
||||
}
|
||||
// Create the logger
|
||||
logger, err := NewLogger(output, upperLevels, upperApiLevels, noColors)
|
||||
if err != nil {
|
||||
loggers = []*Logger{}
|
||||
return err
|
||||
}
|
||||
loggers = append(loggers, logger)
|
||||
return nil
|
||||
}
|
||||
|
||||
func SplitByMultiple(str string) []string {
|
||||
delimiters := []rune{'|', ',', ' '}
|
||||
return strings.FieldsFunc(str, func(r rune) bool {
|
||||
for _, d := range delimiters {
|
||||
if r == d {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"slices"
|
||||
"time"
|
||||
)
|
||||
|
||||
type LogLevel int
|
||||
|
||||
const (
|
||||
DISABLED LogLevel = 0
|
||||
ERROR LogLevel = 1
|
||||
FATAL LogLevel = 1
|
||||
WARNING LogLevel = 2
|
||||
INFO LogLevel = 3
|
||||
DEBUG LogLevel = 4
|
||||
API LogLevel = 10
|
||||
// COLORS
|
||||
RED = "\033[31m"
|
||||
GREEN = "\033[32m"
|
||||
YELLOW = "\033[33m"
|
||||
GRAY = "\033[37m"
|
||||
)
|
||||
|
||||
var (
|
||||
loggers []*Logger
|
||||
)
|
||||
|
||||
type levelConsts struct {
|
||||
INFO string
|
||||
FATAL string
|
||||
ERROR string
|
||||
WARNING string
|
||||
DEBUG string
|
||||
API string
|
||||
DISABLED string
|
||||
}
|
||||
|
||||
var levels = levelConsts{
|
||||
INFO: "INFO ", // with consistent space padding
|
||||
FATAL: "FATAL",
|
||||
ERROR: "ERROR",
|
||||
WARNING: "WARN ", // with consistent space padding
|
||||
DEBUG: "DEBUG",
|
||||
DISABLED: "DISABLED",
|
||||
API: "API",
|
||||
}
|
||||
|
||||
// stringToLevel maps string representation to LogLevel
|
||||
var stringToLevel = map[string]LogLevel{
|
||||
"DEBUG": DEBUG,
|
||||
"INFO ": INFO, // with consistent space padding
|
||||
"ERROR": ERROR,
|
||||
"DISABLED": DISABLED,
|
||||
"WARN ": WARNING, // with consistent space padding
|
||||
"FATAL": FATAL,
|
||||
"API": API,
|
||||
}
|
||||
|
||||
// Log prints a log message if its level is greater than or equal to the logger's levels
|
||||
func Log(level string, msg string, prefix, api bool, color string) {
|
||||
LEVEL := stringToLevel[level]
|
||||
for _, logger := range loggers {
|
||||
if api {
|
||||
if logger.disabledAPI || !slices.Contains(logger.apiLevels, LEVEL) {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
if logger.disabled || !slices.Contains(logger.levels, LEVEL) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if logger.stdout && level == "FATAL" {
|
||||
continue
|
||||
}
|
||||
writeOut := msg
|
||||
formattedTime := time.Now().Format("2006/01/02 15:04:05")
|
||||
if logger.colors && color != "" {
|
||||
formattedTime = formattedTime + color
|
||||
}
|
||||
if prefix || logger.debugEnabled {
|
||||
logger.logger.SetPrefix(fmt.Sprintf("%s [%s] ", formattedTime, level))
|
||||
} else {
|
||||
logger.logger.SetPrefix(formattedTime + " ")
|
||||
}
|
||||
if logger.colors && color != "" {
|
||||
writeOut = writeOut + "\033[0m"
|
||||
}
|
||||
err := logger.logger.Output(3, writeOut) // 3 skips this function for correct file:line
|
||||
if err != nil {
|
||||
log.Printf("failed to log message '%v' with error `%v`", msg, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func Api(msg string, statusCode int) {
|
||||
// redirects are not warnings anymore
|
||||
if statusCode > 302 && statusCode < 500 {
|
||||
Log(levels.WARNING, msg, false, true, YELLOW)
|
||||
} else if statusCode >= 500 {
|
||||
Log(levels.ERROR, msg, false, true, RED)
|
||||
} else {
|
||||
Log(levels.INFO, msg, false, true, GREEN)
|
||||
}
|
||||
}
|
||||
|
||||
// Helper methods for specific log levels
|
||||
func Debug(msg string) {
|
||||
if len(loggers) > 0 {
|
||||
Log(levels.DEBUG, msg, true, false, GRAY)
|
||||
} else {
|
||||
log.Println("[DEBUG] ", msg)
|
||||
}
|
||||
}
|
||||
|
||||
func Info(msg string) {
|
||||
if len(loggers) > 0 {
|
||||
Log(levels.INFO, msg, false, false, "")
|
||||
} else {
|
||||
log.Println(msg)
|
||||
}
|
||||
}
|
||||
|
||||
func Warning(msg string) {
|
||||
if len(loggers) > 0 {
|
||||
Log(levels.WARNING, msg, true, false, YELLOW)
|
||||
} else {
|
||||
log.Println("[WARN ] ", msg)
|
||||
}
|
||||
}
|
||||
|
||||
func Error(msg string) {
|
||||
if len(loggers) > 0 {
|
||||
Log(levels.ERROR, msg, true, false, RED)
|
||||
} else {
|
||||
log.Println("[ERROR]", msg)
|
||||
}
|
||||
}
|
||||
|
||||
func Fatal(msg string) {
|
||||
if len(loggers) > 0 {
|
||||
Log(levels.FATAL, msg, true, false, RED)
|
||||
}
|
||||
log.Fatal("[FATAL] ", msg)
|
||||
}
|
||||
@@ -1,11 +1,24 @@
|
||||
package settings
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
type Auth struct {
|
||||
TokenExpirationHours int `json:"tokenExpirationHours"` // the number of hours until the token expires. Default is 2 hours.
|
||||
Methods LoginMethods `json:"methods"`
|
||||
Key string `json:"key"` // the key used to sign the JWT tokens. If not set, a random key will be generated.
|
||||
AdminUsername string `json:"adminUsername"` // the username of the admin user. If not set, the default is "admin".
|
||||
AdminPassword string `json:"adminPassword"` // the password of the admin user. If not set, the default is "admin".
|
||||
Key string `json:"key"` // the key used to sign the JWT tokens. If not set, a random key will be generated.
|
||||
AdminUsername string `json:"adminUsername"` // the username of the admin user. If not set, the default is "admin".
|
||||
AdminPassword string `json:"adminPassword"` // the password of the admin user. If not set, the default is "admin".
|
||||
ResetAdminOnStart bool `json:"resetAdminOnStart"` // if set to true, the admin user will be reset to the default username and password on startup.
|
||||
TotpSecret string `json:"totpSecret"` // secret used to encrypt TOTP secrets
|
||||
AuthMethods []string `json:"-"`
|
||||
}
|
||||
|
||||
@@ -17,16 +30,18 @@ type LoginMethods struct {
|
||||
}
|
||||
|
||||
type PasswordAuthConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
MinLength int `json:"minLength" validate:"omitempty,min=5"`
|
||||
Signup bool `json:"signup" validate:"omitempty"` // currently not used by filebrowser
|
||||
Recaptcha Recaptcha `json:"recaptcha" validate:"omitempty"` // recaptcha config, only used if signup is enabled
|
||||
Enabled bool `json:"enabled"`
|
||||
MinLength int `json:"minLength" validate:"omitempty,min=5"` // minimum pasword length required.
|
||||
Signup bool `json:"signup" validate:"omitempty"` // allow signups on login page if enabled -- not secure.
|
||||
Recaptcha Recaptcha `json:"recaptcha" validate:"omitempty"` // recaptcha config, only used if signup is enabled
|
||||
EnforcedOtp bool `json:"enforcedOtp"` // if set to true, TOTP is enforced for all password users users. Otherwise, users can choose to enable TOTP.
|
||||
}
|
||||
|
||||
type ProxyAuthConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
CreateUser bool `json:"createUser"` // create user if not exists
|
||||
Header string `json:"header"` // required header to use for authentication. Security Warning: FileBrowser blindly accepts the header value as username.
|
||||
Enabled bool `json:"enabled"`
|
||||
CreateUser bool `json:"createUser"` // create user if not exists
|
||||
Header string `json:"header"` // required header to use for authentication. Security Warning: FileBrowser blindly accepts the header value as username.
|
||||
LogoutRedirectUrl string `json:"logoutRedirectUrl"` // if provider logout url is provided, filebrowser will also redirect to logout url. Custom logout query params are respected.
|
||||
}
|
||||
|
||||
type Recaptcha struct {
|
||||
@@ -37,13 +52,55 @@ type Recaptcha struct {
|
||||
|
||||
// OpenID OAuth2.0
|
||||
type OidcConfig struct {
|
||||
Enabled bool `json:"enabled"` // whether to enable OIDC authentication
|
||||
ClientID string `json:"clientId" validate:"required"` // client id of the OIDC application
|
||||
ClientSecret string `json:"clientSecret" validate:"required"` // client secret of the OIDC application
|
||||
AuthorizationUrl string `json:"authorizationUrl" validate:"required"` // authorization URL of the OIDC provider
|
||||
TokenUrl string `json:"tokenUrl" validate:"required"` // token URL of the OIDC provider
|
||||
UserInfoUrl string `json:"userInfoUrl" validate:"required"` // user info URL of the OIDC provider
|
||||
Scopes string `json:"scopes" validate:"required"` // space separated list of scopes to request from the OIDC provider
|
||||
UserIdentifier string `json:"userIdentifier"` // optional: which attribute should be used as the username? options: email, username, name, phone_number, sub
|
||||
JwksUrl string `json:"jwksUrl"` // currently not used by filebrowser
|
||||
Enabled bool `json:"enabled"` // whether to enable OIDC authentication
|
||||
ClientID string `json:"clientId"` // client id of the OIDC application
|
||||
ClientSecret string `json:"clientSecret"` // client secret of the OIDC application
|
||||
IssuerUrl string `json:"issuerUrl"` // authorization URL of the OIDC provider
|
||||
Scopes string `json:"scopes"` // scopes to request from the OIDC provider
|
||||
UserIdentifier string `json:"userIdentifier"` // the user identifier to use for authentication. Default is "username", can be "email" or "username", or "phone"
|
||||
DisableVerifyTLS bool `json:"disableVerifyTLS"` // disable TLS verification for the OIDC provider. This is insecure and should only be used for testing.
|
||||
LogoutRedirectUrl string `json:"logoutRedirectUrl"` // if provider logout url is provided, filebrowser will also redirect to logout url. Custom logout query params are respected.
|
||||
Provider *oidc.Provider `json:"-"` // OIDC provider
|
||||
Verifier *oidc.IDTokenVerifier `json:"-"` // OIDC verifier
|
||||
}
|
||||
|
||||
// ValidateOidcAuth processes the OIDC callback and retrieves user identity
|
||||
func validateOidcAuth() error {
|
||||
oidcCfg := &Config.Auth.Methods.OidcAuth // Use a pointer to modify the original config
|
||||
if !oidcCfg.Enabled {
|
||||
return errors.New("OIDC is not enabled")
|
||||
}
|
||||
if oidcCfg.UserIdentifier == "" {
|
||||
oidcCfg.UserIdentifier = "username"
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// If disableVerifyTLS is true, create a custom HTTP client
|
||||
// and set it in the context for the OIDC provider.
|
||||
if oidcCfg.DisableVerifyTLS {
|
||||
// Create a custom transport with InsecureSkipVerify set to true
|
||||
transport := &http.Transport{
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
|
||||
}
|
||||
customClient := &http.Client{
|
||||
Transport: transport,
|
||||
}
|
||||
// Use oidc.ClientContext to pass the custom client to the OIDC library
|
||||
ctx = oidc.ClientContext(ctx, customClient)
|
||||
// Log that TLS verification is disabled (important for security awareness)
|
||||
logger.Warning("OIDC TLS verification is disabled.")
|
||||
}
|
||||
|
||||
provider, err := oidc.NewProvider(ctx, oidcCfg.IssuerUrl)
|
||||
if err != nil {
|
||||
return fmt.Errorf("url '%v' failed to create OIDC provider: %w", oidcCfg.IssuerUrl, err)
|
||||
}
|
||||
oidcCfg.Provider = provider
|
||||
oidcCfg.Verifier = provider.Verifier(&oidc.Config{ClientID: oidcCfg.ClientID})
|
||||
if oidcCfg.Scopes == "" {
|
||||
oidcCfg.Scopes = "openid email profile"
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -5,18 +5,24 @@ import (
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/goccy/go-yaml"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/version"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
var Config Settings
|
||||
|
||||
const (
|
||||
generatorPath = "/relative/or/absolute/path"
|
||||
)
|
||||
|
||||
func Initialize(configFile string) {
|
||||
err := loadConfigWithDefaults(configFile)
|
||||
if err != nil {
|
||||
@@ -24,17 +30,17 @@ func Initialize(configFile string) {
|
||||
}
|
||||
err = ValidateConfig(Config)
|
||||
if err != nil {
|
||||
errmsg := "the provided config file failed validation. "
|
||||
errmsg := "The provided config file failed validation. "
|
||||
errmsg += "If you are seeing this on a config that worked previeously, "
|
||||
errmsg += "this is because v0.6.8 requires a fully validated config to run. "
|
||||
errmsg += "Please review your config for typos and invalid keys which are no longer supported. "
|
||||
errmsg += "please review your config for typos and invalid keys which are no longer supported. "
|
||||
errmsg += "visit https://github.com/gtsteffaniak/filebrowser/wiki/Full-Config-Example for more information."
|
||||
logger.Error(errmsg)
|
||||
time.Sleep(5 * time.Second) // allow sleep time before exiting to give docker/kubernetes time before restarting
|
||||
logger.Fatal(err.Error())
|
||||
}
|
||||
setupLogging()
|
||||
setupAuth()
|
||||
setupSources()
|
||||
setupSources(false)
|
||||
setupUrls()
|
||||
setupFrontend()
|
||||
}
|
||||
@@ -56,16 +62,16 @@ func setupFrontend() {
|
||||
func getRealPath(path string) string {
|
||||
realPath, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
logger.Fatal(fmt.Sprintf("could not find configured source path: %v", err))
|
||||
logger.Fatalf("could not find configured source path: %v", err)
|
||||
}
|
||||
// check path exists
|
||||
if _, err = os.Stat(realPath); os.IsNotExist(err) {
|
||||
logger.Fatal(fmt.Sprintf("configured source path does not exist: %v", realPath))
|
||||
logger.Fatalf("configured source path does not exist: %v", realPath)
|
||||
}
|
||||
return realPath
|
||||
}
|
||||
|
||||
func setupSources() {
|
||||
func setupSources(generate bool) {
|
||||
if len(Config.Server.Sources) == 0 {
|
||||
logger.Fatal("There are no `server.sources` configured. If you have `server.root` configured, please update the config and add at least one `server.sources` with a `path` configured.")
|
||||
} else {
|
||||
@@ -75,7 +81,11 @@ func setupSources() {
|
||||
if name == "\\" {
|
||||
name = strings.Split(realPath, ":")[0]
|
||||
}
|
||||
source.Path = realPath // use absolute path
|
||||
if generate {
|
||||
source.Path = generatorPath // use placeholder path
|
||||
} else {
|
||||
source.Path = realPath // use absolute path
|
||||
}
|
||||
if source.Name == "" {
|
||||
_, ok := Config.Server.SourceMap[source.Path]
|
||||
if ok {
|
||||
@@ -102,6 +112,9 @@ func setupSources() {
|
||||
potentialDefaultSource := Config.Server.DefaultSource
|
||||
for _, sourcePathOnly := range Config.Server.Sources {
|
||||
realPath := getRealPath(sourcePathOnly.Path)
|
||||
if generate {
|
||||
realPath = generatorPath // use placeholder path
|
||||
}
|
||||
source, ok := Config.Server.SourceMap[realPath]
|
||||
if ok && !slices.Contains(allSourceNames, source.Name) {
|
||||
if first {
|
||||
@@ -120,12 +133,22 @@ func setupSources() {
|
||||
}
|
||||
allSourceNames = append(allSourceNames, source.Name)
|
||||
} else {
|
||||
logger.Warning(fmt.Sprintf("source %v is not configured correctly, skipping", sourcePathOnly.Path))
|
||||
logger.Warningf("source %v is not configured correctly, skipping", sourcePathOnly.Path)
|
||||
}
|
||||
}
|
||||
if Config.Server.DefaultSource.Path == "" {
|
||||
Config.Server.DefaultSource = potentialDefaultSource
|
||||
}
|
||||
sourceList2 := []Source{}
|
||||
for _, s := range sourceList {
|
||||
if s.Path == Config.Server.DefaultSource.Path {
|
||||
s.Config.DefaultEnabled = true
|
||||
Config.Server.SourceMap[s.Path] = s
|
||||
Config.Server.NameToSource[s.Name] = s
|
||||
}
|
||||
sourceList2 = append(sourceList2, s)
|
||||
}
|
||||
sourceList = sourceList2
|
||||
Config.UserDefaults.DefaultScopes = defaultScopes
|
||||
Config.Server.Sources = sourceList
|
||||
}
|
||||
@@ -145,23 +168,33 @@ func setupUrls() {
|
||||
|
||||
func setupAuth() {
|
||||
if Config.Auth.Methods.PasswordAuth.Enabled {
|
||||
Config.Auth.AuthMethods = append(Config.Auth.AuthMethods, "Password")
|
||||
Config.Auth.AuthMethods = append(Config.Auth.AuthMethods, "password")
|
||||
}
|
||||
if Config.Auth.Methods.ProxyAuth.Enabled {
|
||||
Config.Auth.AuthMethods = append(Config.Auth.AuthMethods, "Proxy")
|
||||
Config.Auth.AuthMethods = append(Config.Auth.AuthMethods, "proxy")
|
||||
}
|
||||
if Config.Auth.Methods.OidcAuth.Enabled {
|
||||
Config.Auth.AuthMethods = append(Config.Auth.AuthMethods, "OIDC")
|
||||
Config.Auth.AuthMethods = append(Config.Auth.AuthMethods, "oidc")
|
||||
}
|
||||
if Config.Auth.Methods.NoAuth {
|
||||
logger.Warning("Configured with no authentication, this is not recommended.")
|
||||
Config.Auth.AuthMethods = []string{"Disabled"}
|
||||
Config.Auth.AuthMethods = []string{"disabled"}
|
||||
}
|
||||
if Config.Auth.Methods.OidcAuth.Enabled {
|
||||
err := validateOidcAuth()
|
||||
if err != nil {
|
||||
logger.Fatalf("Error validating OIDC auth: %v", err)
|
||||
}
|
||||
logger.Info("OIDC Auth configured successfully")
|
||||
}
|
||||
|
||||
// use password auth as default if no auth methods are set
|
||||
if len(Config.Auth.AuthMethods) == 0 {
|
||||
Config.Auth.Methods.PasswordAuth.Enabled = true
|
||||
Config.Auth.AuthMethods = append(Config.Auth.AuthMethods, "Password")
|
||||
Config.Auth.AuthMethods = append(Config.Auth.AuthMethods, "password")
|
||||
}
|
||||
Config.UserDefaults.LoginMethod = Config.Auth.AuthMethods[0]
|
||||
|
||||
}
|
||||
|
||||
func setupLogging() {
|
||||
@@ -173,12 +206,15 @@ func setupLogging() {
|
||||
}
|
||||
}
|
||||
for _, logConfig := range Config.Server.Logging {
|
||||
err := logger.SetupLogger(
|
||||
logConfig.Output,
|
||||
logConfig.Levels,
|
||||
logConfig.ApiLevels,
|
||||
logConfig.NoColors,
|
||||
)
|
||||
logConfig := logger.JsonConfig{
|
||||
Levels: logConfig.Levels,
|
||||
ApiLevels: logConfig.ApiLevels,
|
||||
Output: logConfig.Output,
|
||||
Utc: logConfig.Utc,
|
||||
NoColors: logConfig.NoColors,
|
||||
Json: logConfig.Json,
|
||||
}
|
||||
err := logger.SetupLogger(logConfig)
|
||||
if err != nil {
|
||||
log.Println("[ERROR] Failed to set up logger:", err)
|
||||
}
|
||||
@@ -190,7 +226,14 @@ func loadConfigWithDefaults(configFile string) error {
|
||||
// Open and read the YAML file
|
||||
yamlFile, err := os.Open(configFile)
|
||||
if err != nil {
|
||||
return err
|
||||
logger.Warningf("could not open config file '%v', using default settings", configFile)
|
||||
Config.Server.Sources = []Source{
|
||||
{
|
||||
Path: ".",
|
||||
},
|
||||
}
|
||||
loadEnvConfig()
|
||||
return nil
|
||||
}
|
||||
defer yamlFile.Close()
|
||||
stat, err := yamlFile.Stat()
|
||||
@@ -203,7 +246,7 @@ func loadConfigWithDefaults(configFile string) error {
|
||||
return fmt.Errorf("could not load specified config file: %v", err.Error())
|
||||
}
|
||||
if err != nil {
|
||||
logger.Warning(fmt.Sprintf("Could not load config file '%v', using default settings: %v", configFile, err))
|
||||
logger.Warningf("Could not load config file '%v', using default settings: %v", configFile, err)
|
||||
}
|
||||
err = yaml.NewDecoder(strings.NewReader(string(yamlData)), yaml.DisallowUnknownField()).Decode(&Config)
|
||||
if err != nil {
|
||||
@@ -244,10 +287,15 @@ func loadEnvConfig() {
|
||||
}
|
||||
|
||||
func setDefaults() Settings {
|
||||
// get number of CPUs available
|
||||
numCpus := 4 // default to 4 CPUs if runtime.NumCPU() fails or is not available
|
||||
if cpus := runtime.NumCPU(); cpus > 0 {
|
||||
numCpus = cpus
|
||||
}
|
||||
return Settings{
|
||||
Server: Server{
|
||||
Port: 80,
|
||||
NumImageProcessors: 4,
|
||||
NumImageProcessors: numCpus,
|
||||
BaseURL: "",
|
||||
Database: "database.db",
|
||||
SourceMap: map[string]Source{},
|
||||
@@ -366,7 +414,7 @@ func HasSourceByPath(scopes []users.SourceScope, sourcePath string) bool {
|
||||
func GetScopeFromSourceName(scopes []users.SourceScope, sourceName string) (string, error) {
|
||||
source, ok := Config.Server.NameToSource[sourceName]
|
||||
if !ok {
|
||||
logger.Debug(fmt.Sprint("Could not get scope from source name: ", sourceName))
|
||||
logger.Debug("Could not get scope from source name: ", sourceName)
|
||||
return "", fmt.Errorf("source with name not found %v", sourceName)
|
||||
}
|
||||
for _, scope := range scopes {
|
||||
@@ -374,7 +422,7 @@ func GetScopeFromSourceName(scopes []users.SourceScope, sourceName string) (stri
|
||||
return scope.Scope, nil
|
||||
}
|
||||
}
|
||||
logger.Debug(fmt.Sprintf("scope not found for source %v", sourceName))
|
||||
logger.Debugf("scope not found for source %v", sourceName)
|
||||
return "", fmt.Errorf("scope not found for source %v", sourceName)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
// cmd/yamlgen/main.go
|
||||
package main
|
||||
package settings
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"flag"
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
@@ -13,7 +11,6 @@ import (
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
@@ -116,12 +113,13 @@ func buildNode(v reflect.Value, comm commentsMap) (*yaml.Node, error) {
|
||||
|
||||
// attach validate and comments inline
|
||||
var parts []string
|
||||
if vt := sf.Tag.Get("validate"); vt != "" {
|
||||
parts = append(parts, fmt.Sprintf("validate:%s", vt))
|
||||
}
|
||||
if cm := comm[typeName][sf.Name]; cm != "" {
|
||||
parts = append(parts, fmt.Sprintf("comments:\"%s\"", cm))
|
||||
parts = append(parts, cm)
|
||||
}
|
||||
if vt := sf.Tag.Get("validate"); vt != "" {
|
||||
parts = append(parts, fmt.Sprintf(" validate:%s", vt))
|
||||
}
|
||||
|
||||
if len(parts) > 0 {
|
||||
keyNode.LineComment = strings.Join(parts, " ")
|
||||
}
|
||||
@@ -168,19 +166,29 @@ func buildNode(v reflect.Value, comm commentsMap) (*yaml.Node, error) {
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
input := flag.String("input", "settings/settings.go", "path to Go source file or directory containing structs")
|
||||
output := flag.String("output", "settings/config.generated.yaml", "path to write generated YAML")
|
||||
flag.Parse()
|
||||
func GenerateYaml() {
|
||||
_ = loadConfigWithDefaults("")
|
||||
Config.Server.Sources = []Source{
|
||||
{
|
||||
Path: ".",
|
||||
},
|
||||
}
|
||||
|
||||
comm, err := collectComments(*input)
|
||||
setupLogging()
|
||||
setupAuth()
|
||||
setupSources(true)
|
||||
setupUrls()
|
||||
setupFrontend()
|
||||
input := "common/settings/settings.go" // "path to Go source file or directory containing structs"
|
||||
output := "generated.yaml" // "output YAML file"
|
||||
|
||||
comm, err := collectComments(input)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error parsing comments: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
cfg := &settings.Settings{}
|
||||
node, err := buildNode(reflect.ValueOf(cfg), comm)
|
||||
node, err := buildNode(reflect.ValueOf(Config), comm)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error building YAML node: %v\n", err)
|
||||
os.Exit(1)
|
||||
@@ -199,51 +207,49 @@ func main() {
|
||||
|
||||
aligned := alignComments(rawBuf.String())
|
||||
|
||||
if err := os.WriteFile(*output, []byte(aligned), 0644); err != nil {
|
||||
if err := os.WriteFile(output, []byte(aligned), 0644); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error writing YAML: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Printf("Generated YAML with comments: %s\n", *output)
|
||||
fmt.Printf("Generated YAML with comments: %s\n", output)
|
||||
}
|
||||
|
||||
// alignComments scans YAML text and aligns all inline '#' within each indentation block
|
||||
// formatLine applies padding to a single line so its comment starts at a target column.
|
||||
func formatLine(line string) string {
|
||||
const targetCol = 42
|
||||
const defaultPadding = 1
|
||||
|
||||
idx := strings.Index(line, "#")
|
||||
// If there's no comment, do nothing.
|
||||
if idx == -1 {
|
||||
return line
|
||||
}
|
||||
|
||||
// Separate the content (before #) from the comment (from # onwards).
|
||||
contentPart := line[:idx]
|
||||
commentPart := line[idx:]
|
||||
|
||||
// The YAML encoder adds a space; trim it so we measure only the content length.
|
||||
trimmedContent := strings.TrimRight(contentPart, " ")
|
||||
|
||||
// If the content already extends past our target column, just add a single space.
|
||||
if len(trimmedContent) >= targetCol {
|
||||
return trimmedContent + strings.Repeat(" ", defaultPadding) + commentPart
|
||||
}
|
||||
|
||||
// Otherwise, calculate the needed padding to reach the target column and add it.
|
||||
paddingNeeded := targetCol - len(trimmedContent)
|
||||
return trimmedContent + strings.Repeat(" ", paddingNeeded) + commentPart
|
||||
}
|
||||
|
||||
// alignComments formats each line of the YAML string independently.
|
||||
func alignComments(input string) string {
|
||||
lines := strings.Split(input, "\n")
|
||||
var out []string
|
||||
blockStart := 0
|
||||
maxPos := 0
|
||||
for i, line := range lines {
|
||||
trim := strings.TrimLeft(line, " ")
|
||||
// new block when indentation decreases
|
||||
if i > 0 {
|
||||
prevIndent := len(lines[i-1]) - len(strings.TrimLeft(lines[i-1], " "))
|
||||
curIndent := len(line) - len(trim)
|
||||
if curIndent < prevIndent {
|
||||
for j := blockStart; j < i; j++ {
|
||||
out = append(out, padLine(lines[j], maxPos))
|
||||
}
|
||||
blockStart = i
|
||||
maxPos = 0
|
||||
}
|
||||
}
|
||||
if idx := strings.Index(line, "#"); idx >= 0 {
|
||||
if idx > maxPos {
|
||||
maxPos = idx
|
||||
}
|
||||
}
|
||||
if i == len(lines)-1 {
|
||||
for j := blockStart; j <= i; j++ {
|
||||
out = append(out, padLine(lines[j], maxPos))
|
||||
}
|
||||
}
|
||||
}
|
||||
return strings.Join(out, "\n")
|
||||
}
|
||||
outputLines := make([]string, len(lines))
|
||||
|
||||
// padLine inserts spaces before '#' so it lands at column maxPos
|
||||
func padLine(line string, maxPos int) string {
|
||||
if idx := strings.Index(line, "#"); idx >= 0 && idx < maxPos {
|
||||
return line[:idx] + strings.Repeat(" ", maxPos-idx) + line[idx:]
|
||||
for i, line := range lines {
|
||||
outputLines[i] = formatLine(line)
|
||||
}
|
||||
return line
|
||||
|
||||
return strings.Join(outputLines, "\n")
|
||||
}
|
||||
@@ -46,6 +46,7 @@ func ApplyUserDefaults(u *users.User) {
|
||||
u.ViewMode = Config.UserDefaults.ViewMode
|
||||
u.SingleClick = Config.UserDefaults.SingleClick
|
||||
u.Permissions = Config.UserDefaults.Permissions
|
||||
u.Preview = Config.UserDefaults.Preview
|
||||
u.ShowHidden = Config.UserDefaults.ShowHidden
|
||||
u.DateFormat = Config.UserDefaults.DateFormat
|
||||
u.DisableOnlyOfficeExt = Config.UserDefaults.DisableOnlyOfficeExt
|
||||
|
||||
@@ -21,7 +21,7 @@ type Settings struct {
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
NumImageProcessors int `json:"numImageProcessors"` // number of concurrent image processing jobs
|
||||
NumImageProcessors int `json:"numImageProcessors"` // number of concurrent image processing jobs used to create previews, default is number of cpu cores available.
|
||||
Socket string `json:"socket"` // socket to listen on
|
||||
TLSKey string `json:"tlsKey"` // path to TLS key
|
||||
TLSCert string `json:"tlsCert"` // path to TLS cert
|
||||
@@ -31,16 +31,18 @@ type Server struct {
|
||||
Port int `json:"port"` // port to listen on
|
||||
BaseURL string `json:"baseURL"` // base URL for the server, the subpath that the server is running on.
|
||||
Logging []LogConfig `json:"logging"`
|
||||
Database string `json:"database"` // path to the database file
|
||||
DebugMedia bool `json:"debugMedia"` // output ffmpeg stdout for media integration -- careful can produces lots of output!
|
||||
Database string `json:"database"` // path to the database file
|
||||
Sources []Source `json:"sources" validate:"required,dive"`
|
||||
ExternalUrl string `json:"externalUrl"` // used by share links if set
|
||||
InternalUrl string `json:"internalUrl"` // used by integrations if set, this is the url that an integration service will use to communicate with filebrowser
|
||||
CacheDir string `json:"cacheDir"` // path to the cache directory, used for thumbnails and other cached files
|
||||
MaxArchiveSizeGB int64 `json:"maxArchiveSize"` // max pre-archive combined size of files/folder that are allowed to be archived (in GB)
|
||||
// not exposed to config
|
||||
SourceMap map[string]Source `json:"-" validate:"omitempty"` // uses realpath as key
|
||||
NameToSource map[string]Source `json:"-" validate:"omitempty"` // uses name as key
|
||||
DefaultSource Source `json:"-" validate:"omitempty"`
|
||||
SourceMap map[string]Source `json:"-" validate:"omitempty"` // uses realpath as key
|
||||
NameToSource map[string]Source `json:"-" validate:"omitempty"` // uses name as key
|
||||
DefaultSource Source `json:"-" validate:"omitempty"`
|
||||
MuPdfAvailable bool `json:"-"` // used internally if compiled with mupdf support
|
||||
}
|
||||
|
||||
type Integrations struct {
|
||||
@@ -66,6 +68,7 @@ type LogConfig struct {
|
||||
Output string `json:"output"` // output location. (eg. "stdout" or "path/to/file.log")
|
||||
NoColors bool `json:"noColors"` // disable colors in the output
|
||||
Json bool `json:"json"` // output in json format, currently not supported
|
||||
Utc bool `json:"utc"` // use UTC time in the output instead of local time
|
||||
}
|
||||
|
||||
type Source struct {
|
||||
@@ -110,20 +113,22 @@ type ExternalLink struct {
|
||||
// UserDefaults is a type that holds the default values
|
||||
// for some fields on User.
|
||||
type UserDefaults struct {
|
||||
PreviewOptions users.PreviewOptions `json:"preview"`
|
||||
StickySidebar bool `json:"stickySidebar"`
|
||||
DarkMode bool `json:"darkMode"`
|
||||
LockPassword bool `json:"lockPassword"`
|
||||
DisableSettings bool `json:"disableSettings,omitempty"`
|
||||
Locale string `json:"locale"`
|
||||
ViewMode string `json:"viewMode"`
|
||||
GallerySize int `json:"gallerySize"`
|
||||
SingleClick bool `json:"singleClick"`
|
||||
Permissions users.Permissions `json:"permissions"`
|
||||
ShowHidden bool `json:"showHidden"`
|
||||
DateFormat bool `json:"dateFormat"`
|
||||
ThemeColor string `json:"themeColor"`
|
||||
QuickDownload bool `json:"quickDownload"`
|
||||
DisableOnlyOfficeExt string `json:"disableOnlyOfficeExt"`
|
||||
DefaultScopes []users.SourceScope `json:"-"`
|
||||
StickySidebar bool `json:"stickySidebar"` // keep sidebar open when navigating
|
||||
DarkMode bool `json:"darkMode"` // should dark mode be enabled
|
||||
Locale string `json:"locale"` // language to use: eg. de, en, or fr
|
||||
ViewMode string `json:"viewMode"` // view mode to use: eg. normal, list, grid, or compact
|
||||
SingleClick bool `json:"singleClick"` // open directory on single click, also enables middle click to open in new tab
|
||||
ShowHidden bool `json:"showHidden"` // show hidden files in the UI. On windows this includes files starting with a dot and windows hidden files
|
||||
DateFormat bool `json:"dateFormat"` // when false, the date is relative, when true, the date is an exact timestamp
|
||||
GallerySize int `json:"gallerySize"` // 0-9 - the size of the gallery thumbnails
|
||||
ThemeColor string `json:"themeColor"` // theme color to use: eg. #ff0000, or var(--red), var(--purple), etc
|
||||
QuickDownload bool `json:"quickDownload"` // show icon to download in one click
|
||||
DisableOnlyOfficeExt string `json:"disableOnlyOfficeExt"` // comma separated list of file extensions to disable onlyoffice preview for
|
||||
DisableOfficePreviewExt string `json:"disableOfficePreviewExt"` // comma separated list of file extensions to disable office preview for
|
||||
LockPassword bool `json:"lockPassword"` // disable the user from changing their password
|
||||
DisableSettings bool `json:"disableSettings,omitempty"` // disable the user from viewing the settings page
|
||||
Preview users.Preview `json:"preview"`
|
||||
DefaultScopes []users.SourceScope `json:"-"`
|
||||
Permissions users.Permissions `json:"permissions"`
|
||||
LoginMethod string `json:"loginMethod,omitempty"` // login method to use: eg. password, proxy, oidc
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/gtsteffaniak/go-cache/cache"
|
||||
)
|
||||
|
||||
var (
|
||||
DiskUsageCache = cache.NewCache(30*time.Second, 24*time.Hour)
|
||||
RealPathCache = cache.NewCache(48*time.Hour, 72*time.Hour)
|
||||
SearchResultsCache = cache.NewCache(15*time.Second, 1*time.Hour)
|
||||
OnlyOfficeCache = cache.NewCache(48*time.Hour, 1*time.Hour)
|
||||
JwtCache = cache.NewCache(1*time.Hour, 72*time.Hour)
|
||||
)
|
||||
@@ -13,13 +13,13 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
func CheckErr(source string, err error) {
|
||||
if err != nil {
|
||||
logger.Fatal(fmt.Sprintf("%s: %v", source, err))
|
||||
logger.Fatalf("%s: %v", source, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ func PrintStructFields(v interface{}) {
|
||||
fieldValue = fieldValue[:100] + "..."
|
||||
}
|
||||
|
||||
logger.Debug(fmt.Sprintf("Field: %s, %s\n", fieldType.Name, fieldValue))
|
||||
logger.Debugf("Field: %s, %s\n", fieldType.Name, fieldValue)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
package bolt
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
storm "github.com/asdine/storm/v3"
|
||||
"github.com/asdine/storm/v3/q"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/errors"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/share"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
type shareBackend struct {
|
||||
@@ -63,7 +62,7 @@ func (s shareBackend) Gets(path, sourcePath string, id uint) ([]*share.Link, err
|
||||
if v[i].Expire < time.Now().Unix() && v[i].Expire != 0 {
|
||||
err = s.Delete(v[i].PasswordHash)
|
||||
if err != nil {
|
||||
logger.Error(fmt.Sprintf("expired share could not be deleted: %v", err.Error()))
|
||||
logger.Errorf("expired share could not be deleted: %v", err.Error())
|
||||
}
|
||||
} else {
|
||||
filteredList = append(filteredList, v[i])
|
||||
|
||||
@@ -11,10 +11,10 @@ import (
|
||||
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/auth"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/errors"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
type usersBackend struct {
|
||||
@@ -32,6 +32,7 @@ func (st usersBackend) GetBy(i interface{}) (user *users.User, err error) {
|
||||
arg = "ID"
|
||||
case int:
|
||||
val = uint(i)
|
||||
arg = "ID"
|
||||
case string:
|
||||
arg = "Username"
|
||||
val = i
|
||||
@@ -68,7 +69,11 @@ func (st usersBackend) Update(user *users.User, actorIsAdmin bool, fields ...str
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
passwordUser := existingUser.LoginMethod == users.LoginMethodPassword
|
||||
enforcedOtp := settings.Config.Auth.Methods.PasswordAuth.EnforcedOtp
|
||||
if passwordUser && enforcedOtp && !user.OtpEnabled {
|
||||
return errors.ErrNoTotpConfigured
|
||||
}
|
||||
fields, err = parseFields(user, fields, actorIsAdmin)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -121,6 +126,14 @@ func (st usersBackend) Update(user *users.User, actorIsAdmin bool, fields ...str
|
||||
|
||||
// Get the value to be stored
|
||||
val := fieldValue.Interface()
|
||||
if field == "OtpEnabled" {
|
||||
otpEnabled, _ := val.(bool)
|
||||
if otpEnabled {
|
||||
continue
|
||||
}
|
||||
field = "TOTPSecret" // if otp is disabled, we also want to clear the TOTPSecret
|
||||
val = "" // clear the TOTPSecret
|
||||
}
|
||||
// Update the database
|
||||
if err := st.db.UpdateField(existingUser, field, val); err != nil {
|
||||
return fmt.Errorf("failed to update user field: %s, error: %v", field, err)
|
||||
@@ -136,11 +149,11 @@ func (st usersBackend) Update(user *users.User, actorIsAdmin bool, fields ...str
|
||||
return nil
|
||||
}
|
||||
|
||||
func (st usersBackend) Save(user *users.User, changePass bool) error {
|
||||
func (st usersBackend) Save(user *users.User, changePass, disableScopeChange bool) error {
|
||||
if user.LoginMethod == "" {
|
||||
user.LoginMethod = users.LoginMethodPassword
|
||||
}
|
||||
logger.Debug(fmt.Sprintf("Saving user [%s] changepass: %v", user.Username, changePass))
|
||||
logger.Debugf("Saving user [%s] changepass: %v", user.Username, changePass)
|
||||
if user.LoginMethod == users.LoginMethodPassword && changePass {
|
||||
err := checkPassword(user.Password)
|
||||
if err != nil {
|
||||
@@ -159,13 +172,13 @@ func (st usersBackend) Save(user *users.User, changePass bool) error {
|
||||
return err
|
||||
}
|
||||
user.Scopes = adjustedScopes
|
||||
err = files.MakeUserDirs(user, false)
|
||||
err = files.MakeUserDirs(user, disableScopeChange)
|
||||
if err != nil {
|
||||
logger.Error(err.Error())
|
||||
}
|
||||
err = st.db.Save(user)
|
||||
if err == storm.ErrAlreadyExists {
|
||||
return errors.ErrExist
|
||||
return fmt.Errorf("user with provided username already exists")
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -220,9 +233,12 @@ func parseFields(user *users.User, fields []string, actorIsAdmin bool) ([]string
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
field := t.Field(i)
|
||||
// which=all can't update password
|
||||
if strings.ToLower(field.Name) != "password" && strings.ToLower(field.Name) != "id" && strings.ToLower(field.Name) != "username" {
|
||||
fields = append(fields, field.Name)
|
||||
switch strings.ToLower(field.Name) {
|
||||
case "id", "username", "loginmethod", "password", "apikeys", "totpenabled", "totpsecret", "totpnonce":
|
||||
// Skip these fields
|
||||
continue
|
||||
}
|
||||
fields = append(fields, field.Name)
|
||||
}
|
||||
}
|
||||
newfields := []string{}
|
||||
|
||||
@@ -4,16 +4,16 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
storm "github.com/asdine/storm/v3"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/auth"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/errors"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/share"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/storage/bolt"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
// Storage is a storage powered by a Backend which makes the necessary
|
||||
@@ -33,13 +33,16 @@ func InitializeDb(path string) (*Storage, bool, error) {
|
||||
panic(err)
|
||||
}
|
||||
db, err := storm.Open(path)
|
||||
|
||||
utils.CheckErr(fmt.Sprintf("storm.Open path %v", path), err)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "timeout") {
|
||||
logger.Fatal("the database is locked, please close all other instances of filebrowser before starting.")
|
||||
}
|
||||
logger.Fatalf("could not open database: %v", err)
|
||||
}
|
||||
authStore, userStore, shareStore, settingsStore, err := bolt.NewStorage(db)
|
||||
if err != nil {
|
||||
return nil, exists, err
|
||||
}
|
||||
|
||||
err = bolt.Save(db, "version", 2)
|
||||
if err != nil {
|
||||
return nil, exists, err
|
||||
@@ -97,25 +100,36 @@ func quickSetup(store *Storage) {
|
||||
}
|
||||
user.LockPassword = false
|
||||
user.Permissions = settings.AdminPerms()
|
||||
logger.Debug(fmt.Sprintf("Creating user as admin: %v %v", user.Username, user.Password))
|
||||
err = store.Users.Save(user, true)
|
||||
logger.Debugf("Creating user as admin: %v %v", user.Username, user.Password)
|
||||
err = store.Users.Save(user, true, true)
|
||||
utils.CheckErr("store.Users.Save", err)
|
||||
}
|
||||
|
||||
// create new user
|
||||
func CreateUser(userInfo users.User, asAdmin bool) error {
|
||||
newUser := &userInfo
|
||||
// must have username or password to create
|
||||
if userInfo.Username == "" || userInfo.Password == "" {
|
||||
return errors.ErrInvalidRequestParams
|
||||
if userInfo.LoginMethod == "password" {
|
||||
if userInfo.Password == "" {
|
||||
return fmt.Errorf("password is required to create a password login user")
|
||||
}
|
||||
} else {
|
||||
hashpass, err := users.HashPwd(userInfo.Username)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
userInfo.Password = hashpass
|
||||
}
|
||||
logger.Debug(fmt.Sprintf("Creating user: %v %v", userInfo.Username, userInfo.Scopes))
|
||||
// must have username or password to create
|
||||
if userInfo.Username == "" {
|
||||
return fmt.Errorf("username is required to create a user")
|
||||
}
|
||||
logger.Debugf("Creating user: %v %v", userInfo.Username, userInfo.Scopes)
|
||||
settings.ApplyUserDefaults(newUser)
|
||||
if asAdmin {
|
||||
userInfo.Permissions = settings.AdminPerms()
|
||||
}
|
||||
// create new home directories
|
||||
err := store.Users.Save(newUser, true)
|
||||
err := store.Users.Save(newUser, true, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
type StorageBackend interface {
|
||||
GetBy(interface{}) (*User, error)
|
||||
Gets() ([]*User, error)
|
||||
Save(u *User, changePass bool) error
|
||||
Save(u *User, changePass bool, disableScopeChange bool) error
|
||||
Update(u *User, adminActor bool, fields ...string) error
|
||||
DeleteByID(uint) error
|
||||
DeleteByUsername(string) error
|
||||
@@ -22,7 +22,7 @@ type Store interface {
|
||||
Get(id interface{}) (user *User, err error)
|
||||
Gets() ([]*User, error)
|
||||
Update(user *User, adminActor bool, fields ...string) error
|
||||
Save(user *User, changePass bool) error
|
||||
Save(user *User, changePass bool, disableScopeChange bool) error
|
||||
Delete(id interface{}) error
|
||||
LastUpdate(id uint) int64
|
||||
AddApiKey(username uint, name string, key AuthToken) error
|
||||
@@ -114,8 +114,8 @@ func (s *Storage) DeleteApiKey(userID uint, name string) error {
|
||||
}
|
||||
|
||||
// Save saves the user in a storage.
|
||||
func (s *Storage) Save(user *User, changePass bool) error {
|
||||
return s.back.Save(user, changePass)
|
||||
func (s *Storage) Save(user *User, changePass, disableScopeChange bool) error {
|
||||
return s.back.Save(user, changePass, disableScopeChange)
|
||||
}
|
||||
|
||||
// Delete allows you to delete a user by its name or username. The provided
|
||||
|
||||
@@ -40,12 +40,13 @@ type Sorting struct {
|
||||
Asc bool `json:"asc"`
|
||||
}
|
||||
|
||||
type PreviewOptions struct {
|
||||
HighQuality bool `json:"highQuality"`
|
||||
Image bool `json:"image"`
|
||||
Video bool `json:"video"`
|
||||
Office bool `json:"office"`
|
||||
PopUp bool `json:"popup"`
|
||||
type Preview struct {
|
||||
HighQuality bool `json:"highQuality"` // generate high quality preview images
|
||||
Image bool `json:"image"` // show real image as icon instead of generic photo icon
|
||||
Video bool `json:"video"` // show preview image for video files
|
||||
MotionVideoPreview bool `json:"motionVideoPreview"` // show multiple frames for videos in preview when hovering
|
||||
Office bool `json:"office"` // show preview image for office files
|
||||
PopUp bool `json:"popup"` // show larger popup preview when hovering
|
||||
}
|
||||
|
||||
// User describes a user.
|
||||
@@ -59,7 +60,10 @@ type User struct {
|
||||
LockPassword bool `json:"lockPassword"`
|
||||
Permissions Permissions `json:"permissions"`
|
||||
ApiKeys map[string]AuthToken `json:"apiKeys,omitempty"`
|
||||
TOTPSecret string `json:"totpSecret,omitempty"`
|
||||
TOTPNonce string `json:"totpNonce,omitempty"`
|
||||
LoginMethod LoginMethod `json:"loginMethod"`
|
||||
OtpEnabled bool `json:"otpEnabled"` // true if TOTP is enabled, false otherwise
|
||||
// legacy for migration purposes... og filebrowser has perm attribute
|
||||
Perm Permissions `json:"perm,omitzero"`
|
||||
}
|
||||
@@ -69,21 +73,23 @@ type SourceScope struct {
|
||||
Scope string `json:"scope"`
|
||||
}
|
||||
|
||||
// json tags must match variable name with smaller case first letter
|
||||
type NonAdminEditable struct {
|
||||
Preview PreviewOptions `json:"preview"`
|
||||
StickySidebar bool `json:"stickySidebar"`
|
||||
DarkMode bool `json:"darkMode"`
|
||||
Password string `json:"password,omitempty"`
|
||||
Locale string `json:"locale"`
|
||||
ViewMode string `json:"viewMode"`
|
||||
SingleClick bool `json:"singleClick"`
|
||||
Sorting Sorting `json:"sorting"`
|
||||
ShowHidden bool `json:"showHidden"`
|
||||
DateFormat bool `json:"dateFormat"`
|
||||
GallerySize int `json:"gallerySize"`
|
||||
ThemeColor string `json:"themeColor"`
|
||||
QuickDownload bool `json:"quickDownload"`
|
||||
DisableOnlyOfficeExt string `json:"disableOnlyOfficeExt"`
|
||||
Preview Preview `json:"preview"`
|
||||
StickySidebar bool `json:"stickySidebar"` // keep sidebar open when navigating
|
||||
DarkMode bool `json:"darkMode"` // should dark mode be enabled
|
||||
Password string `json:"password,omitempty"`
|
||||
Locale string `json:"locale"` // language to use: eg. de, en, or fr
|
||||
ViewMode string `json:"viewMode"` // view mode to use: eg. normal, list, grid, or compact
|
||||
SingleClick bool `json:"singleClick"` // open directory on single click, also enables middle click to open in new tab
|
||||
Sorting Sorting `json:"sorting"`
|
||||
ShowHidden bool `json:"showHidden"` // show hidden files in the UI. On windows this includes files starting with a dot and windows hidden files
|
||||
DateFormat bool `json:"dateFormat"` // when false, the date is relative, when true, the date is an exact timestamp
|
||||
GallerySize int `json:"gallerySize"` // 0-9 - the size of the gallery thumbnails
|
||||
ThemeColor string `json:"themeColor"` // theme color to use: eg. #ff0000, or var(--red), var(--purple), etc
|
||||
QuickDownload bool `json:"quickDownload"` // show icon to download in one click
|
||||
DisableOnlyOfficeExt string `json:"disableOnlyOfficeExt"` // comma separated list of file extensions to disable onlyoffice preview for
|
||||
DisableOfficePreviewExt string `json:"disableOfficePreviewExt"` // comma separated list of file extensions to disable office preview for
|
||||
}
|
||||
|
||||
var PublicUser = User{
|
||||
|
||||
+14
-16
@@ -1,15 +1,20 @@
|
||||
module github.com/gtsteffaniak/filebrowser/backend
|
||||
|
||||
go 1.24.0
|
||||
go 1.24.2
|
||||
|
||||
require (
|
||||
github.com/asdine/storm/v3 v3.2.1
|
||||
github.com/disintegration/imaging v1.6.2
|
||||
github.com/coreos/go-oidc/v3 v3.14.1
|
||||
github.com/dsoprea/go-exif/v3 v3.0.1
|
||||
github.com/gen2brain/go-fitz v1.24.14
|
||||
github.com/go-playground/validator/v10 v10.26.0
|
||||
github.com/goccy/go-yaml v1.17.1
|
||||
github.com/goccy/go-yaml v1.18.0
|
||||
github.com/golang-jwt/jwt/v4 v4.5.2
|
||||
github.com/google/go-cmp v0.7.0
|
||||
github.com/gtsteffaniak/go-cache v0.0.0-20250521142451-edc77dfcb063
|
||||
github.com/gtsteffaniak/go-logger v0.1.2
|
||||
github.com/kovidgoyal/imaging v1.6.4
|
||||
github.com/pquerna/otp v1.5.0
|
||||
github.com/shirou/gopsutil/v3 v3.24.5
|
||||
github.com/spf13/afero v1.14.0
|
||||
github.com/stretchr/testify v1.10.0
|
||||
@@ -17,6 +22,7 @@ require (
|
||||
github.com/swaggo/swag v1.16.4
|
||||
golang.org/x/crypto v0.38.0
|
||||
golang.org/x/image v0.27.0
|
||||
golang.org/x/oauth2 v0.30.0
|
||||
golang.org/x/sys v0.33.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
@@ -47,6 +53,7 @@ require (
|
||||
github.com/bkielbasa/cyclop v1.2.3 // indirect
|
||||
github.com/blizzy78/varnamelen v0.8.0 // indirect
|
||||
github.com/bombsimon/wsl/v4 v4.5.0 // indirect
|
||||
github.com/boombuler/barcode v1.0.2 // indirect
|
||||
github.com/breml/bidichk v0.3.2 // indirect
|
||||
github.com/breml/errchkjson v0.4.0 // indirect
|
||||
github.com/butuzov/ireturn v0.3.1 // indirect
|
||||
@@ -61,10 +68,10 @@ require (
|
||||
github.com/curioswitch/go-reassign v0.3.0 // indirect
|
||||
github.com/daixiang0/gci v0.13.5 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect
|
||||
github.com/denis-tingaikin/go-header v0.5.0 // indirect
|
||||
github.com/dsoprea/go-logging v0.0.0-20200710184922-b02d349568dd // indirect
|
||||
github.com/dsoprea/go-utility/v2 v2.0.0-20221003172846-a3e1774ef349 // indirect
|
||||
github.com/ebitengine/purego v0.8.4 // indirect
|
||||
github.com/ettle/strcase v0.2.0 // indirect
|
||||
github.com/fatih/color v1.18.0 // indirect
|
||||
github.com/fatih/structtag v1.2.0 // indirect
|
||||
@@ -75,6 +82,7 @@ require (
|
||||
github.com/ghostiam/protogetter v0.3.9 // indirect
|
||||
github.com/go-critic/go-critic v0.12.0 // indirect
|
||||
github.com/go-errors/errors v1.5.1 // indirect
|
||||
github.com/go-jose/go-jose/v4 v4.1.0 // indirect
|
||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.21.1 // indirect
|
||||
github.com/go-openapi/jsonreference v0.21.0 // indirect
|
||||
@@ -92,9 +100,8 @@ require (
|
||||
github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
|
||||
github.com/go-xmlfmt/xmlfmt v1.1.3 // indirect
|
||||
github.com/gobwas/glob v0.2.3 // indirect
|
||||
github.com/goccy/go-json v0.10.3 // indirect
|
||||
github.com/gofrs/flock v0.12.1 // indirect
|
||||
github.com/golang/geo v0.0.0-20250505201543-5b58c72585db // indirect
|
||||
github.com/golang/geo v0.0.0-20250602202553-92e1c6cfbc31 // indirect
|
||||
github.com/golang/protobuf v1.5.3 // indirect
|
||||
github.com/golangci/dupl v0.0.0-20250308024227-f665c8d69b32 // indirect
|
||||
github.com/golangci/go-printf-func-name v0.1.0 // indirect
|
||||
@@ -120,6 +127,7 @@ require (
|
||||
github.com/jjti/go-spancheck v0.6.4 // indirect
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
github.com/julz/importas v0.2.0 // indirect
|
||||
github.com/jupiterrider/ffi v0.4.1 // indirect
|
||||
github.com/karamaru-alpha/copyloopvar v1.2.1 // indirect
|
||||
github.com/kisielk/errcheck v1.9.0 // indirect
|
||||
github.com/kkHAIKE/contextcheck v1.1.6 // indirect
|
||||
@@ -133,14 +141,6 @@ require (
|
||||
github.com/ldez/usetesting v0.4.2 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/leonklingele/grouper v1.1.2 // indirect
|
||||
github.com/lestrrat-go/backoff/v2 v2.0.8 // indirect
|
||||
github.com/lestrrat-go/blackmagic v1.0.3 // indirect
|
||||
github.com/lestrrat-go/httpcc v1.0.1 // indirect
|
||||
github.com/lestrrat-go/httprc/v3 v3.0.0-beta2 // indirect
|
||||
github.com/lestrrat-go/iter v1.0.2 // indirect
|
||||
github.com/lestrrat-go/jwx v1.2.31 // indirect
|
||||
github.com/lestrrat-go/jwx/v3 v3.0.1 // indirect
|
||||
github.com/lestrrat-go/option v1.0.1 // indirect
|
||||
github.com/macabu/inamedparam v0.1.3 // indirect
|
||||
github.com/magiconair/properties v1.8.6 // indirect
|
||||
github.com/mailru/easyjson v0.9.0 // indirect
|
||||
@@ -162,7 +162,6 @@ require (
|
||||
github.com/olekukonko/tablewriter v0.0.5 // indirect
|
||||
github.com/pelletier/go-toml v1.9.5 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/polyfloyd/go-errorlint v1.7.1 // indirect
|
||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
|
||||
@@ -186,7 +185,6 @@ require (
|
||||
github.com/sashamelentyev/interfacebloat v1.1.0 // indirect
|
||||
github.com/sashamelentyev/usestdlibvars v1.28.0 // indirect
|
||||
github.com/securego/gosec/v2 v2.22.2 // indirect
|
||||
github.com/segmentio/asm v1.2.0 // indirect
|
||||
github.com/sirupsen/logrus v1.9.3 // indirect
|
||||
github.com/sivchari/containedctx v1.0.3 // indirect
|
||||
github.com/sivchari/tenv v1.12.1 // indirect
|
||||
|
||||
+29
-32
@@ -102,6 +102,9 @@ github.com/blizzy78/varnamelen v0.8.0 h1:oqSblyuQvFsW1hbBHh1zfwrKe3kcSj0rnXkKzsQ
|
||||
github.com/blizzy78/varnamelen v0.8.0/go.mod h1:V9TzQZ4fLJ1DSrjVDfl89H7aMnTvKkApdHeyESmyR7k=
|
||||
github.com/bombsimon/wsl/v4 v4.5.0 h1:iZRsEvDdyhd2La0FVi5k6tYehpOR/R7qIUjmKk7N74A=
|
||||
github.com/bombsimon/wsl/v4 v4.5.0/go.mod h1:NOQ3aLF4nD7N5YPXMruR6ZXDOAqLoM0GEpLwTdvmOSc=
|
||||
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
|
||||
github.com/boombuler/barcode v1.0.2 h1:79yrbttoZrLGkL/oOI8hBrUKucwOL0oOjUgEguGMcJ4=
|
||||
github.com/boombuler/barcode v1.0.2/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
|
||||
github.com/breml/bidichk v0.3.2 h1:xV4flJ9V5xWTqxL+/PMFF6dtJPvZLPsyixAoPe8BGJs=
|
||||
github.com/breml/bidichk v0.3.2/go.mod h1:VzFLBxuYtT23z5+iVkamXO386OB+/sVwZOpIj6zXGos=
|
||||
github.com/breml/errchkjson v0.4.0 h1:gftf6uWZMtIa/Is3XJgibewBm2ksAQSY/kABDNFTAdk=
|
||||
@@ -130,6 +133,8 @@ github.com/ckaznocha/intrange v0.3.0 h1:VqnxtK32pxgkhJgYQEeOArVidIPg+ahLP7WBOXZd
|
||||
github.com/ckaznocha/intrange v0.3.0/go.mod h1:+I/o2d2A1FBHgGELbGxzIcyd3/9l9DuwjM8FsbSS3Lo=
|
||||
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
||||
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
|
||||
github.com/coreos/go-oidc/v3 v3.14.1 h1:9ePWwfdwC4QKRlCXsJGou56adA/owXczOzwKdOumLqk=
|
||||
github.com/coreos/go-oidc/v3 v3.14.1/go.mod h1:HaZ3szPaZ0e4r6ebqvsLWlk2Tn+aejfmrfah6hnSYEU=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.6 h1:XJtiaUW6dEEqVuZiMTn1ldk455QWwEIsMIJlo5vtkx0=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||
@@ -140,12 +145,8 @@ github.com/daixiang0/gci v0.13.5/go.mod h1:12etP2OniiIdP4q+kjUGrC/rUagga7ODbqsom
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 h1:NMZiJj8QnKe1LgsbDayM4UoHwbvwDRwnI3hwNaAHRnc=
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40=
|
||||
github.com/denis-tingaikin/go-header v0.5.0 h1:SRdnP5ZKvcO9KKRP1KJrhFR3RrlGuD+42t4429eC9k8=
|
||||
github.com/denis-tingaikin/go-header v0.5.0/go.mod h1:mMenU5bWrok6Wl2UsZjy+1okegmwQ3UgWl4V1D8gjlY=
|
||||
github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
|
||||
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
|
||||
github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
|
||||
github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
|
||||
github.com/dsoprea/go-exif/v2 v2.0.0-20200321225314-640175a69fe4/go.mod h1:Lm2lMM2zx8p4a34ZemkaUV95AnMl4ZvLbCUbwOvLC2E=
|
||||
@@ -165,6 +166,8 @@ github.com/dsoprea/go-utility/v2 v2.0.0-20221003142440-7a1927d49d9d/go.mod h1:LV
|
||||
github.com/dsoprea/go-utility/v2 v2.0.0-20221003160719-7bc88537c05e/go.mod h1:VZ7cB0pTjm1ADBWhJUOHESu4ZYy9JN+ZPqjfiW09EPU=
|
||||
github.com/dsoprea/go-utility/v2 v2.0.0-20221003172846-a3e1774ef349 h1:DilThiXje0z+3UQ5YjYiSRRzVdtamFpvBQXKwMglWqw=
|
||||
github.com/dsoprea/go-utility/v2 v2.0.0-20221003172846-a3e1774ef349/go.mod h1:4GC5sXji84i/p+irqghpPFZBF8tRN/Q7+700G0/DLe8=
|
||||
github.com/ebitengine/purego v0.8.4 h1:CF7LEKg5FFOsASUj0+QwaXf8Ht6TlFxg09+S9wz0omw=
|
||||
github.com/ebitengine/purego v0.8.4/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
|
||||
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
|
||||
@@ -185,6 +188,8 @@ github.com/fzipp/gocyclo v0.6.0 h1:lsblElZG7d3ALtGMx9fmxeTKZaLLpU8mET09yN4BBLo=
|
||||
github.com/fzipp/gocyclo v0.6.0/go.mod h1:rXPyn8fnlpa0R2csP/31uerbiVBugk5whMdlyaLkLoA=
|
||||
github.com/gabriel-vasile/mimetype v1.4.9 h1:5k+WDwEsD9eTLL8Tz3L0VnmVh9QxGjRmjBvAG7U/oYY=
|
||||
github.com/gabriel-vasile/mimetype v1.4.9/go.mod h1:WnSQhFKJuBlRyLiKohA/2DtIlPFAbguNaG7QCHcyGok=
|
||||
github.com/gen2brain/go-fitz v1.24.14 h1:09weRkjVtLYNGo7l0J7DyOwBExbwi8SJ9h8YPhw9WEo=
|
||||
github.com/gen2brain/go-fitz v1.24.14/go.mod h1:0KaZeQgASc20Yp5R/pFzyy7SmP01XcoHKNF842U2/S4=
|
||||
github.com/ghostiam/protogetter v0.3.9 h1:j+zlLLWzqLay22Cz/aYwTHKQ88GE2DQ6GkWSYFOI4lQ=
|
||||
github.com/ghostiam/protogetter v0.3.9/go.mod h1:WZ0nw9pfzsgxuRsPOFQomgDVSWtDLJRfQJEhsGbmQMA=
|
||||
github.com/go-critic/go-critic v0.12.0 h1:iLosHZuye812wnkEz1Xu3aBwn5ocCPfc9yqmFG9pa6w=
|
||||
@@ -198,6 +203,8 @@ github.com/go-errors/errors v1.5.1/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3Bop
|
||||
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
|
||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
||||
github.com/go-jose/go-jose/v4 v4.1.0 h1:cYSYxd3pw5zd2FSXk2vGdn9igQU2PS8MuxrCOCl0FdY=
|
||||
github.com/go-jose/go-jose/v4 v4.1.0/go.mod h1:GG/vqmYm3Von2nYiB2vGTXzdoNKE5tix5tuc6iAd+sw=
|
||||
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
||||
github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
||||
github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY=
|
||||
@@ -255,10 +262,8 @@ github.com/go-xmlfmt/xmlfmt v1.1.3 h1:t8Ey3Uy7jDSEisW2K3somuMKIpzktkWptA0iFCnRUW
|
||||
github.com/go-xmlfmt/xmlfmt v1.1.3/go.mod h1:aUCEOzzezBEjDBbFBoSiya/gduyIiWYRP6CnSFIV8AM=
|
||||
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
|
||||
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
|
||||
github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA=
|
||||
github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/goccy/go-yaml v1.17.1 h1:LI34wktB2xEE3ONG/2Ar54+/HJVBriAGJ55PHls4YuY=
|
||||
github.com/goccy/go-yaml v1.17.1/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||
github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
|
||||
github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||
github.com/gofrs/flock v0.12.1 h1:MTLVXXHf8ekldpJk3AKicLij9MdwOWkZ+a/jHHZby9E=
|
||||
github.com/gofrs/flock v0.12.1/go.mod h1:9zxTsyu5xtJ9DK+1tFZyibEV7y3uwDxPPfbxeeHCoD0=
|
||||
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
|
||||
@@ -267,8 +272,10 @@ github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w
|
||||
github.com/golang/geo v0.0.0-20190916061304-5b978397cfec/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI=
|
||||
github.com/golang/geo v0.0.0-20200319012246-673a6f80352d/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI=
|
||||
github.com/golang/geo v0.0.0-20210211234256-740aa86cb551/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI=
|
||||
github.com/golang/geo v0.0.0-20250505201543-5b58c72585db h1:juWRoz5Y+/j2ffgMV0yPnZD5sd1EkeJOsrnMMyLIFrM=
|
||||
github.com/golang/geo v0.0.0-20250505201543-5b58c72585db/go.mod h1:Vaw7L5b+xa3Rj4/pRtrQkymn3lSBRB/NAEdbF9YEVLA=
|
||||
github.com/golang/geo v0.0.0-20250516193853-92f93c4cb289 h1:HeOFbnyPys/vx/t+d4fwZM782mnjRVtbjxVkDittTUs=
|
||||
github.com/golang/geo v0.0.0-20250516193853-92f93c4cb289/go.mod h1:Vaw7L5b+xa3Rj4/pRtrQkymn3lSBRB/NAEdbF9YEVLA=
|
||||
github.com/golang/geo v0.0.0-20250602202553-92e1c6cfbc31 h1:E1wdqK72/SVuxkxQ2DSE7YZEmcUZvExysw58zmkLKik=
|
||||
github.com/golang/geo v0.0.0-20250602202553-92e1c6cfbc31/go.mod h1:Vaw7L5b+xa3Rj4/pRtrQkymn3lSBRB/NAEdbF9YEVLA=
|
||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||
github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||
@@ -362,6 +369,10 @@ github.com/gostaticanalysis/nilerr v0.1.1/go.mod h1:wZYb6YI5YAxxq0i1+VJbY0s2YONW
|
||||
github.com/gostaticanalysis/testutil v0.3.1-0.20210208050101-bfb5c8eec0e4/go.mod h1:D+FIZ+7OahH3ePw/izIEeH5I06eKs1IKI4Xr64/Am3M=
|
||||
github.com/gostaticanalysis/testutil v0.5.0 h1:Dq4wT1DdTwTGCQQv3rl3IvD5Ld0E6HiY+3Zh0sUGqw8=
|
||||
github.com/gostaticanalysis/testutil v0.5.0/go.mod h1:OLQSbuM6zw2EvCcXTz1lVq5unyoNft372msDY0nY5Hs=
|
||||
github.com/gtsteffaniak/go-cache v0.0.0-20250521142451-edc77dfcb063 h1:CoLbeqTmM7348kulYBXYN82Bowx7Iu9PHe0shqQ2QR8=
|
||||
github.com/gtsteffaniak/go-cache v0.0.0-20250521142451-edc77dfcb063/go.mod h1:rHUZvf4huhMX/bnNK4/oQ3sNAE2fYC2jFpAWZiBPWac=
|
||||
github.com/gtsteffaniak/go-logger v0.1.2 h1:0g6UxxNwU+Q+7IVRw+Yn7AuYsIK0ukiTgbzjTLm+Uy4=
|
||||
github.com/gtsteffaniak/go-logger v0.1.2/go.mod h1:U3ZkdAclcxXNMvoQLq+zDkqcTmdqhX3hTf+6AuTo6v0=
|
||||
github.com/hashicorp/go-immutable-radix/v2 v2.1.0 h1:CUW5RYIcysz+D3B+l1mDeXrQ7fUvGGCwJfdASSzbrfo=
|
||||
github.com/hashicorp/go-immutable-radix/v2 v2.1.0/go.mod h1:hgdqLXA4f6NIjRVisM1TJ9aOJVNRqKZj+xDGF6m7PBw=
|
||||
github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8=
|
||||
@@ -401,6 +412,8 @@ github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7V
|
||||
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
|
||||
github.com/julz/importas v0.2.0 h1:y+MJN/UdL63QbFJHws9BVC5RpA2iq0kpjrFajTGivjQ=
|
||||
github.com/julz/importas v0.2.0/go.mod h1:pThlt589EnCYtMnmhmRYY/qn9lCf/frPOK+WMx3xiJY=
|
||||
github.com/jupiterrider/ffi v0.4.1 h1:Obg+xpuA+rRkRTEN7xu3IagjNDMO8fRUhOPpLEztPYI=
|
||||
github.com/jupiterrider/ffi v0.4.1/go.mod h1:Ba3hjU7Sz2+TO8HupjZwGssVnzo7RG3xF77byUBueB4=
|
||||
github.com/karamaru-alpha/copyloopvar v1.2.1 h1:wmZaZYIjnJ0b5UoKDjUHrikcV0zuPyyxI4SVplLd2CI=
|
||||
github.com/karamaru-alpha/copyloopvar v1.2.1/go.mod h1:nFmMlFNlClC2BPvNaHMdkirmTJxVCY0lhxBtlfOypMM=
|
||||
github.com/kisielk/errcheck v1.9.0 h1:9xt1zI9EBfcYBvdU1nVrzMzzUPUtPKs9bVSIM3TAb3M=
|
||||
@@ -410,6 +423,8 @@ github.com/kkHAIKE/contextcheck v1.1.6 h1:7HIyRcnyzxL9Lz06NGhiKvenXq7Zw6Q0UQu/tt
|
||||
github.com/kkHAIKE/contextcheck v1.1.6/go.mod h1:3dDbMRNBFaq8HFXWC1JyvDSPm43CmE6IuHam8Wr0rkg=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/kovidgoyal/imaging v1.6.4 h1:K0idhRPXnRrJBKnBYcTfI1HTWSNDeAn7hYDvf9I0dCk=
|
||||
github.com/kovidgoyal/imaging v1.6.4/go.mod h1:bEIgsaZmXlvFfkv/CUxr9rJook6AQkJnpB5EPosRfRY=
|
||||
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
@@ -438,25 +453,6 @@ github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/leonklingele/grouper v1.1.2 h1:o1ARBDLOmmasUaNDesWqWCIFH3u7hoFlM84YrjT3mIY=
|
||||
github.com/leonklingele/grouper v1.1.2/go.mod h1:6D0M/HVkhs2yRKRFZUoGjeDy7EZTfFBE9gl4kjmIGkA=
|
||||
github.com/lestrrat-go/backoff/v2 v2.0.8 h1:oNb5E5isby2kiro9AgdHLv5N5tint1AnDVVf2E2un5A=
|
||||
github.com/lestrrat-go/backoff/v2 v2.0.8/go.mod h1:rHP/q/r9aT27n24JQLa7JhSQZCKBBOiM/uP402WwN8Y=
|
||||
github.com/lestrrat-go/blackmagic v1.0.2 h1:Cg2gVSc9h7sz9NOByczrbUvLopQmXrfFx//N+AkAr5k=
|
||||
github.com/lestrrat-go/blackmagic v1.0.2/go.mod h1:UrEqBzIR2U6CnzVyUtfM6oZNMt/7O7Vohk2J0OGSAtU=
|
||||
github.com/lestrrat-go/blackmagic v1.0.3 h1:94HXkVLxkZO9vJI/w2u1T0DAoprShFd13xtnSINtDWs=
|
||||
github.com/lestrrat-go/blackmagic v1.0.3/go.mod h1:6AWFyKNNj0zEXQYfTMPfZrAXUWUfTIZ5ECEUEJaijtw=
|
||||
github.com/lestrrat-go/httpcc v1.0.1 h1:ydWCStUeJLkpYyjLDHihupbn2tYmZ7m22BGkcvZZrIE=
|
||||
github.com/lestrrat-go/httpcc v1.0.1/go.mod h1:qiltp3Mt56+55GPVCbTdM9MlqhvzyuL6W/NMDA8vA5E=
|
||||
github.com/lestrrat-go/httprc/v3 v3.0.0-beta2 h1:SDxjGoH7qj0nBXVrcrxX8eD94wEnjR+EEuqqmeqQYlY=
|
||||
github.com/lestrrat-go/httprc/v3 v3.0.0-beta2/go.mod h1:Nwo81sMxE0DcvTB+rJyynNhv/DUu2yZErV7sscw9pHE=
|
||||
github.com/lestrrat-go/iter v1.0.2 h1:gMXo1q4c2pHmC3dn8LzRhJfP1ceCbgSiT9lUydIzltI=
|
||||
github.com/lestrrat-go/iter v1.0.2/go.mod h1:Momfcq3AnRlRjI5b5O8/G5/BvpzrhoFTZcn06fEOPt4=
|
||||
github.com/lestrrat-go/jwx v1.2.31 h1:/OM9oNl/fzyldpv5HKZ9m7bTywa7COUfg8gujd9nJ54=
|
||||
github.com/lestrrat-go/jwx v1.2.31/go.mod h1:eQJKoRwWcLg4PfD5CFA5gIZGxhPgoPYq9pZISdxLf0c=
|
||||
github.com/lestrrat-go/jwx/v3 v3.0.1 h1:fH3T748FCMbXoF9UXXNS9i0q6PpYyJZK/rKSbkt2guY=
|
||||
github.com/lestrrat-go/jwx/v3 v3.0.1/go.mod h1:XP2WqxMOSzHSyf3pfibCcfsLqbomxakAnNqiuaH8nwo=
|
||||
github.com/lestrrat-go/option v1.0.0/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I=
|
||||
github.com/lestrrat-go/option v1.0.1 h1:oAzP2fvZGQKWkvHa1/SAcFolBEca1oN+mQ7eooNBEYU=
|
||||
github.com/lestrrat-go/option v1.0.1/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I=
|
||||
github.com/macabu/inamedparam v0.1.3 h1:2tk/phHkMlEL/1GNe/Yf6kkR/hkcUdAEY3L0hjYV1Mk=
|
||||
github.com/macabu/inamedparam v0.1.3/go.mod h1:93FLICAIk/quk7eaPPQvbzihUdn/QkGDwIZEoLtpH6I=
|
||||
github.com/magiconair/properties v1.8.6 h1:5ibWZ6iY0NctNGWo87LalDlEZ6R41TqbbDamhfG/Qzo=
|
||||
@@ -530,6 +526,8 @@ github.com/polyfloyd/go-errorlint v1.7.1 h1:RyLVXIbosq1gBdk/pChWA8zWYLsq9UEw7a1L
|
||||
github.com/polyfloyd/go-errorlint v1.7.1/go.mod h1:aXjNb1x2TNhoLsk26iv1yl7a+zTnXPhwEMtEXukiLR8=
|
||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=
|
||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
|
||||
github.com/pquerna/otp v1.5.0 h1:NMMR+WrmaqXU4EzdGJEE1aUUI0AMRzsp96fFFWNPwxs=
|
||||
github.com/pquerna/otp v1.5.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg=
|
||||
github.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4g=
|
||||
github.com/prashantv/gostub v1.1.0/go.mod h1:A5zLQHz7ieHGG7is6LLXLz7I8+3LZzsrV0P1IAHhP5U=
|
||||
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
|
||||
@@ -589,8 +587,6 @@ github.com/sashamelentyev/usestdlibvars v1.28.0 h1:jZnudE2zKCtYlGzLVreNp5pmCdOxX
|
||||
github.com/sashamelentyev/usestdlibvars v1.28.0/go.mod h1:9nl0jgOfHKWNFS43Ojw0i7aRoS4j6EBye3YBhmAIRF8=
|
||||
github.com/securego/gosec/v2 v2.22.2 h1:IXbuI7cJninj0nRpZSLCUlotsj8jGusohfONMrHoF6g=
|
||||
github.com/securego/gosec/v2 v2.22.2/go.mod h1:UEBGA+dSKb+VqM6TdehR7lnQtIIMorYJ4/9CW1KVQBE=
|
||||
github.com/segmentio/asm v1.2.0 h1:9BQrFxC+YOHJlTlHGkTrFWf59nbL3XnCoFLTwDCI7ys=
|
||||
github.com/segmentio/asm v1.2.0/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
|
||||
github.com/shirou/gopsutil/v3 v3.24.5 h1:i0t8kL+kQTvpAYToeuiVk3TgDeKOFioZO3Ztz/iZ9pI=
|
||||
github.com/shirou/gopsutil/v3 v3.24.5/go.mod h1:bsoOS1aStSs9ErQ1WWfxllSeS1K5D+U30r2NfcubMVk=
|
||||
github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk=
|
||||
@@ -636,7 +632,6 @@ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXf
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
@@ -835,6 +830,8 @@ golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4Iltr
|
||||
golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
|
||||
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
|
||||
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
|
||||
+59
-427
@@ -4,7 +4,6 @@ import (
|
||||
"encoding/json"
|
||||
libError "errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
@@ -12,17 +11,15 @@ import (
|
||||
|
||||
jwt "github.com/golang-jwt/jwt/v4"
|
||||
"github.com/golang-jwt/jwt/v4/request"
|
||||
"github.com/lestrrat-go/jwx/v3/jwk"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/cache"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/errors"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/share"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/storage"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
// first checks for cookie
|
||||
@@ -79,16 +76,9 @@ func setupProxyUser(r *http.Request, data *requestContext, proxyUser string) (*u
|
||||
return nil, err
|
||||
}
|
||||
if config.Auth.Methods.ProxyAuth.CreateUser {
|
||||
hashpass, err := users.HashPwd(proxyUser)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = storage.CreateUser(users.User{
|
||||
LoginMethod: users.LoginMethodProxy,
|
||||
Username: proxyUser,
|
||||
NonAdminEditable: users.NonAdminEditable{
|
||||
Password: hashpass, // hashed password that can't actually be used
|
||||
},
|
||||
}, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -102,7 +92,7 @@ func setupProxyUser(r *http.Request, data *requestContext, proxyUser string) (*u
|
||||
}
|
||||
}
|
||||
if data.user.LoginMethod != users.LoginMethodProxy {
|
||||
logger.Warning(fmt.Sprintf("user %s is not allowed to login with proxy authentication, bypassing and updating login method", data.user.Username))
|
||||
logger.Warningf("user %s is not allowed to login with proxy authentication, bypassing and updating login method", data.user.Username)
|
||||
data.user.LoginMethod = users.LoginMethodProxy
|
||||
// Perform the user update
|
||||
err := store.Users.Update(data.user, true, "LoginMethod")
|
||||
@@ -124,55 +114,50 @@ func setupProxyUser(r *http.Request, data *requestContext, proxyUser string) (*u
|
||||
// @Failure 403 {object} map[string]string "Forbidden - authentication failed"
|
||||
// @Failure 500 {object} map[string]string "Internal server error"
|
||||
// @Router /api/login [post]
|
||||
func loginHandler(w http.ResponseWriter, r *http.Request) {
|
||||
func loginHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
|
||||
passwordUser := d.user.LoginMethod == users.LoginMethodPassword
|
||||
enforcedOtp := config.Auth.Methods.PasswordAuth.EnforcedOtp
|
||||
missingOtp := d.user.TOTPSecret == ""
|
||||
if passwordUser && enforcedOtp && missingOtp {
|
||||
return http.StatusForbidden, errors.ErrNoTotpConfigured
|
||||
}
|
||||
return printToken(w, r, d.user) // Pass the data object
|
||||
}
|
||||
|
||||
// logoutHandler handles user logout, specifically used for OIDC or proxy users.
|
||||
// @Summary User Logout
|
||||
// @Description logs a user out of the application.
|
||||
// @Tags Auth
|
||||
// @Success 302 {string} string "Redirect to redirect URL if configured in oidc config."
|
||||
// @Router /api/auth/logout [get]
|
||||
func logoutHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
|
||||
origin := r.Header.Get("Origin")
|
||||
if origin == "" {
|
||||
origin = fmt.Sprintf("%s://%s", getScheme(r), r.Host)
|
||||
}
|
||||
logoutUrl := fmt.Sprintf("%s/login", origin)
|
||||
proxyRedirectUrl := config.Auth.Methods.ProxyAuth.LogoutRedirectUrl
|
||||
oidcRedirectUrl := settings.Config.Auth.Methods.OidcAuth.LogoutRedirectUrl
|
||||
proxyUser := r.Header.Get(config.Auth.Methods.ProxyAuth.Header)
|
||||
|
||||
if config.Auth.Methods.ProxyAuth.Enabled && proxyUser != "" {
|
||||
user, err := setupProxyUser(r, &requestContext{}, proxyUser)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 403)
|
||||
return
|
||||
if proxyRedirectUrl != "" {
|
||||
logoutUrl = proxyRedirectUrl
|
||||
}
|
||||
status, err := printToken(w, r, user) // Pass the data object
|
||||
if err != nil {
|
||||
http.Error(w, http.StatusText(status), status)
|
||||
} else {
|
||||
if oidcRedirectUrl != "" {
|
||||
logoutUrl = oidcRedirectUrl
|
||||
}
|
||||
return
|
||||
}
|
||||
if !config.Auth.Methods.PasswordAuth.Enabled {
|
||||
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
// currently only supports user/pass
|
||||
// Get the authentication method from the settings
|
||||
auther, err := store.Auth.Get("password")
|
||||
if err != nil {
|
||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Authenticate the user based on the request
|
||||
user, err := auther.Auth(r, store.Users)
|
||||
if err != nil {
|
||||
logger.Debug(err.Error())
|
||||
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if user.LoginMethod != users.LoginMethodPassword {
|
||||
logger.Warning(fmt.Sprintf("user %s is not allowed to login with password authentication, bypassing and updating login method", user.Username))
|
||||
user.LoginMethod = users.LoginMethodPassword
|
||||
// Perform the user update
|
||||
err = store.Users.Update(user, true, "LoginMethod")
|
||||
if err != nil {
|
||||
logger.Debug(err.Error())
|
||||
}
|
||||
//http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
|
||||
//return
|
||||
}
|
||||
|
||||
status, err := printToken(w, r, user) // Pass the data object
|
||||
if err != nil {
|
||||
http.Error(w, http.StatusText(status), status)
|
||||
}
|
||||
// clear cookie
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "auth",
|
||||
Value: "",
|
||||
MaxAge: -1,
|
||||
Path: "/",
|
||||
})
|
||||
http.Redirect(w, r, logoutUrl, http.StatusFound)
|
||||
return 302, nil
|
||||
}
|
||||
|
||||
type signupBody struct {
|
||||
@@ -193,41 +178,32 @@ type signupBody struct {
|
||||
// @Failure 409 {object} map[string]string "Conflict - user already exists"
|
||||
// @Failure 500 {object} map[string]string "Internal server error"
|
||||
// @Router /api/signup [post]
|
||||
func signupHandler(w http.ResponseWriter, r *http.Request) {
|
||||
func signupHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
|
||||
if !settings.Config.Auth.Methods.PasswordAuth.Signup {
|
||||
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
|
||||
return
|
||||
return http.StatusMethodNotAllowed, fmt.Errorf("signup is disabled")
|
||||
}
|
||||
|
||||
if r.Body == nil {
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
return
|
||||
return http.StatusBadRequest, fmt.Errorf("no post body provided")
|
||||
}
|
||||
|
||||
info := &signupBody{}
|
||||
err := json.NewDecoder(r.Body).Decode(info)
|
||||
if err != nil {
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
return
|
||||
return http.StatusBadRequest, fmt.Errorf("invalid request body: %v", err)
|
||||
}
|
||||
|
||||
if info.Password == "" || info.Username == "" {
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
return
|
||||
user := users.User{
|
||||
Username: info.Username,
|
||||
NonAdminEditable: users.NonAdminEditable{
|
||||
Password: info.Password,
|
||||
},
|
||||
LoginMethod: users.LoginMethodPassword,
|
||||
}
|
||||
user := &users.User{}
|
||||
settings.ApplyUserDefaults(user)
|
||||
user.Username = info.Username
|
||||
user.Password = info.Password
|
||||
|
||||
err = store.Users.Save(user, true)
|
||||
if err == errors.ErrExist {
|
||||
http.Error(w, http.StatusText(http.StatusConflict), http.StatusConflict)
|
||||
return
|
||||
} else if err != nil {
|
||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||
return
|
||||
err = storage.CreateUser(user, false)
|
||||
if err != nil {
|
||||
logger.Debug(err.Error())
|
||||
w.WriteHeader(http.StatusConflict)
|
||||
return http.StatusConflict, fmt.Errorf("user already exists")
|
||||
}
|
||||
return 201, nil
|
||||
}
|
||||
|
||||
// renewHandler refreshes the authentication token for a logged-in user.
|
||||
@@ -251,11 +227,11 @@ func printToken(w http.ResponseWriter, _ *http.Request, user *users.User) (int,
|
||||
if strings.Contains(err.Error(), "key already exists with same name") {
|
||||
return http.StatusConflict, err
|
||||
}
|
||||
return http.StatusInternalServerError, err
|
||||
return 401, errors.ErrUnauthorized
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
if _, err := w.Write([]byte(signed.Key)); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
return 401, errors.ErrUnauthorized
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
@@ -322,347 +298,3 @@ func authenticateShareRequest(r *http.Request, l *share.Link) (int, error) {
|
||||
}
|
||||
return 200, nil
|
||||
}
|
||||
|
||||
// userInfo struct to hold user claims from either UserInfo or ID token
|
||||
type userInfo struct {
|
||||
Name string `json:"name"`
|
||||
PreferredUsername string `json:"preferred_username"`
|
||||
Email string `json:"email"`
|
||||
Sub string `json:"sub"`
|
||||
Phone string `json:"phone_number"`
|
||||
}
|
||||
|
||||
// getKeySet fetches the JWKS from the given URL, using the provided cache.
|
||||
func getKeySet(jwksUrl string) (jwk.Set, error) {
|
||||
// Check cache first
|
||||
value := cache.JwtCache.Get(jwksUrl)
|
||||
jwks, ok := value.(jwk.Set)
|
||||
if ok {
|
||||
return jwks, nil
|
||||
}
|
||||
logger.Debug("JWKS not found in cache for, fetching...")
|
||||
// Fetch the JWKS from the URL
|
||||
resp, err := http.Get(jwksUrl)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to fetch JWKS from %s: %v", jwksUrl, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
return nil, fmt.Errorf("failed to fetch JWKS from %s: received status code %d with body: %s", jwksUrl, resp.StatusCode, string(bodyBytes))
|
||||
}
|
||||
|
||||
// Decode the JWKS using jwk.ParseReader
|
||||
jwks, err = jwk.ParseReader(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode JWKS: %v", err)
|
||||
}
|
||||
|
||||
// Store in cache. Assuming your cache handles expiration (e.g., 1 hour).
|
||||
cache.JwtCache.Set(jwksUrl, jwks) // Store the jwk.Set
|
||||
return jwks, nil // Return the jwk.Set after type assertion
|
||||
}
|
||||
|
||||
// oidcCallbackHandler handles the OIDC callback after the user authenticates with the provider.
|
||||
// It exchanges the authorization code for tokens, then attempts to verify the ID token using JWKS
|
||||
// if configured, falling back to the UserInfo endpoint if necessary.
|
||||
func oidcCallbackHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
|
||||
code := r.URL.Query().Get("code")
|
||||
// state := r.URL.Query().Get("state") // You might want to validate the state parameter for CSRF protection
|
||||
|
||||
origin := r.Header.Get("Origin")
|
||||
if origin == "" {
|
||||
origin = fmt.Sprintf("%s://%s", getScheme(r), r.Host)
|
||||
}
|
||||
|
||||
redirectURI := fmt.Sprintf("%s/api/auth/oidc/callback", origin)
|
||||
|
||||
// Step 1: Exchange the code for tokens
|
||||
data := url.Values{}
|
||||
data.Set("grant_type", "authorization_code")
|
||||
data.Set("code", code)
|
||||
data.Set("client_id", config.Auth.Methods.OidcAuth.ClientID)
|
||||
data.Set("client_secret", config.Auth.Methods.OidcAuth.ClientSecret)
|
||||
data.Set("redirect_uri", redirectURI)
|
||||
|
||||
req, _ := http.NewRequest("POST", config.Auth.Methods.OidcAuth.TokenUrl, strings.NewReader(data.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
client := &http.Client{} // Consider using a client with a timeout
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
logger.Debug(fmt.Sprintf("failed to send token request: %v", err))
|
||||
return 500, fmt.Errorf("token request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
logger.Debug(fmt.Sprintf("failed to fetch token: %v %v", resp.StatusCode, string(body)))
|
||||
return 500, fmt.Errorf("failed to fetch token: %v %v", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
// Decode the token response, expecting access_token and potentially id_token
|
||||
var tokenResp struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
IDToken string `json:"id_token"` // OIDC providers include id_token here
|
||||
}
|
||||
|
||||
if err = json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {
|
||||
logger.Debug(fmt.Sprintf("failed to parse token response: %v", err))
|
||||
return 500, fmt.Errorf("failed to parse token response: %v", err)
|
||||
}
|
||||
|
||||
var userdata userInfo // This will hold the user claims, using the original struct
|
||||
useUserInfoEndpoint := true // Flag to determine if we need to call the UserInfo endpoint
|
||||
|
||||
// Step 2: Process ID Token if available and JWKS URL is configured
|
||||
if tokenResp.IDToken != "" && config.Auth.Methods.OidcAuth.JwksUrl != "" {
|
||||
logger.Debug(fmt.Sprintf("ID token received `%v` attempting to verify using JWKS URL", tokenResp.IDToken))
|
||||
// getKeySet now returns jwk.Set (interface)
|
||||
var jwks jwk.Set
|
||||
jwks, err = getKeySet(config.Auth.Methods.OidcAuth.JwksUrl)
|
||||
if err != nil {
|
||||
// Log the error but don't fail yet, try UserInfo endpoint as a fallback
|
||||
logger.Warning("Failed to fetch or decode JWKS: %v. Falling back to UserInfo endpoint. Ensure your OidcAuth.JwksUrl is correct.")
|
||||
} else {
|
||||
var token *jwt.Token
|
||||
// Parse the ID token. We need to provide a key function to `jwt.Parse`
|
||||
// that looks up the key in the JWKS based on the token's `kid`.
|
||||
token, err = jwt.Parse(tokenResp.IDToken, func(token *jwt.Token) (interface{}, error) {
|
||||
switch alg := token.Method.Alg(); alg {
|
||||
case "RS256", "RS384", "RS512", "ES256", "ES384", "ES512", "PS256", "PS384", "PS512", "EdDSA":
|
||||
// accepted
|
||||
default:
|
||||
logger.Debug(fmt.Sprintf("unsupported signing method recieved `%v`", alg))
|
||||
return nil, fmt.Errorf("unsupported signing method recieved: %v", alg)
|
||||
}
|
||||
// Find the key in the JWKS that matches the token's kid (Key ID)
|
||||
keyID, ok := token.Header["kid"].(string)
|
||||
if !ok {
|
||||
logger.Debug("kid header not found in ID token")
|
||||
return nil, fmt.Errorf("kid header not found in ID token")
|
||||
}
|
||||
// Use the jwk.Set interface to find the key
|
||||
// LookupKeyID returns a slice of jwk.Key and a boolean indicating if any keys were found.
|
||||
key, found := jwks.LookupKeyID(keyID) // Called on the jwk.Set interface
|
||||
if !found {
|
||||
logger.Debug(fmt.Sprintf("key with kid %s not found in JWKS", keyID))
|
||||
return nil, fmt.Errorf("key with kid %s not found in JWKS", keyID)
|
||||
}
|
||||
// Return the public key from the first matching JWK
|
||||
// In a real scenario, you might need more sophisticated key selection logic.
|
||||
// The jwk.Key interface has a PublicKey() method to get the public key.
|
||||
publicKey, publicKeyErr := key.PublicKey()
|
||||
if publicKeyErr != nil {
|
||||
logger.Debug(fmt.Sprintf("failed to get public key from JWK: %v", publicKeyErr))
|
||||
return nil, fmt.Errorf("failed to get public key from JWK: %v", err)
|
||||
}
|
||||
return publicKey, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
// Log the verification error but fall back to UserInfo endpoint
|
||||
logger.Error(fmt.Sprintf("failed to parse or verify ID token: %v. Falling back to UserInfo endpoint.", err))
|
||||
} else if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
||||
logger.Debug("ID token verified successfully, claims extracted.")
|
||||
|
||||
// --- IMPORTANT OIDC VALIDATION ---
|
||||
// In a production application, you MUST perform additional validations on the ID token claims:
|
||||
// - Issuer (iss): Must match the expected issuer URL.
|
||||
// - Audience (aud): Must contain your client ID.
|
||||
// - Expiration Time (exp): Token must not be expired (jwt.Parse handles this if clock skew is accounted for).
|
||||
// - Issued At Time (iat): Token must not be issued in the future.
|
||||
// - Nonce (nonce): If a nonce was sent in the authorization request, it must match the 'nonce' claim in the ID token.
|
||||
// - Authorized Party (azp): If 'aud' has multiple values, 'azp' must be present and equal to your client ID.
|
||||
// - at_hash and c_hash: If the access token or authorization code were issued, validate their hashes if present in the ID token.
|
||||
// A dedicated OIDC library handles these validations correctly and securely.
|
||||
// This simplified example only verifies the signature and basic validity.
|
||||
// --- END IMPORTANT OIDC VALIDATION ---
|
||||
|
||||
// Populate the userInfo struct from the ID token claims (map)
|
||||
if name, ok := claims["name"].(string); ok {
|
||||
userdata.Name = name
|
||||
}
|
||||
if preferredUsername, ok := claims["preferred_username"].(string); ok {
|
||||
userdata.PreferredUsername = preferredUsername
|
||||
}
|
||||
if email, ok := claims["email"].(string); ok {
|
||||
userdata.Email = email
|
||||
}
|
||||
if sub, ok := claims["sub"].(string); ok {
|
||||
userdata.Sub = sub
|
||||
}
|
||||
if phone, ok := claims["phone_number"].(string); ok {
|
||||
userdata.Phone = phone
|
||||
}
|
||||
|
||||
useUserInfoEndpoint = false // Successfully processed ID token, no need for UserInfo endpoint
|
||||
|
||||
} else {
|
||||
// ID token signature verification failed or token is invalid for other reasons
|
||||
logger.Error("id token signature verification failed or token is invalid. Falling back to UserInfo endpoint.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Step 3: Use the access token to fetch user info from the UserInfo URL if needed
|
||||
// This step is skipped if the ID token was successfully processed and verified.
|
||||
if useUserInfoEndpoint {
|
||||
userInfoURL := config.Auth.Methods.OidcAuth.UserInfoUrl
|
||||
req, _ = http.NewRequest("GET", userInfoURL, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenResp.AccessToken)
|
||||
|
||||
resp, err = client.Do(req)
|
||||
if err != nil {
|
||||
return 500, fmt.Errorf("failed to fetch user info: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
return 500, fmt.Errorf("failed to fetch user info: received status code %d with body: %s", resp.StatusCode, string(bodyBytes))
|
||||
}
|
||||
|
||||
// Decode the UserInfo response directly into the original userdata struct
|
||||
if err = json.NewDecoder(resp.Body).Decode(&userdata); err != nil {
|
||||
return 500, fmt.Errorf("failed to parse user info: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Now userdata contains claims from either the verified ID token or the UserInfo endpoint.
|
||||
// Proceed with logging in the user based on the extracted claims.
|
||||
return loginWithOidcUser(w, r, userdata)
|
||||
}
|
||||
|
||||
// oidcLoginHandler redirects the user to the OIDC provider's authorization endpoint.
|
||||
// This function remains largely the same, but includes the 'fb_redirect' parameter
|
||||
// to redirect the user back to the original page after successful login.
|
||||
func oidcLoginHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
|
||||
if config.Auth.Methods.OidcAuth.Enabled {
|
||||
origin := r.Header.Get("Origin")
|
||||
if origin == "" {
|
||||
origin = fmt.Sprintf("%s://%s", getScheme(r), r.Host)
|
||||
}
|
||||
|
||||
// Generate a nonce for CSRF protection (optional but recommended)
|
||||
// You should store this nonce and validate it in the callback handler.
|
||||
nonce := utils.InsecureRandomIdentifier(16)
|
||||
// For state parameter, you might include the nonce and the original redirect URL
|
||||
state := fmt.Sprintf("%s:%s", nonce, r.URL.Query().Get("fb_redirect")) // Example state parameter structure
|
||||
|
||||
redirectURI := fmt.Sprintf("%s/api/auth/oidc/callback", origin)
|
||||
|
||||
// Construct the authorization URL
|
||||
authURL := fmt.Sprintf("%s?client_id=%s&response_type=code&scope=%s&redirect_uri=%s&redirect_uris=%s&state=%s",
|
||||
config.Auth.Methods.OidcAuth.AuthorizationUrl,
|
||||
url.QueryEscape(config.Auth.Methods.OidcAuth.ClientID),
|
||||
url.QueryEscape(config.Auth.Methods.OidcAuth.Scopes),
|
||||
url.QueryEscape(redirectURI),
|
||||
url.QueryEscape(redirectURI),
|
||||
url.QueryEscape(state), // Use the state parameter
|
||||
)
|
||||
|
||||
// Redirect the user to the OIDC provider
|
||||
http.Redirect(w, r, authURL, http.StatusFound)
|
||||
return 0, nil // Indicate that the request has been handled by the redirect
|
||||
}
|
||||
|
||||
// OIDC authentication is not enabled
|
||||
return http.StatusForbidden, fmt.Errorf("oidc authentication is not enabled")
|
||||
}
|
||||
|
||||
// loginWithOidcUser extracts the username from the user claims (userInfo)
|
||||
// based on the configured UserIdentifier and logs the user into the application.
|
||||
// It creates a new user if one doesn't exist.
|
||||
func loginWithOidcUser(w http.ResponseWriter, r *http.Request, userInfo userInfo) (int, error) {
|
||||
username := userInfo.PreferredUsername
|
||||
switch config.Auth.Methods.OidcAuth.UserIdentifier {
|
||||
case "email":
|
||||
username = userInfo.Email
|
||||
case "username":
|
||||
username = userInfo.PreferredUsername
|
||||
}
|
||||
// Retrieve the user from the store and store it in the context
|
||||
user, err := store.Users.Get(username)
|
||||
if err != nil {
|
||||
if err.Error() != "the resource does not exist" {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
hashpass := ""
|
||||
hashpass, err = users.HashPwd(username) // hashed password that can't actually be used, gets double hashed
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
err = storage.CreateUser(users.User{
|
||||
LoginMethod: users.LoginMethodOidc,
|
||||
Username: username,
|
||||
NonAdminEditable: users.NonAdminEditable{
|
||||
Password: hashpass, // hashed password that can't actually be used
|
||||
},
|
||||
}, false)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
user, err = store.Users.Get(username)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
}
|
||||
if user.LoginMethod != users.LoginMethodOidc {
|
||||
logger.Warning(fmt.Sprintf("user %s is not allowed to login with oidc authentication, bypassing and updating login method", user.Username))
|
||||
user.LoginMethod = users.LoginMethodOidc
|
||||
err = store.Users.Update(user, true, "LoginMethod")
|
||||
if err != nil {
|
||||
logger.Debug(err.Error())
|
||||
}
|
||||
//return http.StatusForbidden, fmt.Errorf("user %s is not allowed to login with OIDC", username)
|
||||
}
|
||||
signed, err := makeSignedTokenAPI(user, "WEB_TOKEN_"+utils.InsecureRandomIdentifier(4), time.Hour*time.Duration(config.Auth.TokenExpirationHours), user.Permissions)
|
||||
if err != nil {
|
||||
// Handle potential errors during token generation
|
||||
if strings.Contains(err.Error(), "key already exists with same name") {
|
||||
return http.StatusConflict, fmt.Errorf("token name conflict: %v", err)
|
||||
}
|
||||
return http.StatusInternalServerError, fmt.Errorf("failed to generate authentication token for user %s: %v", username, err)
|
||||
}
|
||||
|
||||
// Set the authentication token as an HTTP cookie
|
||||
cookie := &http.Cookie{
|
||||
Name: "auth", // The name of your auth cookie
|
||||
Value: signed.Key, // The generated token value
|
||||
Domain: strings.Split(r.Host, ":")[0], // Set domain to the host without port
|
||||
Path: "/", // Make the cookie available to the whole site
|
||||
// Secure: true, // Recommended: Set to true in production with HTTPS
|
||||
// HttpOnly: true, // Recommended: Set to true to prevent client-side script access
|
||||
Expires: time.Now().Add(time.Hour * time.Duration(config.Auth.TokenExpirationHours)), // Set cookie expiration
|
||||
}
|
||||
http.SetCookie(w, cookie)
|
||||
|
||||
// Set the authenticated user in the request context or response writer
|
||||
// This allows subsequent handlers to access the current user.
|
||||
setUserInResponseWriter(w, user)
|
||||
|
||||
// Redirect the user to the page they were trying to access before login,
|
||||
// or to the root ("/") if no specific redirect was requested.
|
||||
// The 'fb_redirect' parameter is extracted from the 'state' parameter for security.
|
||||
state := r.URL.Query().Get("state")
|
||||
fbRedirect := "/" // Default redirect path
|
||||
if state != "" {
|
||||
// Assuming state is in the format "nonce:fb_redirect"
|
||||
parts := strings.SplitN(state, ":", 2)
|
||||
if len(parts) == 2 {
|
||||
// TODO: Validate the nonce part against the stored nonce for CSRF protection
|
||||
// For this example, we'll just extract the redirect part
|
||||
extractedRedirect := parts[1]
|
||||
if extractedRedirect != "" {
|
||||
fbRedirect = extractedRedirect
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fbRedirect, http.StatusFound)
|
||||
|
||||
// Return 0 to indicate that the response has been handled by the redirect
|
||||
return 0, nil
|
||||
}
|
||||
@@ -5,9 +5,9 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/events"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
type messenger struct {
|
||||
@@ -40,7 +40,7 @@ func sseHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int,
|
||||
|
||||
f, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
logger.Debug(fmt.Sprintf("error: ResponseWriter does not support Flusher. User: %s, SessionId: %s", username, sessionId))
|
||||
logger.Debugf("error: ResponseWriter does not support Flusher. User: %s, SessionId: %s", username, sessionId)
|
||||
return http.StatusInternalServerError, fmt.Errorf("streaming not supported")
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ func sseHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int,
|
||||
return http.StatusOK, nil
|
||||
|
||||
case <-clientGone:
|
||||
logger.Debug(fmt.Sprintf("client disconnected. user: %s, SessionId: %s", username, sessionId))
|
||||
logger.Debugf("client disconnected. user: %s, SessionId: %s", username, sessionId)
|
||||
return http.StatusOK, nil
|
||||
|
||||
case msg := <-events.BroadcastChan:
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
func getJobsHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
|
||||
@@ -15,7 +14,7 @@ func getJobsHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (
|
||||
for _, source := range sources {
|
||||
reducedIndex, err := indexing.GetIndexInfo(source)
|
||||
if err != nil {
|
||||
logger.Debug(fmt.Sprintf("error getting index info: %v", err))
|
||||
logger.Debugf("error getting index info: %v", err)
|
||||
continue
|
||||
}
|
||||
reducedIndexes[source] = reducedIndex
|
||||
|
||||
+14
-11
@@ -11,10 +11,10 @@ import (
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/version"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/storage"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
// http-swagger middleware
|
||||
)
|
||||
|
||||
@@ -46,7 +46,7 @@ func StartHttp(ctx context.Context, storage *storage.Storage, shutdownComplete c
|
||||
store = storage
|
||||
config = &settings.Config
|
||||
var err error
|
||||
|
||||
// --- START: ADD THIS DECRYPTION LOGIC ---
|
||||
if embeddedFS {
|
||||
// Embedded mode: Serve files from the embedded assets
|
||||
assetFs, err = fs.Sub(assets, "embed")
|
||||
@@ -72,8 +72,11 @@ func StartHttp(ctx context.Context, storage *storage.Storage, shutdownComplete c
|
||||
api.HandleFunc("DELETE /users", withSelfOrAdmin(userDeleteHandler))
|
||||
|
||||
// Auth routes
|
||||
api.HandleFunc("POST /auth/login", loginHandler)
|
||||
api.HandleFunc("GET /auth/signup", signupHandler)
|
||||
api.HandleFunc("POST /auth/login", userWithoutOTP(loginHandler))
|
||||
api.HandleFunc("GET /auth/logout", withoutUser(logoutHandler))
|
||||
api.HandleFunc("POST /auth/signup", withoutUser(signupHandler))
|
||||
api.HandleFunc("POST /auth/otp/generate", userWithoutOTP(generateOTPHandler))
|
||||
api.HandleFunc("POST /auth/otp/verify", userWithoutOTP(verifyOTPHandler))
|
||||
api.HandleFunc("POST /auth/renew", withUser(renewHandler))
|
||||
api.HandleFunc("PUT /auth/token", withUser(createApiKeyHandler))
|
||||
api.HandleFunc("GET /auth/token", withUser(createApiKeyHandler))
|
||||
@@ -149,7 +152,7 @@ func StartHttp(ctx context.Context, storage *storage.Storage, shutdownComplete c
|
||||
// Load the TLS certificate and key
|
||||
cer, err := tls.LoadX509KeyPair(config.Server.TLSCert, config.Server.TLSKey)
|
||||
if err != nil {
|
||||
logger.Fatal(fmt.Sprintf("Could not load certificate: %v", err))
|
||||
logger.Fatalf("Could not load certificate: %v", err)
|
||||
}
|
||||
|
||||
// Create a custom TLS configuration
|
||||
@@ -166,15 +169,15 @@ func StartHttp(ctx context.Context, storage *storage.Storage, shutdownComplete c
|
||||
|
||||
// Build the full URL with host and port
|
||||
fullURL := fmt.Sprintf("%s://localhost%s%s", scheme, port, config.Server.BaseURL)
|
||||
logger.Info(fmt.Sprintf("Running at : %s", fullURL))
|
||||
logger.Infof("Running at : %s", fullURL)
|
||||
|
||||
// Create a TLS listener and serve
|
||||
listener, err := tls.Listen("tcp", srv.Addr, tlsConfig)
|
||||
if err != nil {
|
||||
logger.Fatal(fmt.Sprintf("Could not start TLS server: %v", err))
|
||||
logger.Fatalf("Could not start TLS server: %v", err)
|
||||
}
|
||||
if err := srv.Serve(listener); err != nil && err != http.ErrServerClosed {
|
||||
logger.Fatal(fmt.Sprintf("Server error: %v", err))
|
||||
logger.Fatalf("Server error: %v", err)
|
||||
}
|
||||
} else {
|
||||
// Set HTTP scheme and the default port for HTTP
|
||||
@@ -185,11 +188,11 @@ func StartHttp(ctx context.Context, storage *storage.Storage, shutdownComplete c
|
||||
|
||||
// Build the full URL with host and port
|
||||
fullURL := fmt.Sprintf("%s://localhost%s%s", scheme, port, config.Server.BaseURL)
|
||||
logger.Info(fmt.Sprintf("Running at : %s", fullURL))
|
||||
logger.Infof("Running at : %s", fullURL)
|
||||
|
||||
// Start HTTP server
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
logger.Fatal(fmt.Sprintf("Server error: %v", err))
|
||||
logger.Fatalf("Server error: %v", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
@@ -202,7 +205,7 @@ func StartHttp(ctx context.Context, storage *storage.Storage, shutdownComplete c
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||
logger.Error(fmt.Sprintf("HTTP server forced to shut down: %v", err))
|
||||
logger.Errorf("HTTP server forced to shut down: %v", err)
|
||||
} else {
|
||||
logger.Info("HTTP server shut down gracefully.")
|
||||
}
|
||||
|
||||
+122
-13
@@ -6,16 +6,18 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
jwt "github.com/golang-jwt/jwt/v4"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/auth"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/errors"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/share"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
type requestContext struct {
|
||||
@@ -78,7 +80,7 @@ func withHashFileHelper(fn handleFunc) handleFunc {
|
||||
})
|
||||
file.Token = link.Token
|
||||
if err != nil {
|
||||
logger.Error(fmt.Sprintf("error fetching file info for share. hash=%v path=%v error=%v", hash, data.path, err))
|
||||
logger.Errorf("error fetching file info for share. hash=%v path=%v error=%v", hash, data.path, err)
|
||||
return errToStatus(err), fmt.Errorf("error fetching share from server")
|
||||
}
|
||||
// Set the file info in the `data` object
|
||||
@@ -99,6 +101,53 @@ func withAdminHelper(fn handleFunc) handleFunc {
|
||||
})
|
||||
}
|
||||
|
||||
func withoutUserHelper(fn handleFunc) handleFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request, data *requestContext) (int, error) {
|
||||
// This middleware is used when no user authentication is required
|
||||
// Call the actual handler function with the updated context
|
||||
return fn(w, r, data)
|
||||
}
|
||||
}
|
||||
|
||||
// allow user without OTP to pass
|
||||
func userWithoutOTPhelper(fn handleFunc) handleFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
|
||||
// This middleware is used when no user authentication is required
|
||||
// Call the actual handler function with the updated context
|
||||
username := r.URL.Query().Get("username")
|
||||
password := r.Header.Get("X-Password")
|
||||
proxyUser := r.Header.Get(config.Auth.Methods.ProxyAuth.Header)
|
||||
if config.Auth.Methods.ProxyAuth.Enabled && proxyUser != "" {
|
||||
user, err := setupProxyUser(r, &requestContext{}, proxyUser)
|
||||
if err != nil {
|
||||
return 401, errors.ErrUnauthorized
|
||||
}
|
||||
d.user = user
|
||||
} else if username == "" || password == "" {
|
||||
return withUserHelper(fn)(w, r, d)
|
||||
} else {
|
||||
if !config.Auth.Methods.PasswordAuth.Enabled {
|
||||
return 401, errors.ErrUnauthorized
|
||||
}
|
||||
// Get the authentication method from the settings
|
||||
auther, err := store.Auth.Get("password")
|
||||
if err != nil {
|
||||
return 401, errors.ErrUnauthorized
|
||||
}
|
||||
// Authenticate the user based on the request
|
||||
user, err := auther.Auth(r, store.Users)
|
||||
if err != nil {
|
||||
if err == errors.ErrNoTotpProvided {
|
||||
return 403, err
|
||||
}
|
||||
return 401, errors.ErrUnauthorized
|
||||
}
|
||||
d.user = user
|
||||
}
|
||||
return fn(w, r, d)
|
||||
}
|
||||
}
|
||||
|
||||
// Middleware to retrieve and authenticate user
|
||||
func withUserHelper(fn handleFunc) handleFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request, data *requestContext) (int, error) {
|
||||
@@ -107,7 +156,7 @@ func withUserHelper(fn handleFunc) handleFunc {
|
||||
// Retrieve the user from the store and store it in the context
|
||||
data.user, err = store.Users.Get(uint(1))
|
||||
if err != nil {
|
||||
logger.Error(fmt.Sprintf("no auth: %v", err))
|
||||
logger.Errorf("no auth: %v", err)
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
return fn(w, r, data)
|
||||
@@ -192,14 +241,14 @@ func wrapHandler(fn handleFunc) http.HandlerFunc {
|
||||
// Marshal the error response to JSON
|
||||
errorBytes, marshalErr := json.Marshal(response)
|
||||
if marshalErr != nil {
|
||||
logger.Error(fmt.Sprintf("Error marshalling error response: %v", marshalErr))
|
||||
logger.Errorf("Error marshalling error response: %v", marshalErr)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Write the JSON error response
|
||||
if _, writeErr := w.Write(errorBytes); writeErr != nil {
|
||||
logger.Debug(fmt.Sprintf("Error writing error response: %v", writeErr))
|
||||
logger.Debugf("Error writing error response: %v", writeErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -237,6 +286,14 @@ func withUser(fn handleFunc) http.HandlerFunc {
|
||||
return wrapHandler(withUserHelper(fn))
|
||||
}
|
||||
|
||||
func withoutUser(fn handleFunc) http.HandlerFunc {
|
||||
return wrapHandler(withoutUserHelper(fn))
|
||||
}
|
||||
|
||||
func userWithoutOTP(fn handleFunc) http.HandlerFunc {
|
||||
return wrapHandler(userWithoutOTPhelper(fn))
|
||||
}
|
||||
|
||||
func withSelfOrAdmin(fn handleFunc) http.HandlerFunc {
|
||||
return wrapHandler(withSelfOrAdminHelper(fn))
|
||||
}
|
||||
@@ -289,32 +346,84 @@ func setUserInResponseWriter(w http.ResponseWriter, user *users.User) {
|
||||
// LoggingMiddleware logs each request and its status code.
|
||||
func LoggingMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
// DEFER RECOVERY FUNCTION
|
||||
defer func() {
|
||||
if rcv := recover(); rcv != nil {
|
||||
// Log detailed information about the panic
|
||||
// Extract as much context as possible for logging
|
||||
method := r.Method
|
||||
url := r.URL.String()
|
||||
remoteAddr := r.RemoteAddr
|
||||
username := "unknown" // Default username
|
||||
|
||||
// Wrap the ResponseWriter to capture the status code.
|
||||
// Attempt to get username from ResponseWriterWrapper if it's set
|
||||
if ww, ok := w.(*ResponseWriterWrapper); ok && ww.User != "" {
|
||||
username = ww.User
|
||||
}
|
||||
// Or try to get it from request context if your other middleware populates it
|
||||
// This depends on your context setup; example:
|
||||
// if dataCtx, ok := r.Context().Value("requestData").(*requestContext); ok && dataCtx.user != nil {
|
||||
// username = dataCtx.user.Username
|
||||
// }
|
||||
|
||||
// Get Go-level stack trace
|
||||
buf := make([]byte, 16384) // Increased buffer size for potentially long CGo traces
|
||||
n := runtime.Stack(buf, false) // false for current goroutine only
|
||||
stackTrace := string(buf[:n])
|
||||
|
||||
logger.Errorf("PANIC RECOVERED: %v\nUser: %s\nMethod: %s\nURL: %s\nRemoteAddr: %s\nGo Stack Trace:\n%s",
|
||||
rcv, username, method, url, remoteAddr, stackTrace)
|
||||
|
||||
// Attempt to send a 500 error response to the client
|
||||
// This is a best-effort; the connection might be broken or process too unstable.
|
||||
if ww, ok := w.(*ResponseWriterWrapper); ok { // Check if it's our wrapper
|
||||
if !ww.wroteHeader { // Only write if headers haven't been sent
|
||||
ww.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
ww.WriteHeader(http.StatusInternalServerError)
|
||||
}
|
||||
} else {
|
||||
_, _ = renderJSON(w, r, &HttpResponse{
|
||||
Status: 500,
|
||||
Message: "A critical internal error occurred. Please try again later.",
|
||||
})
|
||||
}
|
||||
|
||||
// IMPORTANT: After a SIGSEGV from C code, the process might be unstable.
|
||||
// Even if Go recovers, continuing to run the process is risky.
|
||||
// Consider a strategy to gracefully shut down or signal an external supervisor
|
||||
// to restart the process after logging. For now, this will allow other requests
|
||||
// to proceed if the process doesn't die, but be wary.
|
||||
}
|
||||
}() // End of deferred recovery function
|
||||
|
||||
start := time.Now()
|
||||
wrappedWriter := &ResponseWriterWrapper{ResponseWriter: w, StatusCode: http.StatusOK}
|
||||
|
||||
// Call the next handler.
|
||||
// Call the next handler in the chain
|
||||
next.ServeHTTP(wrappedWriter, r)
|
||||
|
||||
// Capture the full URL path including the query parameters.
|
||||
// Existing logging logic for normal requests
|
||||
fullURL := r.URL.Path
|
||||
if r.URL.RawQuery != "" {
|
||||
fullURL += "?" + r.URL.RawQuery
|
||||
}
|
||||
truncUser := wrappedWriter.User
|
||||
if len(truncUser) > 12 {
|
||||
if truncUser == "" {
|
||||
truncUser = "N/A" // Handle case where user might not be set (e.g., if panic occurred before user auth)
|
||||
} else if len(truncUser) > 12 {
|
||||
truncUser = truncUser[:10] + ".."
|
||||
}
|
||||
duration := time.Since(start)
|
||||
logger.Api(
|
||||
|
||||
// Use the StatusCode from wrappedWriter, which might have been set to 500 by the recover logic
|
||||
logger.Api(wrappedWriter.StatusCode,
|
||||
fmt.Sprintf("%-7s | %3d | %-15s | %-12s | %-12s | \"%s\"",
|
||||
r.Method,
|
||||
wrappedWriter.StatusCode, // Captured status code
|
||||
wrappedWriter.StatusCode,
|
||||
r.RemoteAddr,
|
||||
truncUser,
|
||||
fmt.Sprintf("%vms", duration.Milliseconds()),
|
||||
fullURL), wrappedWriter.StatusCode)
|
||||
fullURL))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -77,10 +77,10 @@ func TestWithAdminHelper(t *testing.T) {
|
||||
Permissions: users.Permissions{Admin: false}, // Non-admin user
|
||||
}
|
||||
// Save the users to the mock database
|
||||
if err := store.Users.Save(adminUser, true); err != nil {
|
||||
if err := store.Users.Save(adminUser, true, true); err != nil {
|
||||
t.Fatal("failed to save admin user:", err)
|
||||
}
|
||||
if err := store.Users.Save(nonAdminUser, true); err != nil {
|
||||
if err := store.Users.Save(nonAdminUser, true, true); err != nil {
|
||||
t.Fatal("failed to save non-admin user:", err)
|
||||
}
|
||||
// Test cases for different scenarios
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/storage"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// userInfo struct to hold user claims from either UserInfo or ID token
|
||||
type userInfo struct {
|
||||
Name string `json:"name"`
|
||||
PreferredUsername string `json:"preferred_username"`
|
||||
Email string `json:"email"`
|
||||
Sub string `json:"sub"`
|
||||
Phone string `json:"phone_number"`
|
||||
}
|
||||
|
||||
// oidcCallbackHandler handles the OIDC callback after the user authenticates with the provider.
|
||||
// It exchanges the authorization code for tokens, attempts to verify the ID token.
|
||||
// If ID token verification or essential claims extraction fails, it falls back to the UserInfo endpoint.
|
||||
func oidcCallbackHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
|
||||
ctx := r.Context()
|
||||
oidcCfg := settings.Config.Auth.Methods.OidcAuth
|
||||
if oidcCfg.Provider == nil || oidcCfg.Verifier == nil {
|
||||
// Ensure Provider and Verifier are initialized on application startup
|
||||
// This check is good, keep it.
|
||||
logger.Error("OIDC provider or verifier not initialized.")
|
||||
return http.StatusInternalServerError, fmt.Errorf("OIDC provider or verifier not initialized")
|
||||
}
|
||||
// If disableVerifyTLS is true, create a custom HTTP client
|
||||
// and set it in the context for the OIDC provider.
|
||||
if oidcCfg.DisableVerifyTLS {
|
||||
// Create a custom transport with InsecureSkipVerify set to true
|
||||
transport := &http.Transport{
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
|
||||
}
|
||||
customClient := &http.Client{
|
||||
Transport: transport,
|
||||
}
|
||||
ctx = oidc.ClientContext(ctx, customClient)
|
||||
}
|
||||
code := r.Header.Get("X-Secret")
|
||||
// state := r.URL.Query().Get("state") // You might want to validate the state parameter for CSRF protection
|
||||
|
||||
// The redirect URI MUST match the one registered with the OIDC provider
|
||||
// and used in the initial /api/auth/oidc/login handler.
|
||||
// Using r.Host here might be tricky if running behind a proxy.
|
||||
// Consider using a fixed redirect URL from settings if possible.
|
||||
redirectURL := fmt.Sprintf("%s://%s/api/auth/oidc/callback", getScheme(r), r.Host)
|
||||
|
||||
oauth2Config := &oauth2.Config{
|
||||
ClientID: oidcCfg.ClientID,
|
||||
ClientSecret: oidcCfg.ClientSecret,
|
||||
Endpoint: oidcCfg.Provider.Endpoint(), // Use endpoint from discovered provider
|
||||
RedirectURL: redirectURL, // Use the dynamically determined redirect URL
|
||||
Scopes: strings.Split(oidcCfg.Scopes, " "),
|
||||
}
|
||||
|
||||
// Exchange the authorization code for tokens
|
||||
token, err := oauth2Config.Exchange(ctx, code)
|
||||
if err != nil {
|
||||
logger.Errorf("failed to exchange token: %v", err)
|
||||
return http.StatusInternalServerError, fmt.Errorf("failed to exchange token: %v", err)
|
||||
}
|
||||
|
||||
rawIDToken, ok := token.Extra("id_token").(string)
|
||||
// accessToken := token.AccessToken // Access token is needed for UserInfo, already in 'token'
|
||||
|
||||
var userdata userInfo // Declare userdata here to be populated by either source
|
||||
claimsFromIDToken := false // Flag to track if we successfully got claims from ID token
|
||||
loginUsername := "" // Variable to hold the login username
|
||||
|
||||
// --- Attempt to process ID Token ---
|
||||
if ok && rawIDToken != "" {
|
||||
logger.Debug("ID token found in token response, attempting verification.")
|
||||
|
||||
// Verify the ID token
|
||||
// This uses the verifier initialized with the provider's JWKS endpoint and client ID
|
||||
idToken, err := oidcCfg.Verifier.Verify(ctx, rawIDToken)
|
||||
if err != nil {
|
||||
logger.Warningf("failed to verify ID token: %v. Falling back to UserInfo endpoint.", err)
|
||||
// Verification failed, claimsFromIDToken remains false
|
||||
} else {
|
||||
var claims map[string]interface{}
|
||||
// Decode the ID token claims into a map to handle arbitrary structure
|
||||
// This is where the JWE unmarshalling error occurs if the token is encrypted
|
||||
if err := idToken.Claims(&claims); err != nil {
|
||||
logger.Warningf("failed to decode ID token claims: %v. Falling back to UserInfo endpoint.", err)
|
||||
// Claims decoding failed, claimsFromIDToken remains false
|
||||
} else {
|
||||
// Successfully verified and decoded ID token claims
|
||||
logger.Debugf("ID Token verified and claims decoded: %+v", claims)
|
||||
|
||||
// Populate userdata from ID token claims
|
||||
if name, ok := claims["name"].(string); ok {
|
||||
userdata.Name = name
|
||||
}
|
||||
if preferredUsername, ok := claims["preferred_username"].(string); ok {
|
||||
userdata.PreferredUsername = preferredUsername
|
||||
}
|
||||
if email, ok := claims["email"].(string); ok {
|
||||
userdata.Email = email
|
||||
}
|
||||
if sub, ok := claims["sub"].(string); ok {
|
||||
userdata.Sub = sub
|
||||
}
|
||||
if phone, ok := claims["phone_number"].(string); ok {
|
||||
userdata.Phone = phone
|
||||
}
|
||||
// Decide if we rely on ID token claims or still need UserInfo
|
||||
// Even if parsing succeeded, if essential claims are missing, use UserInfo
|
||||
switch oidcCfg.UserIdentifier {
|
||||
case "email":
|
||||
if userdata.Email != "" {
|
||||
claimsFromIDToken = true
|
||||
loginUsername = userdata.Email
|
||||
}
|
||||
case "username":
|
||||
if userdata.PreferredUsername != "" {
|
||||
claimsFromIDToken = true
|
||||
loginUsername = userdata.PreferredUsername
|
||||
}
|
||||
case "phone":
|
||||
if userdata.Phone != "" {
|
||||
claimsFromIDToken = true
|
||||
loginUsername = userdata.Phone
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
logger.Debug("No ID token found in token response or it was empty. Falling back to UserInfo endpoint.")
|
||||
// claimsFromIDToken remains false
|
||||
}
|
||||
|
||||
// --- Fallback to UserInfo endpoint if ID token processing did not provide essential claims ---
|
||||
if !claimsFromIDToken {
|
||||
// Use the access token obtained from the initial exchange
|
||||
// oauth2Config.TokenSource creates a token source that uses the provided token.
|
||||
userInfoResp, err := oidcCfg.Provider.UserInfo(ctx, oauth2Config.TokenSource(ctx, token))
|
||||
if err != nil {
|
||||
logger.Errorf("failed to fetch user info from endpoint: %v", err)
|
||||
return http.StatusInternalServerError, fmt.Errorf("failed to fetch user info from endpoint: %v", err)
|
||||
}
|
||||
// Decode the UserInfo response directly into the userdata struct
|
||||
// The UserInfo endpoint is expected to return standard JSON
|
||||
if err := userInfoResp.Claims(&userdata); err != nil {
|
||||
logger.Errorf("failed to decode user info from endpoint: %v", err)
|
||||
return http.StatusInternalServerError, fmt.Errorf("failed to decode user info from endpoint: %v", err)
|
||||
}
|
||||
// Decide if we rely on ID token claims or still need UserInfo
|
||||
// Even if parsing succeeded, if essential claims are missing, use UserInfo
|
||||
switch oidcCfg.UserIdentifier {
|
||||
case "email":
|
||||
loginUsername = userdata.Email
|
||||
case "username":
|
||||
loginUsername = userdata.PreferredUsername
|
||||
case "phone":
|
||||
loginUsername = userdata.Phone
|
||||
}
|
||||
}
|
||||
if loginUsername == "" {
|
||||
logger.Error("No valid username found in ID token or UserInfo response.")
|
||||
return http.StatusInternalServerError, fmt.Errorf("no valid username found in ID token or UserInfo response from claims")
|
||||
}
|
||||
// Proceed to log the user in with the OIDC data
|
||||
// userdata struct now contains info from either verified ID token or UserInfo endpoint
|
||||
return loginWithOidcUser(w, r, loginUsername)
|
||||
}
|
||||
|
||||
// oidcLoginHandler redirects the user to the OIDC provider's authorization endpoint.
|
||||
// This function remains largely the same, but includes the 'fb_redirect' parameter
|
||||
// to redirect the user back to the original page after successful login.
|
||||
func oidcLoginHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
|
||||
oidcCfg := settings.Config.Auth.Methods.OidcAuth
|
||||
if !oidcCfg.Enabled {
|
||||
return http.StatusForbidden, fmt.Errorf("oidc authentication is not enabled")
|
||||
}
|
||||
|
||||
origin := r.Header.Get("Origin")
|
||||
if origin == "" {
|
||||
origin = fmt.Sprintf("%s://%s", getScheme(r), r.Host)
|
||||
}
|
||||
|
||||
oauth2Config := &oauth2.Config{
|
||||
ClientID: oidcCfg.ClientID,
|
||||
ClientSecret: oidcCfg.ClientSecret,
|
||||
Endpoint: oidcCfg.Provider.Endpoint(),
|
||||
RedirectURL: fmt.Sprintf("%s/api/auth/oidc/callback", origin),
|
||||
Scopes: strings.Split(oidcCfg.Scopes, " "),
|
||||
}
|
||||
|
||||
nonce := utils.InsecureRandomIdentifier(16)
|
||||
fbRedirect := r.URL.Query().Get("fb_redirect")
|
||||
state := fmt.Sprintf("%s:%s", nonce, fbRedirect)
|
||||
|
||||
authURL := oauth2Config.AuthCodeURL(state)
|
||||
http.Redirect(w, r, authURL, http.StatusFound)
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// loginWithOidcUser extracts the username from the user claims (userInfo)
|
||||
// based on the configured UserIdentifier and logs the user into the application.
|
||||
// It creates a new user if one doesn't exist.
|
||||
func loginWithOidcUser(w http.ResponseWriter, r *http.Request, username string) (int, error) {
|
||||
logger.Debugf("Successfully authenticated OIDC username: %s", username)
|
||||
// Retrieve the user from the store and store it in the context
|
||||
user, err := store.Users.Get(username)
|
||||
if err != nil {
|
||||
if err.Error() != "the resource does not exist" {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
err = storage.CreateUser(users.User{
|
||||
LoginMethod: users.LoginMethodOidc,
|
||||
Username: username,
|
||||
}, false)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
user, err = store.Users.Get(username)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
}
|
||||
if user.LoginMethod != users.LoginMethodOidc {
|
||||
logger.Warningf("user %s is not allowed to login with oidc authentication, bypassing and updating login method", user.Username)
|
||||
user.LoginMethod = users.LoginMethodOidc
|
||||
err = store.Users.Update(user, true, "LoginMethod")
|
||||
if err != nil {
|
||||
logger.Debug(err.Error())
|
||||
}
|
||||
//return http.StatusForbidden, fmt.Errorf("user %s is not allowed to login with OIDC", username)
|
||||
}
|
||||
signed, err := makeSignedTokenAPI(user, "WEB_TOKEN_"+utils.InsecureRandomIdentifier(4), time.Hour*time.Duration(config.Auth.TokenExpirationHours), user.Permissions)
|
||||
if err != nil {
|
||||
// Handle potential errors during token generation
|
||||
if strings.Contains(err.Error(), "key already exists with same name") {
|
||||
return http.StatusConflict, fmt.Errorf("token name conflict: %v", err)
|
||||
}
|
||||
return http.StatusInternalServerError, fmt.Errorf("failed to generate authentication token for user %s: %v", username, err)
|
||||
}
|
||||
|
||||
// Set the authentication token as an HTTP cookie
|
||||
cookie := &http.Cookie{
|
||||
Name: "auth", // The name of your auth cookie
|
||||
Value: signed.Key, // The generated token value
|
||||
Domain: strings.Split(r.Host, ":")[0], // Set domain to the host without port
|
||||
Path: "/", // Make the cookie available to the whole site
|
||||
// Secure: true, // Recommended: Set to true in production with HTTPS
|
||||
// HttpOnly: true, // Recommended: Set to true to prevent client-side script access
|
||||
Expires: time.Now().Add(time.Hour * time.Duration(config.Auth.TokenExpirationHours)), // Set cookie expiration
|
||||
}
|
||||
http.SetCookie(w, cookie)
|
||||
|
||||
// Set the authenticated user in the request context or response writer
|
||||
// This allows subsequent handlers to access the current user.
|
||||
setUserInResponseWriter(w, user)
|
||||
|
||||
// Redirect the user to the page they were trying to access before login,
|
||||
// or to the root ("/") if no specific redirect was requested.
|
||||
// The 'fb_redirect' parameter is extracted from the 'state' parameter for security.
|
||||
state := r.URL.Query().Get("state")
|
||||
fbRedirect := "/" // Default redirect path
|
||||
if state != "" {
|
||||
// Assuming state is in the format "nonce:fb_redirect"
|
||||
parts := strings.SplitN(state, ":", 2)
|
||||
if len(parts) == 2 {
|
||||
// TODO: Validate the nonce part against the stored nonce for CSRF protection
|
||||
// For this example, we'll just extract the redirect part
|
||||
extractedRedirect := parts[1]
|
||||
if extractedRedirect != "" {
|
||||
fbRedirect = extractedRedirect
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fbRedirect, http.StatusFound)
|
||||
|
||||
// Return 0 to indicate that the response has been handled by the redirect
|
||||
return 0, nil
|
||||
}
|
||||
@@ -12,12 +12,11 @@ import (
|
||||
|
||||
jwt "github.com/golang-jwt/jwt/v4"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/cache"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -196,7 +195,7 @@ func getOnlyOfficeId(source, path string) (string, error) {
|
||||
realpath, _, _ := idx.GetRealPath(path)
|
||||
// error is intentionally ignored in order treat errors
|
||||
// the same as a cache-miss
|
||||
cachedDocumentKey, ok := cache.OnlyOffice.Get(realpath).(string)
|
||||
cachedDocumentKey, ok := utils.OnlyOfficeCache.Get(realpath).(string)
|
||||
if ok {
|
||||
return cachedDocumentKey, nil
|
||||
}
|
||||
@@ -206,11 +205,11 @@ func getOnlyOfficeId(source, path string) (string, error) {
|
||||
func deleteOfficeId(source, path string) {
|
||||
idx := indexing.GetIndex(source)
|
||||
if idx == nil {
|
||||
logger.Error(fmt.Sprintf("deleteOfficeId: failed to find source index for user home dir creation: %s", source))
|
||||
logger.Errorf("deleteOfficeId: failed to find source index for user home dir creation: %s", source)
|
||||
return
|
||||
}
|
||||
realpath, _, _ := idx.GetRealPath(path)
|
||||
cache.OnlyOffice.Delete(realpath)
|
||||
utils.OnlyOfficeCache.Delete(realpath)
|
||||
}
|
||||
|
||||
func onlyofficeGetTokenHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
|
||||
|
||||
+38
-13
@@ -5,7 +5,9 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files"
|
||||
@@ -42,11 +44,17 @@ func previewHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (
|
||||
if config.Server.DisablePreviews {
|
||||
return http.StatusNotImplemented, fmt.Errorf("preview is disabled")
|
||||
}
|
||||
|
||||
path := r.URL.Query().Get("path")
|
||||
source := r.URL.Query().Get("source")
|
||||
if source == "" {
|
||||
source = settings.Config.Server.DefaultSource.Name
|
||||
} else {
|
||||
var err error
|
||||
// decode url encoded source name
|
||||
source, err = url.QueryUnescape(source)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, fmt.Errorf("invalid source encoding: %v", err)
|
||||
}
|
||||
}
|
||||
if path == "" {
|
||||
return http.StatusBadRequest, fmt.Errorf("invalid request path")
|
||||
@@ -89,8 +97,8 @@ func rawFileHandler(w http.ResponseWriter, r *http.Request, file iteminfo.Extend
|
||||
|
||||
func previewHelperFunc(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
|
||||
previewSize := r.URL.Query().Get("size")
|
||||
if previewSize != "small" {
|
||||
previewSize = "large"
|
||||
if !(previewSize == "large" || previewSize == "original") {
|
||||
previewSize = "small"
|
||||
}
|
||||
if d.fileInfo.Type == "directory" {
|
||||
return http.StatusBadRequest, fmt.Errorf("can't create preview for directory")
|
||||
@@ -106,18 +114,35 @@ func previewHelperFunc(w http.ResponseWriter, r *http.Request, d *requestContext
|
||||
}
|
||||
return http.StatusNotImplemented, fmt.Errorf("can't create preview for %s type", d.fileInfo.Type)
|
||||
}
|
||||
pathUrl := fmt.Sprintf("/api/raw?files=%s::%s", d.fileInfo.Source, d.fileInfo.Path)
|
||||
pathUrl = pathUrl + "&auth=" + d.token
|
||||
if settings.Config.Server.InternalUrl != "" {
|
||||
pathUrl = config.Server.InternalUrl + pathUrl
|
||||
} else {
|
||||
scheme := "http"
|
||||
if r.TLS != nil {
|
||||
scheme = "https"
|
||||
seekPercentage := 0
|
||||
percentage := r.URL.Query().Get("atPercentage")
|
||||
if percentage != "" {
|
||||
var err error
|
||||
// convert string to int
|
||||
seekPercentage, err = strconv.Atoi(percentage)
|
||||
if err != nil {
|
||||
seekPercentage = 10
|
||||
}
|
||||
if seekPercentage < 0 || seekPercentage > 100 {
|
||||
seekPercentage = 10
|
||||
}
|
||||
pathUrl = scheme + "://" + r.Host + pathUrl
|
||||
}
|
||||
previewImg, err := preview.GetPreviewForFile(d.fileInfo, previewSize, pathUrl)
|
||||
|
||||
officeUrl := ""
|
||||
if d.fileInfo.OnlyOfficeId != "" {
|
||||
pathUrl := fmt.Sprintf("/api/raw?files=%s::%s", d.fileInfo.Source, d.fileInfo.Path)
|
||||
pathUrl = pathUrl + "&auth=" + d.token
|
||||
if settings.Config.Server.InternalUrl != "" {
|
||||
officeUrl = config.Server.InternalUrl + pathUrl
|
||||
} else {
|
||||
scheme := "http"
|
||||
if r.TLS != nil {
|
||||
scheme = "https"
|
||||
}
|
||||
officeUrl = scheme + "://" + r.Host + pathUrl
|
||||
}
|
||||
}
|
||||
previewImg, err := preview.GetPreviewForFile(d.fileInfo, previewSize, officeUrl, seekPercentage)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
+10
-3
@@ -8,11 +8,11 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
|
||||
_ "github.com/gtsteffaniak/filebrowser/backend/swagger/docs"
|
||||
)
|
||||
@@ -52,7 +52,7 @@ func publicRawHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
|
||||
var status int
|
||||
status, err = rawFilesHandler(w, r, d, fileList)
|
||||
if err != nil {
|
||||
logger.Error(fmt.Sprintf("public share handler: error processing filelist: %v", err))
|
||||
logger.Errorf("public share handler: error processing filelist: %v", err)
|
||||
return status, fmt.Errorf("error processing filelist: %v", f)
|
||||
}
|
||||
return status, nil
|
||||
@@ -118,6 +118,13 @@ func publicPreviewHandler(w http.ResponseWriter, r *http.Request, d *requestCont
|
||||
source := r.URL.Query().Get("source")
|
||||
if source == "" {
|
||||
source = settings.Config.Server.DefaultSource.Name
|
||||
} else {
|
||||
var err error
|
||||
// decode url encoded source name
|
||||
source, err = url.QueryUnescape(source)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, fmt.Errorf("invalid source encoding: %v", err)
|
||||
}
|
||||
}
|
||||
if path == "" {
|
||||
return http.StatusBadRequest, fmt.Errorf("invalid request path")
|
||||
@@ -129,7 +136,7 @@ func publicPreviewHandler(w http.ResponseWriter, r *http.Request, d *requestCont
|
||||
Expand: true,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Debug(fmt.Sprintf("public preview handler: error getting file info: %v", err))
|
||||
logger.Debugf("public preview handler: error getting file info: %v", err)
|
||||
return 400, fmt.Errorf("file not found")
|
||||
}
|
||||
if fileInfo.Type == "directory" {
|
||||
|
||||
+6
-6
@@ -13,10 +13,10 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
func setContentDisposition(w http.ResponseWriter, r *http.Request, fileName string) {
|
||||
@@ -232,7 +232,7 @@ func rawFilesHandler(w http.ResponseWriter, r *http.Request, d *requestContext,
|
||||
sizeInMB := estimatedSize / 1024 / 1024
|
||||
// if larger than 500 MB, log it
|
||||
if sizeInMB > 500 {
|
||||
logger.Debug(fmt.Sprintf("User %v is downloading large (%d MB) file: %v", d.user.Username, sizeInMB, fileName))
|
||||
logger.Debugf("User %v is downloading large (%d MB) file: %v", d.user.Username, sizeInMB, fileName)
|
||||
}
|
||||
// serve content allows for range requests.
|
||||
// video scrubbing, etc.
|
||||
@@ -295,7 +295,7 @@ func rawFilesHandler(w http.ResponseWriter, r *http.Request, d *requestContext,
|
||||
|
||||
sizeInMB := fileInfo.Size() / 1024 / 1024
|
||||
if sizeInMB > 500 {
|
||||
logger.Debug(fmt.Sprintf("User %v is downloading large (%d MB) file: %v", d.user.Username, sizeInMB, fileName))
|
||||
logger.Debugf("User %v is downloading large (%d MB) file: %v", d.user.Username, sizeInMB, fileName)
|
||||
}
|
||||
|
||||
// Set headers AFTER computing actual archive size
|
||||
@@ -307,7 +307,7 @@ func rawFilesHandler(w http.ResponseWriter, r *http.Request, d *requestContext,
|
||||
_, err = io.Copy(w, fd)
|
||||
os.Remove(archiveData) // Remove the file after streaming
|
||||
if err != nil {
|
||||
logger.Error(fmt.Sprintf("Failed to copy archive data to response: %v", err))
|
||||
logger.Errorf("Failed to copy archive data to response: %v", err)
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
@@ -362,7 +362,7 @@ func createZip(d *requestContext, tmpDirPath string, filenames ...string) error
|
||||
for _, fname := range filenames {
|
||||
err := addFile(fname, d, nil, zipWriter, false)
|
||||
if err != nil {
|
||||
logger.Error(fmt.Sprintf("Failed to add %s to ZIP: %v", fname, err))
|
||||
logger.Errorf("Failed to add %s to ZIP: %v", fname, err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -385,7 +385,7 @@ func createTarGz(d *requestContext, tmpDirPath string, filenames ...string) erro
|
||||
for _, fname := range filenames {
|
||||
err := addFile(fname, d, tarWriter, nil, false)
|
||||
if err != nil {
|
||||
logger.Error(fmt.Sprintf("Failed to add %s to TAR.GZ: %v", fname, err))
|
||||
logger.Errorf("Failed to add %s to TAR.GZ: %v", fname, err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,12 +13,12 @@ import (
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/errors"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/preview"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
// resourceGetHandler retrieves information about a resource.
|
||||
@@ -41,6 +41,13 @@ func resourceGetHandler(w http.ResponseWriter, r *http.Request, d *requestContex
|
||||
source := r.URL.Query().Get("source")
|
||||
if source == "" {
|
||||
source = config.Server.DefaultSource.Name
|
||||
} else {
|
||||
var err error
|
||||
// decode url encoded source name
|
||||
source, err = url.QueryUnescape(source)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, fmt.Errorf("invalid source encoding: %v", err)
|
||||
}
|
||||
}
|
||||
// Decode the URL-encoded path
|
||||
path, err := url.QueryUnescape(encodedPath)
|
||||
@@ -109,6 +116,13 @@ func resourceDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestCon
|
||||
source := r.URL.Query().Get("source")
|
||||
if source == "" {
|
||||
source = config.Server.DefaultSource.Name
|
||||
} else {
|
||||
var err error
|
||||
// decode url encoded source name
|
||||
source, err = url.QueryUnescape(source)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, fmt.Errorf("invalid source encoding: %v", err)
|
||||
}
|
||||
}
|
||||
// Decode the URL-encoded path
|
||||
path, err := url.QueryUnescape(encodedPath)
|
||||
@@ -163,6 +177,13 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte
|
||||
source := r.URL.Query().Get("source")
|
||||
if source == "" {
|
||||
source = config.Server.DefaultSource.Name
|
||||
} else {
|
||||
var err error
|
||||
// decode url encoded source name
|
||||
source, err = url.QueryUnescape(source)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, fmt.Errorf("invalid source encoding: %v", err)
|
||||
}
|
||||
}
|
||||
if !d.user.Permissions.Modify {
|
||||
return http.StatusForbidden, fmt.Errorf("user is not allowed to create or modify")
|
||||
@@ -188,7 +209,7 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte
|
||||
fileInfo, err := files.FileInfoFaster(fileOpts)
|
||||
if err == nil {
|
||||
if r.URL.Query().Get("override") != "true" {
|
||||
logger.Debug(fmt.Sprintf("Resource already exists: %v", fileInfo.RealPath))
|
||||
logger.Debugf("Resource already exists: %v", fileInfo.RealPath)
|
||||
return http.StatusConflict, nil
|
||||
}
|
||||
|
||||
@@ -226,6 +247,13 @@ func resourcePutHandler(w http.ResponseWriter, r *http.Request, d *requestContex
|
||||
source := r.URL.Query().Get("source")
|
||||
if source == "" {
|
||||
source = config.Server.DefaultSource.Name
|
||||
} else {
|
||||
var err error
|
||||
// decode url encoded source name
|
||||
source, err = url.QueryUnescape(source)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, fmt.Errorf("invalid source encoding: %v", err)
|
||||
}
|
||||
}
|
||||
if !d.user.Permissions.Modify {
|
||||
return http.StatusForbidden, fmt.Errorf("user is not allowed to create or modify")
|
||||
@@ -324,7 +352,7 @@ func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestCont
|
||||
// check target dir exists
|
||||
parentDir, _, err := idx.GetRealPath(userscopeDst, filepath.Dir(dst))
|
||||
if err != nil {
|
||||
logger.Debug(fmt.Sprintf("Could not get real path for parent dir: %v %v %v", userscopeDst, filepath.Dir(dst), err))
|
||||
logger.Debugf("Could not get real path for parent dir: %v %v %v", userscopeDst, filepath.Dir(dst), err)
|
||||
return http.StatusNotFound, err
|
||||
}
|
||||
realDest := parentDir + "/" + filepath.Base(dst)
|
||||
@@ -349,7 +377,7 @@ func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestCont
|
||||
}
|
||||
err = patchAction(r.Context(), action, realSrc, realDest, d, isSrcDir, srcIndex, dstIndex)
|
||||
if err != nil {
|
||||
logger.Debug(fmt.Sprintf("Could not run patch action. src=%v dst=%v err=%v", realSrc, realDest, err))
|
||||
logger.Debugf("Could not run patch action. src=%v dst=%v err=%v", realSrc, realDest, err)
|
||||
}
|
||||
return errToStatus(err), err
|
||||
}
|
||||
@@ -404,6 +432,9 @@ func inspectIndex(w http.ResponseWriter, r *http.Request) {
|
||||
source := r.URL.Query().Get("source")
|
||||
if source == "" {
|
||||
source = config.Server.DefaultSource.Name
|
||||
} else {
|
||||
// decode url encoded source name
|
||||
source, _ = url.QueryUnescape(source)
|
||||
}
|
||||
// Decode the URL-encoded path
|
||||
path, _ := url.QueryUnescape(encodedPath)
|
||||
|
||||
@@ -60,6 +60,13 @@ func searchHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i
|
||||
source := r.URL.Query().Get("source")
|
||||
if source == "" {
|
||||
source = config.Server.DefaultSource.Name
|
||||
} else {
|
||||
var err error
|
||||
// decode url encoded source name
|
||||
source, err = url.QueryUnescape(source)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, fmt.Errorf("invalid source encoding: %v", err)
|
||||
}
|
||||
}
|
||||
scope := r.URL.Query().Get("scope")
|
||||
unencodedScope, err := url.QueryUnescape(scope)
|
||||
|
||||
@@ -69,6 +69,13 @@ func shareGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
|
||||
source := r.URL.Query().Get("source")
|
||||
if source == "" {
|
||||
source = settings.Config.Server.DefaultSource.Name
|
||||
} else {
|
||||
var err error
|
||||
// decode url encoded source name
|
||||
source, err = url.QueryUnescape(source)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, fmt.Errorf("invalid source encoding: %v", err)
|
||||
}
|
||||
}
|
||||
// Decode the URL-encoded path
|
||||
path, err := url.QueryUnescape(encodedPath)
|
||||
@@ -192,6 +199,13 @@ func sharePostHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
|
||||
sourceName := r.URL.Query().Get("source")
|
||||
if sourceName == "" {
|
||||
sourceName = config.Server.DefaultSource.Name
|
||||
} else {
|
||||
var err error
|
||||
// decode url encoded source name
|
||||
sourceName, err = url.QueryUnescape(sourceName)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, fmt.Errorf("invalid source encoding: %v", err)
|
||||
}
|
||||
}
|
||||
source := config.Server.NameToSource[sourceName]
|
||||
|
||||
|
||||
@@ -48,17 +48,17 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, file, contentT
|
||||
"StaticURL": config.Server.BaseURL + "static",
|
||||
"Signup": settings.Config.Auth.Methods.PasswordAuth.Signup,
|
||||
"NoAuth": config.Auth.Methods.NoAuth,
|
||||
"PasswordAuth": config.Auth.Methods.PasswordAuth,
|
||||
"LoginPage": auther.LoginPage(),
|
||||
"CSS": false,
|
||||
"EnableThumbs": !config.Server.DisablePreviews,
|
||||
"ExternalLinks": config.Frontend.ExternalLinks,
|
||||
"ExternalUrl": strings.TrimSuffix(config.Server.ExternalUrl, "/"),
|
||||
"OnlyOfficeUrl": settings.Config.Integrations.OnlyOffice.Url,
|
||||
"SourceCount": len(config.Server.Sources),
|
||||
"SourceCount": len(config.Server.SourceMap),
|
||||
"OidcAvailable": config.Auth.Methods.OidcAuth.Enabled,
|
||||
"PasswordAvailable": config.Auth.Methods.PasswordAuth.Enabled,
|
||||
"MediaAvailable": config.Integrations.Media.FfmpegPath != "",
|
||||
"MuPdfAvailable": config.Server.MuPdfAvailable,
|
||||
}
|
||||
|
||||
b, err := json.Marshal(data)
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/auth"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
// generateOTPHandler handles the generation of a new TOTP secret and QR code.
|
||||
// @Summary Generate OTP
|
||||
// @Description Generates a new TOTP secret and QR code for the authenticated user.
|
||||
// @Tags OTP
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {object} map[string]string "OTP secret generated successfully."
|
||||
// @Failure 500 {object} map[string]string "Internal server error"
|
||||
// @Router /api/auth/otp/generate [post]
|
||||
func generateOTPHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
|
||||
logger.Debug("Generating OTP for user:", d.user.Username)
|
||||
url, err := auth.GenerateOtpForUser(d.user, store.Users)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, fmt.Errorf("error generating OTP secret: %w", err)
|
||||
}
|
||||
response := map[string]string{
|
||||
"message": "OTP secret generated successfully.",
|
||||
"url": url, // The otpauth:// URL for QR code generation
|
||||
}
|
||||
return renderJSON(w, r, response)
|
||||
}
|
||||
|
||||
// verifyOTPHandler handles the verification of a TOTP code.
|
||||
// @Summary Verify OTP
|
||||
// @Description Verifies the provided TOTP code for the authenticated user.
|
||||
// @Tags OTP
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security ApiKeyAuth
|
||||
// @Param code query string true "TOTP code to verify"
|
||||
// @Success 200 {object} HttpResponse "OTP token is valid."
|
||||
// @Failure 401 {object} map[string]string "Unauthorized - invalid TOTP token"
|
||||
// @Router /api/auth/otp/verify [post]
|
||||
func verifyOTPHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
|
||||
code := r.Header.Get("X-Secret")
|
||||
if code == "" {
|
||||
return http.StatusUnauthorized, fmt.Errorf("code is required")
|
||||
}
|
||||
err := auth.VerifyTotpCode(d.user, code, store.Users)
|
||||
if err != nil {
|
||||
return http.StatusUnauthorized, fmt.Errorf("invalid OTP token")
|
||||
}
|
||||
response := HttpResponse{
|
||||
Status: http.StatusOK,
|
||||
Message: "OTP token is valid.",
|
||||
}
|
||||
// On success, return a simple confirmation.
|
||||
return renderJSON(w, r, response)
|
||||
}
|
||||
@@ -88,6 +88,9 @@ func userGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (
|
||||
func prepForFrontend(u *users.User) {
|
||||
u.Password = ""
|
||||
u.ApiKeys = nil
|
||||
u.OtpEnabled = u.TOTPSecret != ""
|
||||
u.TOTPSecret = ""
|
||||
u.TOTPNonce = ""
|
||||
u.Scopes = settings.ConvertToFrontendScopes(u.Scopes)
|
||||
}
|
||||
|
||||
@@ -158,7 +161,7 @@ func usersPostHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
|
||||
return http.StatusBadRequest, nil
|
||||
}
|
||||
|
||||
if req.Data.Password == "" {
|
||||
if req.Data.Password == "" && req.Data.LoginMethod == "password" {
|
||||
return http.StatusBadRequest, errors.ErrEmptyPassword
|
||||
}
|
||||
|
||||
@@ -205,6 +208,10 @@ func userPutHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (
|
||||
if err = json.Unmarshal(body, &req); err != nil {
|
||||
return http.StatusBadRequest, err
|
||||
}
|
||||
if !req.Data.OtpEnabled {
|
||||
req.Data.TOTPSecret = ""
|
||||
req.Data.TOTPNonce = ""
|
||||
}
|
||||
|
||||
// Perform the user update
|
||||
err = store.Users.Update(req.Data, d.user.Permissions.Admin, req.Which...)
|
||||
|
||||
@@ -10,13 +10,15 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/cache"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
|
||||
"github.com/gtsteffaniak/go-cache/cache"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
var RealPathCache = cache.NewCache(48*time.Hour, 72*time.Hour)
|
||||
|
||||
// reduced index is json exposed to the client
|
||||
type ReducedIndex struct {
|
||||
IdxName string `json:"name"`
|
||||
@@ -77,7 +79,7 @@ func Initialize(source settings.Source, mock bool) {
|
||||
indexesMutex.Unlock()
|
||||
if !newIndex.Source.Config.Disabled {
|
||||
time.Sleep(time.Second)
|
||||
logger.Info(fmt.Sprintf("initializing index: [%v]", newIndex.Source.Name))
|
||||
logger.Infof("initializing index: [%v]", newIndex.Source.Name)
|
||||
newIndex.RunIndexing("/", false)
|
||||
go newIndex.setupIndexingScanners()
|
||||
} else {
|
||||
@@ -121,7 +123,7 @@ func (idx *Index) indexDirectory(adjustedPath string, quick, recursive bool) err
|
||||
for _, item := range cacheDirItems {
|
||||
err = idx.indexDirectory(combinedPath+item.Name, quick, true)
|
||||
if err != nil {
|
||||
logger.Error(fmt.Sprintf("error indexing directory %v : %v", combinedPath+item.Name, err))
|
||||
logger.Errorf("error indexing directory %v : %v", combinedPath+item.Name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -169,7 +171,7 @@ func (idx *Index) indexDirectory(adjustedPath string, quick, recursive bool) err
|
||||
// Recursively index the subdirectory
|
||||
err = idx.indexDirectory(dirPath, quick, recursive)
|
||||
if err != nil {
|
||||
logger.Error(fmt.Sprintf("Failed to index directory %s: %v", dirPath, err))
|
||||
logger.Errorf("Failed to index directory %s: %v", dirPath, err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
@@ -247,8 +249,8 @@ func (idx *Index) recursiveUpdateDirSizes(childInfo *iteminfo.FileInfo, previous
|
||||
func (idx *Index) GetRealPath(relativePath ...string) (string, bool, error) {
|
||||
combined := append([]string{idx.Source.Path}, relativePath...)
|
||||
joinedPath := filepath.Join(combined...)
|
||||
isDir, _ := cache.RealPath.Get(joinedPath + ":isdir").(bool)
|
||||
cached, ok := cache.RealPath.Get(joinedPath).(string)
|
||||
isDir, _ := RealPathCache.Get(joinedPath + ":isdir").(bool)
|
||||
cached, ok := RealPathCache.Get(joinedPath).(string)
|
||||
if ok && cached != "" {
|
||||
return cached, isDir, nil
|
||||
}
|
||||
@@ -260,8 +262,8 @@ func (idx *Index) GetRealPath(relativePath ...string) (string, bool, error) {
|
||||
// Resolve symlinks and get the real path
|
||||
realPath, isDir, err := utils.ResolveSymlinks(absolutePath)
|
||||
if err == nil {
|
||||
cache.RealPath.Set(joinedPath, realPath)
|
||||
cache.RealPath.Set(joinedPath+":isdir", isDir)
|
||||
RealPathCache.Set(joinedPath, realPath)
|
||||
RealPathCache.Set(joinedPath+":isdir", isDir)
|
||||
}
|
||||
return realPath, isDir, err
|
||||
}
|
||||
|
||||
@@ -2,11 +2,10 @@ package indexing
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/events"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
// schedule in minutes
|
||||
@@ -36,7 +35,7 @@ func (idx *Index) newScanner(origin string) {
|
||||
sleepTime = time.Duration(idx.Source.Config.IndexingInterval) * time.Minute
|
||||
}
|
||||
// Log and sleep before indexing
|
||||
logger.Debug(fmt.Sprintf("Next scan in %v", sleepTime))
|
||||
logger.Debugf("Next scan in %v", sleepTime)
|
||||
time.Sleep(sleepTime)
|
||||
if fullScanCounter == 5 {
|
||||
idx.RunIndexing(origin, false) // Full scan
|
||||
@@ -64,7 +63,7 @@ func (idx *Index) PostScan() {
|
||||
func (idx *Index) UpdateSchedule() {
|
||||
// Adjust schedule based on file changes
|
||||
if idx.FilesChangedDuringIndexing {
|
||||
logger.Debug(fmt.Sprintf("Files changed during indexing [%v], adjusting schedule.", idx.Name))
|
||||
logger.Debugf("Files changed during indexing [%v], adjusting schedule.", idx.Name)
|
||||
// Move to at least the full-scan anchor or reduce interval
|
||||
if idx.CurrentSchedule > fullScanAnchor {
|
||||
idx.CurrentSchedule = fullScanAnchor
|
||||
@@ -95,7 +94,7 @@ func (idx *Index) SendSourceUpdateEvent() {
|
||||
}
|
||||
reducedIndex, err := GetIndexInfo(idx.Name)
|
||||
if err != nil {
|
||||
logger.Error(fmt.Sprintf("Error getting index info: %v", err))
|
||||
logger.Errorf("Error getting index info: %v", err)
|
||||
return
|
||||
}
|
||||
sourceAsMap := map[string]ReducedIndex{
|
||||
@@ -103,7 +102,7 @@ func (idx *Index) SendSourceUpdateEvent() {
|
||||
}
|
||||
message, err := json.Marshal(sourceAsMap)
|
||||
if err != nil {
|
||||
logger.Error(fmt.Sprintf("Error marshalling source update message: %v", err))
|
||||
logger.Errorf("Error marshalling source update message: %v", err)
|
||||
return
|
||||
}
|
||||
events.SendSourceUpdate(idx.Name, string(message))
|
||||
@@ -114,9 +113,9 @@ func (idx *Index) RunIndexing(origin string, quick bool) {
|
||||
prevNumDirs := idx.NumDirs
|
||||
prevNumFiles := idx.NumFiles
|
||||
if quick {
|
||||
logger.Debug(fmt.Sprintf("Starting quick scan for [%v]", idx.Source.Name))
|
||||
logger.Debugf("Starting quick scan for [%v]", idx.Source.Name)
|
||||
} else {
|
||||
logger.Debug(fmt.Sprintf("Starting full scan for [%v]", idx.Source.Name))
|
||||
logger.Debugf("Starting full scan for [%v]", idx.Source.Name)
|
||||
idx.NumDirs = 0
|
||||
idx.NumFiles = 0
|
||||
}
|
||||
@@ -125,7 +124,7 @@ func (idx *Index) RunIndexing(origin string, quick bool) {
|
||||
// Perform the indexing operation
|
||||
err := idx.indexDirectory("/", quick, true)
|
||||
if err != nil {
|
||||
logger.Error(fmt.Sprintf("Error during indexing: %v", err))
|
||||
logger.Errorf("Error during indexing: %v", err)
|
||||
}
|
||||
firstRun := idx.LastIndexed == time.Time{}
|
||||
// Update the LastIndexed time
|
||||
@@ -133,7 +132,7 @@ func (idx *Index) RunIndexing(origin string, quick bool) {
|
||||
idx.LastIndexedUnix = idx.LastIndexed.Unix()
|
||||
if quick {
|
||||
idx.QuickScanTime = int(time.Since(startTime).Seconds())
|
||||
logger.Debug(fmt.Sprintf("Time spent indexing [%v]: %v seconds", idx.Source.Name, idx.QuickScanTime))
|
||||
logger.Debugf("Time spent indexing [%v]: %v seconds", idx.Source.Name, idx.QuickScanTime)
|
||||
} else {
|
||||
idx.FullScanTime = int(time.Since(startTime).Seconds())
|
||||
// update smart indexing
|
||||
@@ -148,14 +147,14 @@ func (idx *Index) RunIndexing(origin string, quick bool) {
|
||||
idx.Assessment = "normal"
|
||||
}
|
||||
if firstRun {
|
||||
logger.Info(fmt.Sprintf("Index assessment : [%v] complexity=%v directories=%v files=%v", idx.Source.Name, idx.Assessment, idx.NumDirs, idx.NumFiles))
|
||||
logger.Infof("Index assessment : [%v] complexity=%v directories=%v files=%v", idx.Source.Name, idx.Assessment, idx.NumDirs, idx.NumFiles)
|
||||
} else {
|
||||
logger.Debug(fmt.Sprintf("Index assessment : [%v] complexity=%v directories=%v files=%v", idx.Source.Name, idx.Assessment, idx.NumDirs, idx.NumFiles))
|
||||
logger.Debugf("Index assessment : [%v] complexity=%v directories=%v files=%v", idx.Source.Name, idx.Assessment, idx.NumDirs, idx.NumFiles)
|
||||
}
|
||||
if idx.NumDirs != prevNumDirs || idx.NumFiles != prevNumFiles {
|
||||
idx.FilesChangedDuringIndexing = true
|
||||
}
|
||||
logger.Debug(fmt.Sprintf("Time spent indexing [%v]: %v seconds", idx.Source.Name, idx.FullScanTime))
|
||||
logger.Debugf("Time spent indexing [%v]: %v seconds", idx.Source.Name, idx.FullScanTime)
|
||||
}
|
||||
|
||||
idx.PostScan()
|
||||
|
||||
@@ -20,6 +20,24 @@ var AllFiletypeOptions = []string{
|
||||
"text",
|
||||
}
|
||||
|
||||
var MuPdfConvertable = []string{
|
||||
".pdf", // PDF
|
||||
".xps", // XPS
|
||||
".epub", // EPUB
|
||||
".mobi", // MOBI
|
||||
".fb2", // FB2
|
||||
".cbz", // CBZ
|
||||
".svg", // SVG
|
||||
".txt", // TXT
|
||||
".docx", // DOCX
|
||||
".ppt", // PPT
|
||||
".pptx", // PPTX
|
||||
".xlsx", // XLSX
|
||||
".hwp", // HWP
|
||||
".hwp", // HWPX
|
||||
".md", // Markdown
|
||||
}
|
||||
|
||||
// Known bundle-style extensions that are technically directories but treated as files
|
||||
var BundleExtensions = []string{
|
||||
".app", // macOS application bundle
|
||||
@@ -355,3 +373,19 @@ func hasBundleExtension(name string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func HasDocConvertableExtension(name, mimetype string) bool {
|
||||
if !settings.Config.Server.MuPdfAvailable {
|
||||
return false
|
||||
}
|
||||
if strings.HasPrefix(mimetype, "text") {
|
||||
return true
|
||||
}
|
||||
ext := strings.ToLower(filepath.Ext(name))
|
||||
for _, e := range MuPdfConvertable {
|
||||
if ext == e {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
// detects subtitles for video files.
|
||||
|
||||
@@ -4,10 +4,10 @@ import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/cache"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
|
||||
"github.com/shirou/gopsutil/v3/disk"
|
||||
)
|
||||
@@ -87,11 +87,11 @@ func GetIndex(name string) *Index {
|
||||
// todo: update everywhere else so this isn't needed.
|
||||
source, ok := settings.Config.Server.SourceMap[name]
|
||||
if !ok {
|
||||
logger.Error(fmt.Sprintf("index %s not found", name))
|
||||
logger.Errorf("index %s not found", name)
|
||||
}
|
||||
index, ok = indexes[source.Name]
|
||||
if !ok {
|
||||
logger.Error(fmt.Sprintf("index %s not found", name))
|
||||
logger.Errorf("index %s not found", name)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -105,11 +105,11 @@ func GetIndexInfo(sourceName string) (ReducedIndex, error) {
|
||||
}
|
||||
sourcePath := idx.Path
|
||||
cacheKey := "usageCache-" + sourceName
|
||||
_, ok = cache.DiskUsage.Get(cacheKey).(bool)
|
||||
_, ok = utils.DiskUsageCache.Get(cacheKey).(bool)
|
||||
if !ok {
|
||||
usage, err := disk.Usage(sourcePath)
|
||||
if err != nil {
|
||||
logger.Error(fmt.Sprintf("error getting disk usage for %s: %v", sourcePath, err))
|
||||
logger.Errorf("error getting disk usage for %s: %v", sourcePath, err)
|
||||
idx.SetStatus(UNAVAILABLE)
|
||||
return ReducedIndex{}, fmt.Errorf("error getting disk usage for %s: %v", sourcePath, err)
|
||||
}
|
||||
@@ -118,7 +118,7 @@ func GetIndexInfo(sourceName string) (ReducedIndex, error) {
|
||||
Used: usage.Used,
|
||||
}
|
||||
idx.SetUsage(latestUsage)
|
||||
cache.DiskUsage.Set(cacheKey, true)
|
||||
utils.DiskUsageCache.Set(cacheKey, true)
|
||||
}
|
||||
return idx.ReducedIndex, nil
|
||||
}
|
||||
@@ -5,12 +5,15 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/cache"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
|
||||
"github.com/gtsteffaniak/go-cache/cache"
|
||||
)
|
||||
|
||||
var SearchResultsCache = cache.NewCache(15 * time.Second)
|
||||
|
||||
var (
|
||||
sessionInProgress sync.Map
|
||||
maxSearchResults = 100
|
||||
@@ -34,12 +37,12 @@ func (idx *Index) Search(search string, scope string, sourceSession string) []Se
|
||||
results := make(map[string]SearchResult, 0)
|
||||
count := 0
|
||||
var directories []string
|
||||
cachedDirs, ok := cache.SearchResults.Get(idx.Source.Path + scope).([]string)
|
||||
cachedDirs, ok := SearchResultsCache.Get(idx.Source.Path + scope).([]string)
|
||||
if ok {
|
||||
directories = cachedDirs
|
||||
} else {
|
||||
directories = idx.getDirsInScope(scope)
|
||||
cache.SearchResults.Set(idx.Source.Path+scope, directories)
|
||||
SearchResultsCache.Set(idx.Source.Path+scope, directories)
|
||||
}
|
||||
for _, searchTerm := range searchOptions.Terms {
|
||||
if searchTerm == "" {
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
//go:build mupdf
|
||||
// +build mupdf
|
||||
|
||||
package preview
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"image/jpeg"
|
||||
"io"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/gen2brain/go-fitz"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
|
||||
)
|
||||
|
||||
func docEnabled() bool {
|
||||
// This function checks if the PDF support is enabled.
|
||||
// In a real implementation, this might check a build tag or configuration.
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Service) GenerateImageFromDoc(file iteminfo.ExtendedFileInfo, tempFilePath string, pageNumber int) ([]byte, error) {
|
||||
// 1. Serialize access to the entire go-fitz operation block
|
||||
s.docGenMutex.Lock()
|
||||
defer s.docGenMutex.Unlock()
|
||||
|
||||
// 2. Lock the current goroutine to a single OS thread for CGo calls
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
|
||||
docPath := file.RealPath
|
||||
// copy file to a temporary location if needed
|
||||
if strings.HasPrefix(file.Type, "text") && !strings.HasSuffix(file.RealPath, ".txt") {
|
||||
originalFile, err := os.Open(file.RealPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("text snippet: failed to open original file '%s': %w", file.RealPath, err)
|
||||
}
|
||||
defer originalFile.Close() // Ensure original file is closed
|
||||
|
||||
buffer := make([]byte, 1024) // Buffer for up to 1KB
|
||||
n, readErr := originalFile.Read(buffer)
|
||||
if readErr != nil && readErr != io.EOF { // io.EOF is not an error if some bytes were read
|
||||
return nil, fmt.Errorf("text snippet: failed to read from original file '%s': %w", file.RealPath, readErr)
|
||||
}
|
||||
|
||||
if n == 0 {
|
||||
return nil, fmt.Errorf("text snippet: original file '%s' is empty or unreadable", file.RealPath)
|
||||
} else {
|
||||
tempFile, err := os.Create(tempFilePath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("text snippet: failed to create temporary file '%s': %w", tempFilePath, err)
|
||||
}
|
||||
defer os.Remove(tempFilePath) // Ensure cleanup on error
|
||||
// Write the read content (up to 1KB or EOF) to the temporary file
|
||||
if _, err := tempFile.Write(buffer[:n]); err != nil {
|
||||
tempFile.Close() // Attempt to close
|
||||
os.Remove(tempFilePath) // Clean up on error
|
||||
return nil, fmt.Errorf("text snippet: failed to write to temporary file '%s': %w", tempFilePath, err)
|
||||
}
|
||||
|
||||
// Close the temporary file so it can be reliably opened by path by other processes/functions
|
||||
if err := tempFile.Close(); err != nil {
|
||||
os.Remove(tempFilePath) // Clean up on error
|
||||
return nil, fmt.Errorf("text snippet: failed to close temporary file '%s': %w", tempFilePath, err)
|
||||
}
|
||||
|
||||
docPath = tempFilePath // Update docPath to point to the new temporary text snippet file
|
||||
}
|
||||
}
|
||||
doc, err := fitz.New(docPath) // This calls the CGo version
|
||||
if err != nil {
|
||||
// The error message you received: "failed to open PDF: fitz: cannot open memory"
|
||||
return nil, fmt.Errorf("failed to open PDF from memory for file '%s': %w", docPath, err)
|
||||
}
|
||||
defer doc.Close()
|
||||
|
||||
// Get the image from the doc page
|
||||
// Ensure pageNumber is valid (e.g., >= 0 for 0-indexed or >= 1 for 1-indexed, check go-fitz docs)
|
||||
// And pageNumber < doc.NumPage()
|
||||
numPages := doc.NumPage()
|
||||
if pageNumber < 0 || pageNumber >= numPages { // Assuming 0-indexed for Image()
|
||||
return nil, fmt.Errorf("invalid page number %d for PDF with %d pages ('%s')", pageNumber, numPages, docPath)
|
||||
}
|
||||
|
||||
img, err := doc.Image(pageNumber)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get image from page %d of '%s': %w", pageNumber, docPath, err)
|
||||
}
|
||||
|
||||
// Create a new buffer to hold the image bytes
|
||||
var buf bytes.Buffer
|
||||
|
||||
// Encode the image directly into the buffer
|
||||
err = jpeg.Encode(&buf, img, &jpeg.Options{Quality: jpeg.DefaultQuality})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to encode image to jpeg for '%s': %w", docPath, err)
|
||||
}
|
||||
|
||||
// Return the byte slice from the buffer
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
//go:build !mupdf
|
||||
// +build !mupdf
|
||||
|
||||
package preview
|
||||
|
||||
import "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
|
||||
|
||||
func docEnabled() bool {
|
||||
// This function checks if the PDF support is enabled.
|
||||
// In a real implementation, this might check a build tag or configuration.
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Service) GenerateImageFromDoc(file iteminfo.ExtendedFileInfo, tempFilePath string, pageNumber int) ([]byte, error) { // 1. Serialize access to the entire go-fitz operation block
|
||||
s.docGenMutex.Lock()
|
||||
defer s.docGenMutex.Unlock()
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"image"
|
||||
"io"
|
||||
|
||||
"github.com/disintegration/imaging"
|
||||
"github.com/kovidgoyal/imaging"
|
||||
exif "github.com/dsoprea/go-exif/v3"
|
||||
exifcommon "github.com/dsoprea/go-exif/v3/common"
|
||||
)
|
||||
@@ -119,8 +119,8 @@ func WithQuality(quality Quality) Option {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) Resize(ctx context.Context, in io.Reader, width, height int, out io.Writer, options ...Option) error {
|
||||
if err := s.acquire(ctx); err != nil {
|
||||
func (s *Service) Resize(in io.Reader, width, height int, out io.Writer, options ...Option) error {
|
||||
if err := s.acquire(context.Background()); err != nil {
|
||||
return err
|
||||
}
|
||||
defer s.release()
|
||||
|
||||
@@ -2,7 +2,6 @@ package preview
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"image"
|
||||
"image/gif"
|
||||
@@ -277,12 +276,12 @@ func TestService_Resize(t *testing.T) {
|
||||
|
||||
for name, test := range testCases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
svc := New(1, "", "")
|
||||
svc := NewPreviewGenerator(1, "", "")
|
||||
source := test.source(t)
|
||||
defer source.Close()
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
err := svc.Resize(context.Background(), source, test.width, test.height, buf, test.options...)
|
||||
err := svc.Resize(source, test.width, test.height, buf, test.options...)
|
||||
if (err != nil) != test.wantErr {
|
||||
t.Fatalf("GetMarketSpecs() error = %v, wantErr %v", err, test.wantErr)
|
||||
}
|
||||
@@ -435,7 +434,7 @@ func TestService_FormatFromExtension(t *testing.T) {
|
||||
|
||||
for name, test := range testCases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
svc := New(1, "", "")
|
||||
svc := NewPreviewGenerator(1, "", "")
|
||||
got, err := svc.FormatFromExtension(test.ext)
|
||||
require.Truef(t, errors.Is(err, test.wantErr), "error = %v, wantErr %v", err, test.wantErr)
|
||||
if err != nil {
|
||||
|
||||
@@ -2,6 +2,7 @@ package preview
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -21,6 +22,10 @@ type officePreviewResponse struct {
|
||||
|
||||
// GenerateOfficePreview generates a preview for an office document using OnlyOffice.
|
||||
func (s *Service) GenerateOfficePreview(filetype, key, title, url string) ([]byte, error) {
|
||||
if err := s.acquire(context.Background()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer s.release()
|
||||
data := []byte{}
|
||||
// Create the request payload
|
||||
requestPayload := map[string]interface{}{
|
||||
|
||||
+119
-70
@@ -3,6 +3,8 @@ package preview
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
@@ -10,12 +12,13 @@ import (
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/diskcache"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/logger"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -29,9 +32,11 @@ type Service struct {
|
||||
ffmpegPath string
|
||||
ffprobePath string
|
||||
fileCache diskcache.Interface
|
||||
debug bool
|
||||
docGenMutex sync.Mutex // Mutex to serialize access to doc generation
|
||||
}
|
||||
|
||||
func New(concurrencyLimit int, ffmpegPath string, cacheDir string) *Service {
|
||||
func NewPreviewGenerator(concurrencyLimit int, ffmpegPath string, cacheDir string) *Service {
|
||||
var fileCache diskcache.Interface
|
||||
// Use file cache if cacheDir is specified
|
||||
if cacheDir != "" {
|
||||
@@ -41,61 +46,81 @@ func New(concurrencyLimit int, ffmpegPath string, cacheDir string) *Service {
|
||||
if cacheDir == "tmp" {
|
||||
logger.Error("The cache dir could not be created. Make sure the user that you executed the program with has access to create directories in the local path. filebrowser is trying to use the default `server.cacheDir: tmp` , but you can change this location if you need to. Please see configuration wiki for more information about this error. https://github.com/gtsteffaniak/filebrowser/wiki/Configuration")
|
||||
}
|
||||
logger.Fatal(fmt.Sprintf("failed to create file cache path, which is now require to run the server: %v", err))
|
||||
logger.Fatalf("failed to create file cache path, which is now require to run the server: %v", err)
|
||||
}
|
||||
} else {
|
||||
// No-op cache if no cacheDir is specified
|
||||
fileCache = diskcache.NewNoOp()
|
||||
}
|
||||
ffprobePath := ""
|
||||
ffmpegMainPath := ""
|
||||
var err error
|
||||
if ffmpegPath != "" {
|
||||
ffmpegMainPath, err = CheckValidFFmpeg(ffmpegPath)
|
||||
if err != nil {
|
||||
logger.Fatal(fmt.Sprintf("the configured ffmpeg path does not contain a valid ffmpeg binary %s, err: %v", ffmpegPath, err))
|
||||
}
|
||||
ffprobePath, err = CheckValidFFprobe(ffmpegPath)
|
||||
if err != nil {
|
||||
logger.Fatal(fmt.Sprintf("the configured ffmpeg path is not a valid ffprobe binary %s, err: %v", ffmpegPath, err))
|
||||
}
|
||||
// Create directories recursively with 0755 permissions
|
||||
err := os.MkdirAll(filepath.Join(settings.Config.Server.CacheDir, "thumbnails", "docs"), 0755)
|
||||
if err != nil {
|
||||
logger.Error(err)
|
||||
}
|
||||
err = os.MkdirAll(filepath.Join(settings.Config.Server.CacheDir, "thumbnails", "videos"), 0755)
|
||||
if err != nil {
|
||||
logger.Error(err)
|
||||
}
|
||||
ffmpegMainPath, err := CheckValidFFmpeg(ffmpegPath)
|
||||
if err != nil && ffmpegPath != "" {
|
||||
logger.Fatalf("the configured ffmpeg path does not contain a valid ffmpeg binary %s, err: %v", ffmpegPath, err)
|
||||
}
|
||||
ffprobePath, errprobe := CheckValidFFprobe(ffmpegPath)
|
||||
if errprobe != nil && ffmpegPath != "" {
|
||||
logger.Fatalf("the configured ffmpeg path is not a valid ffprobe binary %s, err: %v", ffmpegPath, err)
|
||||
}
|
||||
if errprobe == nil && err == nil {
|
||||
logger.Infof("Media Enabled : %v", errprobe == nil)
|
||||
settings.Config.Integrations.Media.FfmpegPath = filepath.Base(ffmpegMainPath)
|
||||
}
|
||||
settings.Config.Server.MuPdfAvailable = docEnabled()
|
||||
return &Service{
|
||||
sem: make(chan struct{}, concurrencyLimit),
|
||||
ffmpegPath: ffmpegMainPath,
|
||||
ffprobePath: ffprobePath,
|
||||
fileCache: fileCache,
|
||||
debug: settings.Config.Server.DebugMedia,
|
||||
}
|
||||
}
|
||||
|
||||
func Start(concurrencyLimit int, ffmpegPath, cacheDir string) error {
|
||||
service = New(concurrencyLimit, ffmpegPath, cacheDir)
|
||||
func StartPreviewGenerator(concurrencyLimit int, ffmpegPath, cacheDir string) error {
|
||||
service = NewPreviewGenerator(concurrencyLimit, ffmpegPath, cacheDir)
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetPreviewForFile(file iteminfo.ExtendedFileInfo, previewSize, rawUrl string) ([]byte, error) {
|
||||
func GetPreviewForFile(file iteminfo.ExtendedFileInfo, previewSize, url string, seekPercentage int) ([]byte, error) {
|
||||
if !AvailablePreview(file) {
|
||||
return nil, ErrUnsupportedMedia
|
||||
}
|
||||
cacheKey := CacheKey(file.RealPath, previewSize, file.ItemInfo.ModTime)
|
||||
cacheKey := CacheKey(file.RealPath, previewSize, file.ItemInfo.ModTime, seekPercentage)
|
||||
if data, found, err := service.fileCache.Load(context.Background(), cacheKey); err != nil {
|
||||
return nil, fmt.Errorf("failed to load from cache: %w", err)
|
||||
} else if found {
|
||||
return data, nil
|
||||
}
|
||||
return GeneratePreview(file, previewSize, rawUrl)
|
||||
|
||||
return GeneratePreview(file, previewSize, url, seekPercentage)
|
||||
}
|
||||
|
||||
func GeneratePreview(file iteminfo.ExtendedFileInfo, previewSize, rawUrl string) ([]byte, error) {
|
||||
func GeneratePreview(file iteminfo.ExtendedFileInfo, previewSize, officeUrl string, seekPercentage int) ([]byte, error) {
|
||||
ext := strings.ToLower(filepath.Ext(file.Name))
|
||||
var (
|
||||
err error
|
||||
imageBytes []byte
|
||||
)
|
||||
|
||||
// Generate thumbnail image from video
|
||||
hasher := md5.New() //nolint:gosec
|
||||
_, _ = hasher.Write([]byte(CacheKey(file.RealPath, previewSize, file.ItemInfo.ModTime, seekPercentage)))
|
||||
hash := hex.EncodeToString(hasher.Sum(nil))
|
||||
// Generate an image from office document
|
||||
if file.OnlyOfficeId != "" {
|
||||
imageBytes, err = service.GenerateOfficePreview(filepath.Ext(file.Name), file.OnlyOfficeId, file.Name, rawUrl)
|
||||
if iteminfo.HasDocConvertableExtension(file.Name, file.Type) {
|
||||
tempFilePath := filepath.Join(settings.Config.Server.CacheDir, "thumbnails", "docs", hash) + ".txt"
|
||||
imageBytes, err = service.GenerateImageFromDoc(file, tempFilePath, 0) // 0 for the first page
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create image for PDF file: %w", err)
|
||||
}
|
||||
} else if file.OnlyOfficeId != "" {
|
||||
imageBytes, err = service.GenerateOfficePreview(filepath.Ext(file.Name), file.OnlyOfficeId, file.Name, officeUrl)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create image for office file: %w", err)
|
||||
}
|
||||
@@ -106,29 +131,42 @@ func GeneratePreview(file iteminfo.ExtendedFileInfo, previewSize, rawUrl string)
|
||||
return nil, fmt.Errorf("failed to read image file: %w", err)
|
||||
}
|
||||
} else if strings.HasPrefix(file.Type, "video") {
|
||||
// Generate thumbnail image from video
|
||||
outPathPattern := filepath.Join(settings.Config.Server.CacheDir, "thumbnails", "video", CacheKey(file.RealPath, previewSize, file.ItemInfo.ModTime)+".jpg")
|
||||
defer os.Remove(outPathPattern) // cleanup
|
||||
if err = service.GenerateVideoPreview(file.RealPath, outPathPattern); err != nil {
|
||||
return nil, fmt.Errorf("failed to generate video preview: %w", err)
|
||||
if seekPercentage == 0 {
|
||||
seekPercentage = 10
|
||||
}
|
||||
imageBytes, err = os.ReadFile(outPathPattern)
|
||||
outPathPattern := filepath.Join(settings.Config.Server.CacheDir, "thumbnails", "videos", hash) + ".jpg"
|
||||
defer os.Remove(outPathPattern) // cleanup
|
||||
imageBytes, err = service.GenerateVideoPreview(file.RealPath, outPathPattern, seekPercentage)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read video thumbnail: %w", err)
|
||||
return nil, fmt.Errorf("failed to create image for video file: %w", err)
|
||||
}
|
||||
} else {
|
||||
return nil, fmt.Errorf("unsupported media type: %s", ext)
|
||||
}
|
||||
resizedBytes, err := service.CreatePreview(imageBytes, previewSize)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to resize preview image: %w", err)
|
||||
if len(imageBytes) < 100 {
|
||||
return nil, fmt.Errorf("generated image is too small, likely an error occurred: %d bytes", len(imageBytes))
|
||||
}
|
||||
// Cache and return
|
||||
cacheKey := CacheKey(file.RealPath, previewSize, file.ItemInfo.ModTime)
|
||||
if err := service.fileCache.Store(context.Background(), cacheKey, resizedBytes); err != nil {
|
||||
logger.Error(fmt.Sprintf("failed to cache resized image: %v", err))
|
||||
|
||||
if previewSize != "original" {
|
||||
// resize image
|
||||
resizedBytes, err := service.CreatePreview(imageBytes, previewSize)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to resize preview image: %w", err)
|
||||
}
|
||||
// Cache and return
|
||||
cacheKey := CacheKey(file.RealPath, previewSize, file.ItemInfo.ModTime, seekPercentage)
|
||||
if err := service.fileCache.Store(context.Background(), cacheKey, resizedBytes); err != nil {
|
||||
logger.Errorf("failed to cache resized image: %v", err)
|
||||
}
|
||||
return resizedBytes, nil
|
||||
} else {
|
||||
cacheKey := CacheKey(file.RealPath, previewSize, file.ItemInfo.ModTime, seekPercentage)
|
||||
if err := service.fileCache.Store(context.Background(), cacheKey, imageBytes); err != nil {
|
||||
logger.Errorf("failed to cache resized image: %v", err)
|
||||
}
|
||||
return imageBytes, nil
|
||||
}
|
||||
return resizedBytes, nil
|
||||
|
||||
}
|
||||
|
||||
func (s *Service) CreatePreview(data []byte, previewSize string) ([]byte, error) {
|
||||
@@ -140,7 +178,7 @@ func (s *Service) CreatePreview(data []byte, previewSize string) ([]byte, error)
|
||||
|
||||
switch previewSize {
|
||||
case "large":
|
||||
width, height = 512, 512
|
||||
width, height = 640, 640
|
||||
options = []Option{WithMode(ResizeModeFit), WithQuality(QualityHigh), WithFormat(FormatJpeg)}
|
||||
case "small":
|
||||
width, height = 256, 256
|
||||
@@ -152,23 +190,23 @@ func (s *Service) CreatePreview(data []byte, previewSize string) ([]byte, error)
|
||||
input := bytes.NewReader(data)
|
||||
output := &bytes.Buffer{}
|
||||
|
||||
if err := s.Resize(context.Background(), input, width, height, output, options...); err != nil {
|
||||
if err := s.Resize(input, width, height, output, options...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return output.Bytes(), nil
|
||||
}
|
||||
|
||||
func CacheKey(realPath, previewSize string, modTime time.Time) string {
|
||||
return fmt.Sprintf("%x%x%x", realPath, modTime.Unix(), previewSize)
|
||||
func CacheKey(realPath, previewSize string, modTime time.Time, percentage int) string {
|
||||
return fmt.Sprintf("%x%x%x%x", realPath, modTime.Unix(), previewSize, percentage)
|
||||
}
|
||||
|
||||
func DelThumbs(ctx context.Context, file iteminfo.ExtendedFileInfo) {
|
||||
errSmall := service.fileCache.Delete(ctx, CacheKey(file.RealPath, "small", file.ItemInfo.ModTime))
|
||||
errSmall := service.fileCache.Delete(ctx, CacheKey(file.RealPath, "small", file.ItemInfo.ModTime, 0))
|
||||
if errSmall != nil {
|
||||
errLarge := service.fileCache.Delete(ctx, CacheKey(file.RealPath, "large", file.ItemInfo.ModTime))
|
||||
errLarge := service.fileCache.Delete(ctx, CacheKey(file.RealPath, "large", file.ItemInfo.ModTime, 0))
|
||||
if errLarge != nil {
|
||||
logger.Debug(fmt.Sprintf("Could not delete thumbnail: %v", file.Name))
|
||||
logger.Debugf("Could not delete thumbnail: %v", file.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -177,10 +215,7 @@ func AvailablePreview(file iteminfo.ExtendedFileInfo) bool {
|
||||
if strings.HasPrefix(file.Type, "video") && service.ffmpegPath != "" {
|
||||
return true
|
||||
}
|
||||
if file.OnlyOfficeId != "" {
|
||||
return true
|
||||
}
|
||||
if file.Type == "application/pdf" {
|
||||
if iteminfo.HasDocConvertableExtension(file.Name, file.Type) {
|
||||
return true
|
||||
}
|
||||
ext := strings.ToLower(filepath.Ext(file.Name))
|
||||
@@ -188,33 +223,47 @@ func AvailablePreview(file iteminfo.ExtendedFileInfo) bool {
|
||||
case ".jpg", ".jpeg", ".png", ".bmp", ".tiff":
|
||||
return true
|
||||
}
|
||||
if file.OnlyOfficeId != "" {
|
||||
return true
|
||||
}
|
||||
if file.Type == "application/pdf" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
return file.OnlyOfficeId != ""
|
||||
}
|
||||
|
||||
// CheckValidFFmpeg checks for a valid ffmpeg executable.
|
||||
// If a path is provided, it looks there. Otherwise, it searches the system's PATH.
|
||||
func CheckValidFFmpeg(path string) (string, error) {
|
||||
var exeExt string
|
||||
if runtime.GOOS == "windows" {
|
||||
exeExt = ".exe"
|
||||
}
|
||||
|
||||
ffmpegPath := filepath.Join(path, "ffmpeg"+exeExt)
|
||||
cmd := exec.Command(ffmpegPath, "-version")
|
||||
return ffmpegPath, cmd.Run()
|
||||
return checkExecutable(path, "ffmpeg")
|
||||
}
|
||||
|
||||
// CheckValidFFprobe checks for a valid ffprobe executable.
|
||||
// If a path is provided, it looks there. Otherwise, it searches the system's PATH.
|
||||
func CheckValidFFprobe(path string) (string, error) {
|
||||
var exeExt string
|
||||
return checkExecutable(path, "ffprobe")
|
||||
}
|
||||
|
||||
// checkExecutable is an internal helper function to find and validate an executable.
|
||||
// It checks a specific path if provided, otherwise falls back to searching the system PATH.
|
||||
func checkExecutable(providedPath, execName string) (string, error) {
|
||||
// Add .exe extension for Windows systems
|
||||
if runtime.GOOS == "windows" {
|
||||
exeExt = ".exe"
|
||||
execName += ".exe"
|
||||
}
|
||||
|
||||
ffprobePath := filepath.Join(path, "ffprobe"+exeExt)
|
||||
cmd := exec.Command(ffprobePath, "-version")
|
||||
return ffprobePath, cmd.Run()
|
||||
var finalPath string
|
||||
var err error
|
||||
|
||||
if providedPath != "" {
|
||||
// A path was provided, so we'll use it.
|
||||
finalPath = filepath.Join(providedPath, execName)
|
||||
} else {
|
||||
// No path was provided, so search the system's PATH for the executable.
|
||||
finalPath, err = exec.LookPath(execName)
|
||||
if err != nil {
|
||||
// The executable was not found in the system's PATH.
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
// Verify the executable is valid by running the "-version" command.
|
||||
cmd := exec.Command(finalPath, "-version")
|
||||
err = cmd.Run()
|
||||
|
||||
return finalPath, err
|
||||
}
|
||||
+48
-19
@@ -2,47 +2,71 @@ package preview
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
// GenerateVideoPreview generates a single preview image from a video using ffmpeg.
|
||||
// videoPath: path to the input video file.
|
||||
// outputPath: path where the generated preview image will be saved (e.g., "/tmp/preview.jpg").
|
||||
// seekTime: how many seconds into the video to seek before capturing the frame.
|
||||
func (s *Service) GenerateVideoPreview(videoPath, outputPath string) error {
|
||||
// Step 1: Get video stream duration (v:0)
|
||||
func (s *Service) GenerateVideoPreview(videoPath, outputPath string, percentageSeek int) ([]byte, error) {
|
||||
if err := s.acquire(context.Background()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer s.release()
|
||||
// Step 1: Get video duration from the container format
|
||||
probeCmd := exec.Command(
|
||||
s.ffprobePath,
|
||||
"-v", "error",
|
||||
"-select_streams", "v:0",
|
||||
"-show_entries", "stream=duration",
|
||||
// Use format=duration for better compatibility
|
||||
"-show_entries", "format=duration",
|
||||
"-of", "default=noprint_wrappers=1:nokey=1",
|
||||
videoPath,
|
||||
)
|
||||
|
||||
var probeOut bytes.Buffer
|
||||
probeCmd.Stdout = &probeOut
|
||||
//probeCmd.Stderr = os.Stderr
|
||||
|
||||
if s.debug {
|
||||
probeCmd.Stderr = os.Stderr
|
||||
}
|
||||
if err := probeCmd.Run(); err != nil {
|
||||
return fmt.Errorf("ffprobe failed: %w", err)
|
||||
logger.Errorf("ffprobe command failed on file '%v' : %v", videoPath, err)
|
||||
return nil, fmt.Errorf("ffprobe failed: %w", err)
|
||||
}
|
||||
|
||||
durationStr := strings.TrimSpace(probeOut.String())
|
||||
durationFloat, err := strconv.ParseFloat(durationStr, 64)
|
||||
if err != nil || durationFloat <= 0 {
|
||||
return fmt.Errorf("invalid duration: %v", err)
|
||||
if durationStr == "" || durationStr == "N/A" {
|
||||
logger.Errorf("could not determine video duration for file '%v' using duration info '%v'", videoPath, durationStr)
|
||||
return nil, fmt.Errorf("could not determine video duration")
|
||||
}
|
||||
|
||||
// Step 2: Truncate and compute 10% of video length
|
||||
duration := int(durationFloat)
|
||||
seekSeconds := duration / 10
|
||||
seekTime := strconv.Itoa(seekSeconds)
|
||||
durationFloat, err := strconv.ParseFloat(durationStr, 64)
|
||||
if err != nil {
|
||||
// The original error you saw would be caught here if "N/A" was still the output
|
||||
return nil, fmt.Errorf("invalid duration: %v", err)
|
||||
}
|
||||
|
||||
// Step 3: Extract frame at seek time
|
||||
if durationFloat <= 0 {
|
||||
return nil, fmt.Errorf("video duration must be positive")
|
||||
}
|
||||
|
||||
// The rest of your function remains the same...
|
||||
// Step 2: Get the duration of the video in whole seconds
|
||||
duration := int(durationFloat)
|
||||
|
||||
// Step 3: Calculate seek time based on percentageSeek (percentage value)
|
||||
seekSeconds := duration * percentageSeek / 100
|
||||
|
||||
// Step 4: Convert seekSeconds to string for ffmpeg command
|
||||
seekTime := strconv.Itoa(seekSeconds)
|
||||
// Step 5: Extract frame at seek time
|
||||
cmd := exec.Command(
|
||||
s.ffmpegPath,
|
||||
"-ss", seekTime,
|
||||
@@ -53,8 +77,13 @@ func (s *Service) GenerateVideoPreview(videoPath, outputPath string) error {
|
||||
outputPath,
|
||||
)
|
||||
|
||||
//cmd.Stdout = os.Stdout
|
||||
//cmd.Stderr = os.Stderr
|
||||
|
||||
return cmd.Run()
|
||||
if s.debug {
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
}
|
||||
err = cmd.Run()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ffmpeg command failed on file '%v' : %w", videoPath, err)
|
||||
}
|
||||
return os.ReadFile(outputPath)
|
||||
}
|
||||
+200
-29
@@ -15,6 +15,109 @@ const docTemplate = `{
|
||||
"host": "{{.Host}}",
|
||||
"basePath": "{{.BasePath}}",
|
||||
"paths": {
|
||||
"/api/auth/logout": {
|
||||
"get": {
|
||||
"description": "logs a user out of the application.",
|
||||
"tags": [
|
||||
"Auth"
|
||||
],
|
||||
"summary": "User Logout",
|
||||
"responses": {
|
||||
"302": {
|
||||
"description": "Redirect to redirect URL if configured in oidc config.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/auth/otp/generate": {
|
||||
"post": {
|
||||
"security": [
|
||||
{
|
||||
"ApiKeyAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Generates a new TOTP secret and QR code for the authenticated user.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"OTP"
|
||||
],
|
||||
"summary": "Generate OTP",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OTP secret generated successfully.",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal server error",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/auth/otp/verify": {
|
||||
"post": {
|
||||
"security": [
|
||||
{
|
||||
"ApiKeyAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Verifies the provided TOTP code for the authenticated user.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"OTP"
|
||||
],
|
||||
"summary": "Verify OTP",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "TOTP code to verify",
|
||||
"name": "code",
|
||||
"in": "query",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OTP token is valid.",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/http.HttpResponse"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized - invalid TOTP token",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/createApiKey": {
|
||||
"post": {
|
||||
"description": "Create an API key with specified name, duration, and permissions.",
|
||||
@@ -1653,9 +1756,17 @@ const docTemplate = `{
|
||||
"methods": {
|
||||
"$ref": "#/definitions/settings.LoginMethods"
|
||||
},
|
||||
"resetAdminOnStart": {
|
||||
"description": "if set to true, the admin user will be reset to the default username and password on startup.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"tokenExpirationHours": {
|
||||
"description": "the number of hours until the token expires. Default is 2 hours.",
|
||||
"type": "integer"
|
||||
},
|
||||
"totpSecret": {
|
||||
"description": "secret used to encrypt TOTP secrets",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -1762,6 +1873,10 @@ const docTemplate = `{
|
||||
"output": {
|
||||
"description": "output location. (eg. \"stdout\" or \"path/to/file.log\")",
|
||||
"type": "string"
|
||||
},
|
||||
"utc": {
|
||||
"description": "use UTC time in the output instead of local time",
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -1794,19 +1909,7 @@ const docTemplate = `{
|
||||
},
|
||||
"settings.OidcConfig": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"authorizationUrl",
|
||||
"clientId",
|
||||
"clientSecret",
|
||||
"scopes",
|
||||
"tokenUrl",
|
||||
"userInfoUrl"
|
||||
],
|
||||
"properties": {
|
||||
"authorizationUrl": {
|
||||
"description": "authorization URL of the OIDC provider",
|
||||
"type": "string"
|
||||
},
|
||||
"clientId": {
|
||||
"description": "client id of the OIDC application",
|
||||
"type": "string"
|
||||
@@ -1815,28 +1918,28 @@ const docTemplate = `{
|
||||
"description": "client secret of the OIDC application",
|
||||
"type": "string"
|
||||
},
|
||||
"disableVerifyTLS": {
|
||||
"description": "disable TLS verification for the OIDC provider. This is insecure and should only be used for testing.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"enabled": {
|
||||
"description": "whether to enable OIDC authentication",
|
||||
"type": "boolean"
|
||||
},
|
||||
"jwksUrl": {
|
||||
"description": "currently not used by filebrowser",
|
||||
"issuerUrl": {
|
||||
"description": "authorization URL of the OIDC provider",
|
||||
"type": "string"
|
||||
},
|
||||
"logoutRedirectUrl": {
|
||||
"description": "if provider logout url is provided, filebrowser will also redirect to logout url. Custom logout query params are respected.",
|
||||
"type": "string"
|
||||
},
|
||||
"scopes": {
|
||||
"description": "space separated list of scopes to request from the OIDC provider",
|
||||
"type": "string"
|
||||
},
|
||||
"tokenUrl": {
|
||||
"description": "token URL of the OIDC provider",
|
||||
"description": "scopes to request from the OIDC provider",
|
||||
"type": "string"
|
||||
},
|
||||
"userIdentifier": {
|
||||
"description": "optional: which attribute should be used as the username? options: email, username, name, phone_number, sub",
|
||||
"type": "string"
|
||||
},
|
||||
"userInfoUrl": {
|
||||
"description": "user info URL of the OIDC provider",
|
||||
"description": "the user identifier to use for authentication. Default is \"username\", can be \"email\" or \"username\", or \"phone\"",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
@@ -1867,7 +1970,12 @@ const docTemplate = `{
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"enforcedOtp": {
|
||||
"description": "if set to true, TOTP is enforced for all password users users. Otherwise, users can choose to enable TOTP.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"minLength": {
|
||||
"description": "minimum pasword length required.",
|
||||
"type": "integer",
|
||||
"minimum": 5
|
||||
},
|
||||
@@ -1880,7 +1988,7 @@ const docTemplate = `{
|
||||
]
|
||||
},
|
||||
"signup": {
|
||||
"description": "currently not used by filebrowser",
|
||||
"description": "allow signups on login page if enabled -- not secure.",
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
@@ -1898,6 +2006,10 @@ const docTemplate = `{
|
||||
"header": {
|
||||
"description": "required header to use for authentication. Security Warning: FileBrowser blindly accepts the header value as username.",
|
||||
"type": "string"
|
||||
},
|
||||
"logoutRedirectUrl": {
|
||||
"description": "if provider logout url is provided, filebrowser will also redirect to logout url. Custom logout query params are respected.",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -1938,6 +2050,10 @@ const docTemplate = `{
|
||||
"description": "path to the database file",
|
||||
"type": "string"
|
||||
},
|
||||
"debugMedia": {
|
||||
"description": "output ffmpeg stdout for media integration -- careful can produces lots of output!",
|
||||
"type": "boolean"
|
||||
},
|
||||
"disablePreviewResize": {
|
||||
"description": "disable resizing of previews for faster loading over slow connections",
|
||||
"type": "boolean"
|
||||
@@ -1969,7 +2085,7 @@ const docTemplate = `{
|
||||
"type": "integer"
|
||||
},
|
||||
"numImageProcessors": {
|
||||
"description": "number of concurrent image processing jobs",
|
||||
"description": "number of concurrent image processing jobs used to create previews, default is number of cpu cores available.",
|
||||
"type": "integer"
|
||||
},
|
||||
"port": {
|
||||
@@ -2099,48 +2215,69 @@ const docTemplate = `{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"darkMode": {
|
||||
"description": "should dark mode be enabled",
|
||||
"type": "boolean"
|
||||
},
|
||||
"dateFormat": {
|
||||
"description": "when false, the date is relative, when true, the date is an exact timestamp",
|
||||
"type": "boolean"
|
||||
},
|
||||
"disableOfficePreviewExt": {
|
||||
"description": "comma separated list of file extensions to disable office preview for",
|
||||
"type": "string"
|
||||
},
|
||||
"disableOnlyOfficeExt": {
|
||||
"description": "comma separated list of file extensions to disable onlyoffice preview for",
|
||||
"type": "string"
|
||||
},
|
||||
"disableSettings": {
|
||||
"description": "disable the user from viewing the settings page",
|
||||
"type": "boolean"
|
||||
},
|
||||
"gallerySize": {
|
||||
"description": "0-9 - the size of the gallery thumbnails",
|
||||
"type": "integer"
|
||||
},
|
||||
"locale": {
|
||||
"description": "language to use: eg. de, en, or fr",
|
||||
"type": "string"
|
||||
},
|
||||
"lockPassword": {
|
||||
"description": "disable the user from changing their password",
|
||||
"type": "boolean"
|
||||
},
|
||||
"loginMethod": {
|
||||
"description": "login method to use: eg. password, proxy, oidc",
|
||||
"type": "string"
|
||||
},
|
||||
"permissions": {
|
||||
"$ref": "#/definitions/users.Permissions"
|
||||
},
|
||||
"preview": {
|
||||
"$ref": "#/definitions/users.PreviewOptions"
|
||||
"$ref": "#/definitions/users.Preview"
|
||||
},
|
||||
"quickDownload": {
|
||||
"description": "show icon to download in one click",
|
||||
"type": "boolean"
|
||||
},
|
||||
"showHidden": {
|
||||
"description": "show hidden files in the UI. On windows this includes files starting with a dot and windows hidden files",
|
||||
"type": "boolean"
|
||||
},
|
||||
"singleClick": {
|
||||
"description": "open directory on single click, also enables middle click to open in new tab",
|
||||
"type": "boolean"
|
||||
},
|
||||
"stickySidebar": {
|
||||
"description": "keep sidebar open when navigating",
|
||||
"type": "boolean"
|
||||
},
|
||||
"themeColor": {
|
||||
"description": "theme color to use: eg. #ff0000, or var(--red), var(--purple), etc",
|
||||
"type": "string"
|
||||
},
|
||||
"viewMode": {
|
||||
"description": "view mode to use: eg. normal, list, grid, or compact",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
@@ -2242,22 +2379,31 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"users.PreviewOptions": {
|
||||
"users.Preview": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"highQuality": {
|
||||
"description": "generate high quality preview images",
|
||||
"type": "boolean"
|
||||
},
|
||||
"image": {
|
||||
"description": "show real image as icon instead of generic photo icon",
|
||||
"type": "boolean"
|
||||
},
|
||||
"motionVideoPreview": {
|
||||
"description": "show multiple frames for videos in preview when hovering",
|
||||
"type": "boolean"
|
||||
},
|
||||
"office": {
|
||||
"description": "show preview image for office files",
|
||||
"type": "boolean"
|
||||
},
|
||||
"popup": {
|
||||
"description": "show larger popup preview when hovering",
|
||||
"type": "boolean"
|
||||
},
|
||||
"video": {
|
||||
"description": "show preview image for video files",
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
@@ -2294,24 +2440,33 @@ const docTemplate = `{
|
||||
}
|
||||
},
|
||||
"darkMode": {
|
||||
"description": "should dark mode be enabled",
|
||||
"type": "boolean"
|
||||
},
|
||||
"dateFormat": {
|
||||
"description": "when false, the date is relative, when true, the date is an exact timestamp",
|
||||
"type": "boolean"
|
||||
},
|
||||
"disableOfficePreviewExt": {
|
||||
"description": "comma separated list of file extensions to disable office preview for",
|
||||
"type": "string"
|
||||
},
|
||||
"disableOnlyOfficeExt": {
|
||||
"description": "comma separated list of file extensions to disable onlyoffice preview for",
|
||||
"type": "string"
|
||||
},
|
||||
"disableSettings": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"gallerySize": {
|
||||
"description": "0-9 - the size of the gallery thumbnails",
|
||||
"type": "integer"
|
||||
},
|
||||
"id": {
|
||||
"type": "integer"
|
||||
},
|
||||
"locale": {
|
||||
"description": "language to use: eg. de, en, or fr",
|
||||
"type": "string"
|
||||
},
|
||||
"lockPassword": {
|
||||
@@ -2320,6 +2475,10 @@ const docTemplate = `{
|
||||
"loginMethod": {
|
||||
"$ref": "#/definitions/users.LoginMethod"
|
||||
},
|
||||
"otpEnabled": {
|
||||
"description": "true if TOTP is enabled, false otherwise",
|
||||
"type": "boolean"
|
||||
},
|
||||
"password": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -2335,9 +2494,10 @@ const docTemplate = `{
|
||||
"$ref": "#/definitions/users.Permissions"
|
||||
},
|
||||
"preview": {
|
||||
"$ref": "#/definitions/users.PreviewOptions"
|
||||
"$ref": "#/definitions/users.Preview"
|
||||
},
|
||||
"quickDownload": {
|
||||
"description": "show icon to download in one click",
|
||||
"type": "boolean"
|
||||
},
|
||||
"scope": {
|
||||
@@ -2350,24 +2510,35 @@ const docTemplate = `{
|
||||
}
|
||||
},
|
||||
"showHidden": {
|
||||
"description": "show hidden files in the UI. On windows this includes files starting with a dot and windows hidden files",
|
||||
"type": "boolean"
|
||||
},
|
||||
"singleClick": {
|
||||
"description": "open directory on single click, also enables middle click to open in new tab",
|
||||
"type": "boolean"
|
||||
},
|
||||
"sorting": {
|
||||
"$ref": "#/definitions/users.Sorting"
|
||||
},
|
||||
"stickySidebar": {
|
||||
"description": "keep sidebar open when navigating",
|
||||
"type": "boolean"
|
||||
},
|
||||
"themeColor": {
|
||||
"description": "theme color to use: eg. #ff0000, or var(--red), var(--purple), etc",
|
||||
"type": "string"
|
||||
},
|
||||
"totpNonce": {
|
||||
"type": "string"
|
||||
},
|
||||
"totpSecret": {
|
||||
"type": "string"
|
||||
},
|
||||
"username": {
|
||||
"type": "string"
|
||||
},
|
||||
"viewMode": {
|
||||
"description": "view mode to use: eg. normal, list, grid, or compact",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,109 @@
|
||||
"contact": {}
|
||||
},
|
||||
"paths": {
|
||||
"/api/auth/logout": {
|
||||
"get": {
|
||||
"description": "logs a user out of the application.",
|
||||
"tags": [
|
||||
"Auth"
|
||||
],
|
||||
"summary": "User Logout",
|
||||
"responses": {
|
||||
"302": {
|
||||
"description": "Redirect to redirect URL if configured in oidc config.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/auth/otp/generate": {
|
||||
"post": {
|
||||
"security": [
|
||||
{
|
||||
"ApiKeyAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Generates a new TOTP secret and QR code for the authenticated user.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"OTP"
|
||||
],
|
||||
"summary": "Generate OTP",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OTP secret generated successfully.",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal server error",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/auth/otp/verify": {
|
||||
"post": {
|
||||
"security": [
|
||||
{
|
||||
"ApiKeyAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Verifies the provided TOTP code for the authenticated user.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"OTP"
|
||||
],
|
||||
"summary": "Verify OTP",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "TOTP code to verify",
|
||||
"name": "code",
|
||||
"in": "query",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OTP token is valid.",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/http.HttpResponse"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized - invalid TOTP token",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/createApiKey": {
|
||||
"post": {
|
||||
"description": "Create an API key with specified name, duration, and permissions.",
|
||||
@@ -1642,9 +1745,17 @@
|
||||
"methods": {
|
||||
"$ref": "#/definitions/settings.LoginMethods"
|
||||
},
|
||||
"resetAdminOnStart": {
|
||||
"description": "if set to true, the admin user will be reset to the default username and password on startup.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"tokenExpirationHours": {
|
||||
"description": "the number of hours until the token expires. Default is 2 hours.",
|
||||
"type": "integer"
|
||||
},
|
||||
"totpSecret": {
|
||||
"description": "secret used to encrypt TOTP secrets",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -1751,6 +1862,10 @@
|
||||
"output": {
|
||||
"description": "output location. (eg. \"stdout\" or \"path/to/file.log\")",
|
||||
"type": "string"
|
||||
},
|
||||
"utc": {
|
||||
"description": "use UTC time in the output instead of local time",
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -1783,19 +1898,7 @@
|
||||
},
|
||||
"settings.OidcConfig": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"authorizationUrl",
|
||||
"clientId",
|
||||
"clientSecret",
|
||||
"scopes",
|
||||
"tokenUrl",
|
||||
"userInfoUrl"
|
||||
],
|
||||
"properties": {
|
||||
"authorizationUrl": {
|
||||
"description": "authorization URL of the OIDC provider",
|
||||
"type": "string"
|
||||
},
|
||||
"clientId": {
|
||||
"description": "client id of the OIDC application",
|
||||
"type": "string"
|
||||
@@ -1804,28 +1907,28 @@
|
||||
"description": "client secret of the OIDC application",
|
||||
"type": "string"
|
||||
},
|
||||
"disableVerifyTLS": {
|
||||
"description": "disable TLS verification for the OIDC provider. This is insecure and should only be used for testing.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"enabled": {
|
||||
"description": "whether to enable OIDC authentication",
|
||||
"type": "boolean"
|
||||
},
|
||||
"jwksUrl": {
|
||||
"description": "currently not used by filebrowser",
|
||||
"issuerUrl": {
|
||||
"description": "authorization URL of the OIDC provider",
|
||||
"type": "string"
|
||||
},
|
||||
"logoutRedirectUrl": {
|
||||
"description": "if provider logout url is provided, filebrowser will also redirect to logout url. Custom logout query params are respected.",
|
||||
"type": "string"
|
||||
},
|
||||
"scopes": {
|
||||
"description": "space separated list of scopes to request from the OIDC provider",
|
||||
"type": "string"
|
||||
},
|
||||
"tokenUrl": {
|
||||
"description": "token URL of the OIDC provider",
|
||||
"description": "scopes to request from the OIDC provider",
|
||||
"type": "string"
|
||||
},
|
||||
"userIdentifier": {
|
||||
"description": "optional: which attribute should be used as the username? options: email, username, name, phone_number, sub",
|
||||
"type": "string"
|
||||
},
|
||||
"userInfoUrl": {
|
||||
"description": "user info URL of the OIDC provider",
|
||||
"description": "the user identifier to use for authentication. Default is \"username\", can be \"email\" or \"username\", or \"phone\"",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
@@ -1856,7 +1959,12 @@
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"enforcedOtp": {
|
||||
"description": "if set to true, TOTP is enforced for all password users users. Otherwise, users can choose to enable TOTP.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"minLength": {
|
||||
"description": "minimum pasword length required.",
|
||||
"type": "integer",
|
||||
"minimum": 5
|
||||
},
|
||||
@@ -1869,7 +1977,7 @@
|
||||
]
|
||||
},
|
||||
"signup": {
|
||||
"description": "currently not used by filebrowser",
|
||||
"description": "allow signups on login page if enabled -- not secure.",
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
@@ -1887,6 +1995,10 @@
|
||||
"header": {
|
||||
"description": "required header to use for authentication. Security Warning: FileBrowser blindly accepts the header value as username.",
|
||||
"type": "string"
|
||||
},
|
||||
"logoutRedirectUrl": {
|
||||
"description": "if provider logout url is provided, filebrowser will also redirect to logout url. Custom logout query params are respected.",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -1927,6 +2039,10 @@
|
||||
"description": "path to the database file",
|
||||
"type": "string"
|
||||
},
|
||||
"debugMedia": {
|
||||
"description": "output ffmpeg stdout for media integration -- careful can produces lots of output!",
|
||||
"type": "boolean"
|
||||
},
|
||||
"disablePreviewResize": {
|
||||
"description": "disable resizing of previews for faster loading over slow connections",
|
||||
"type": "boolean"
|
||||
@@ -1958,7 +2074,7 @@
|
||||
"type": "integer"
|
||||
},
|
||||
"numImageProcessors": {
|
||||
"description": "number of concurrent image processing jobs",
|
||||
"description": "number of concurrent image processing jobs used to create previews, default is number of cpu cores available.",
|
||||
"type": "integer"
|
||||
},
|
||||
"port": {
|
||||
@@ -2088,48 +2204,69 @@
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"darkMode": {
|
||||
"description": "should dark mode be enabled",
|
||||
"type": "boolean"
|
||||
},
|
||||
"dateFormat": {
|
||||
"description": "when false, the date is relative, when true, the date is an exact timestamp",
|
||||
"type": "boolean"
|
||||
},
|
||||
"disableOfficePreviewExt": {
|
||||
"description": "comma separated list of file extensions to disable office preview for",
|
||||
"type": "string"
|
||||
},
|
||||
"disableOnlyOfficeExt": {
|
||||
"description": "comma separated list of file extensions to disable onlyoffice preview for",
|
||||
"type": "string"
|
||||
},
|
||||
"disableSettings": {
|
||||
"description": "disable the user from viewing the settings page",
|
||||
"type": "boolean"
|
||||
},
|
||||
"gallerySize": {
|
||||
"description": "0-9 - the size of the gallery thumbnails",
|
||||
"type": "integer"
|
||||
},
|
||||
"locale": {
|
||||
"description": "language to use: eg. de, en, or fr",
|
||||
"type": "string"
|
||||
},
|
||||
"lockPassword": {
|
||||
"description": "disable the user from changing their password",
|
||||
"type": "boolean"
|
||||
},
|
||||
"loginMethod": {
|
||||
"description": "login method to use: eg. password, proxy, oidc",
|
||||
"type": "string"
|
||||
},
|
||||
"permissions": {
|
||||
"$ref": "#/definitions/users.Permissions"
|
||||
},
|
||||
"preview": {
|
||||
"$ref": "#/definitions/users.PreviewOptions"
|
||||
"$ref": "#/definitions/users.Preview"
|
||||
},
|
||||
"quickDownload": {
|
||||
"description": "show icon to download in one click",
|
||||
"type": "boolean"
|
||||
},
|
||||
"showHidden": {
|
||||
"description": "show hidden files in the UI. On windows this includes files starting with a dot and windows hidden files",
|
||||
"type": "boolean"
|
||||
},
|
||||
"singleClick": {
|
||||
"description": "open directory on single click, also enables middle click to open in new tab",
|
||||
"type": "boolean"
|
||||
},
|
||||
"stickySidebar": {
|
||||
"description": "keep sidebar open when navigating",
|
||||
"type": "boolean"
|
||||
},
|
||||
"themeColor": {
|
||||
"description": "theme color to use: eg. #ff0000, or var(--red), var(--purple), etc",
|
||||
"type": "string"
|
||||
},
|
||||
"viewMode": {
|
||||
"description": "view mode to use: eg. normal, list, grid, or compact",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
@@ -2231,22 +2368,31 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"users.PreviewOptions": {
|
||||
"users.Preview": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"highQuality": {
|
||||
"description": "generate high quality preview images",
|
||||
"type": "boolean"
|
||||
},
|
||||
"image": {
|
||||
"description": "show real image as icon instead of generic photo icon",
|
||||
"type": "boolean"
|
||||
},
|
||||
"motionVideoPreview": {
|
||||
"description": "show multiple frames for videos in preview when hovering",
|
||||
"type": "boolean"
|
||||
},
|
||||
"office": {
|
||||
"description": "show preview image for office files",
|
||||
"type": "boolean"
|
||||
},
|
||||
"popup": {
|
||||
"description": "show larger popup preview when hovering",
|
||||
"type": "boolean"
|
||||
},
|
||||
"video": {
|
||||
"description": "show preview image for video files",
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
@@ -2283,24 +2429,33 @@
|
||||
}
|
||||
},
|
||||
"darkMode": {
|
||||
"description": "should dark mode be enabled",
|
||||
"type": "boolean"
|
||||
},
|
||||
"dateFormat": {
|
||||
"description": "when false, the date is relative, when true, the date is an exact timestamp",
|
||||
"type": "boolean"
|
||||
},
|
||||
"disableOfficePreviewExt": {
|
||||
"description": "comma separated list of file extensions to disable office preview for",
|
||||
"type": "string"
|
||||
},
|
||||
"disableOnlyOfficeExt": {
|
||||
"description": "comma separated list of file extensions to disable onlyoffice preview for",
|
||||
"type": "string"
|
||||
},
|
||||
"disableSettings": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"gallerySize": {
|
||||
"description": "0-9 - the size of the gallery thumbnails",
|
||||
"type": "integer"
|
||||
},
|
||||
"id": {
|
||||
"type": "integer"
|
||||
},
|
||||
"locale": {
|
||||
"description": "language to use: eg. de, en, or fr",
|
||||
"type": "string"
|
||||
},
|
||||
"lockPassword": {
|
||||
@@ -2309,6 +2464,10 @@
|
||||
"loginMethod": {
|
||||
"$ref": "#/definitions/users.LoginMethod"
|
||||
},
|
||||
"otpEnabled": {
|
||||
"description": "true if TOTP is enabled, false otherwise",
|
||||
"type": "boolean"
|
||||
},
|
||||
"password": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -2324,9 +2483,10 @@
|
||||
"$ref": "#/definitions/users.Permissions"
|
||||
},
|
||||
"preview": {
|
||||
"$ref": "#/definitions/users.PreviewOptions"
|
||||
"$ref": "#/definitions/users.Preview"
|
||||
},
|
||||
"quickDownload": {
|
||||
"description": "show icon to download in one click",
|
||||
"type": "boolean"
|
||||
},
|
||||
"scope": {
|
||||
@@ -2339,24 +2499,35 @@
|
||||
}
|
||||
},
|
||||
"showHidden": {
|
||||
"description": "show hidden files in the UI. On windows this includes files starting with a dot and windows hidden files",
|
||||
"type": "boolean"
|
||||
},
|
||||
"singleClick": {
|
||||
"description": "open directory on single click, also enables middle click to open in new tab",
|
||||
"type": "boolean"
|
||||
},
|
||||
"sorting": {
|
||||
"$ref": "#/definitions/users.Sorting"
|
||||
},
|
||||
"stickySidebar": {
|
||||
"description": "keep sidebar open when navigating",
|
||||
"type": "boolean"
|
||||
},
|
||||
"themeColor": {
|
||||
"description": "theme color to use: eg. #ff0000, or var(--red), var(--purple), etc",
|
||||
"type": "string"
|
||||
},
|
||||
"totpNonce": {
|
||||
"type": "string"
|
||||
},
|
||||
"totpSecret": {
|
||||
"type": "string"
|
||||
},
|
||||
"username": {
|
||||
"type": "string"
|
||||
},
|
||||
"viewMode": {
|
||||
"description": "view mode to use: eg. normal, list, grid, or compact",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,9 +100,16 @@ definitions:
|
||||
type: string
|
||||
methods:
|
||||
$ref: '#/definitions/settings.LoginMethods'
|
||||
resetAdminOnStart:
|
||||
description: if set to true, the admin user will be reset to the default username
|
||||
and password on startup.
|
||||
type: boolean
|
||||
tokenExpirationHours:
|
||||
description: the number of hours until the token expires. Default is 2 hours.
|
||||
type: integer
|
||||
totpSecret:
|
||||
description: secret used to encrypt TOTP secrets
|
||||
type: string
|
||||
type: object
|
||||
settings.ExternalLink:
|
||||
properties:
|
||||
@@ -177,6 +184,9 @@ definitions:
|
||||
output:
|
||||
description: output location. (eg. "stdout" or "path/to/file.log")
|
||||
type: string
|
||||
utc:
|
||||
description: use UTC time in the output instead of local time
|
||||
type: boolean
|
||||
type: object
|
||||
settings.LoginMethods:
|
||||
properties:
|
||||
@@ -199,41 +209,33 @@ definitions:
|
||||
type: object
|
||||
settings.OidcConfig:
|
||||
properties:
|
||||
authorizationUrl:
|
||||
description: authorization URL of the OIDC provider
|
||||
type: string
|
||||
clientId:
|
||||
description: client id of the OIDC application
|
||||
type: string
|
||||
clientSecret:
|
||||
description: client secret of the OIDC application
|
||||
type: string
|
||||
disableVerifyTLS:
|
||||
description: disable TLS verification for the OIDC provider. This is insecure
|
||||
and should only be used for testing.
|
||||
type: boolean
|
||||
enabled:
|
||||
description: whether to enable OIDC authentication
|
||||
type: boolean
|
||||
jwksUrl:
|
||||
description: currently not used by filebrowser
|
||||
issuerUrl:
|
||||
description: authorization URL of the OIDC provider
|
||||
type: string
|
||||
logoutRedirectUrl:
|
||||
description: if provider logout url is provided, filebrowser will also redirect
|
||||
to logout url. Custom logout query params are respected.
|
||||
type: string
|
||||
scopes:
|
||||
description: space separated list of scopes to request from the OIDC provider
|
||||
type: string
|
||||
tokenUrl:
|
||||
description: token URL of the OIDC provider
|
||||
description: scopes to request from the OIDC provider
|
||||
type: string
|
||||
userIdentifier:
|
||||
description: 'optional: which attribute should be used as the username? options:
|
||||
email, username, name, phone_number, sub'
|
||||
description: the user identifier to use for authentication. Default is "username",
|
||||
can be "email" or "username", or "phone"
|
||||
type: string
|
||||
userInfoUrl:
|
||||
description: user info URL of the OIDC provider
|
||||
type: string
|
||||
required:
|
||||
- authorizationUrl
|
||||
- clientId
|
||||
- clientSecret
|
||||
- scopes
|
||||
- tokenUrl
|
||||
- userInfoUrl
|
||||
type: object
|
||||
settings.OnlyOffice:
|
||||
properties:
|
||||
@@ -256,7 +258,12 @@ definitions:
|
||||
properties:
|
||||
enabled:
|
||||
type: boolean
|
||||
enforcedOtp:
|
||||
description: if set to true, TOTP is enforced for all password users users.
|
||||
Otherwise, users can choose to enable TOTP.
|
||||
type: boolean
|
||||
minLength:
|
||||
description: minimum pasword length required.
|
||||
minimum: 5
|
||||
type: integer
|
||||
recaptcha:
|
||||
@@ -264,7 +271,7 @@ definitions:
|
||||
- $ref: '#/definitions/settings.Recaptcha'
|
||||
description: recaptcha config, only used if signup is enabled
|
||||
signup:
|
||||
description: currently not used by filebrowser
|
||||
description: allow signups on login page if enabled -- not secure.
|
||||
type: boolean
|
||||
type: object
|
||||
settings.ProxyAuthConfig:
|
||||
@@ -278,6 +285,10 @@ definitions:
|
||||
description: 'required header to use for authentication. Security Warning:
|
||||
FileBrowser blindly accepts the header value as username.'
|
||||
type: string
|
||||
logoutRedirectUrl:
|
||||
description: if provider logout url is provided, filebrowser will also redirect
|
||||
to logout url. Custom logout query params are respected.
|
||||
type: string
|
||||
type: object
|
||||
settings.Recaptcha:
|
||||
properties:
|
||||
@@ -305,6 +316,10 @@ definitions:
|
||||
database:
|
||||
description: path to the database file
|
||||
type: string
|
||||
debugMedia:
|
||||
description: output ffmpeg stdout for media integration -- careful can produces
|
||||
lots of output!
|
||||
type: boolean
|
||||
disablePreviewResize:
|
||||
description: disable resizing of previews for faster loading over slow connections
|
||||
type: boolean
|
||||
@@ -330,7 +345,8 @@ definitions:
|
||||
to be archived (in GB)
|
||||
type: integer
|
||||
numImageProcessors:
|
||||
description: number of concurrent image processing jobs
|
||||
description: number of concurrent image processing jobs used to create previews,
|
||||
default is number of cpu cores available.
|
||||
type: integer
|
||||
port:
|
||||
description: port to listen on
|
||||
@@ -421,34 +437,59 @@ definitions:
|
||||
settings.UserDefaults:
|
||||
properties:
|
||||
darkMode:
|
||||
description: should dark mode be enabled
|
||||
type: boolean
|
||||
dateFormat:
|
||||
description: when false, the date is relative, when true, the date is an exact
|
||||
timestamp
|
||||
type: boolean
|
||||
disableOfficePreviewExt:
|
||||
description: comma separated list of file extensions to disable office preview
|
||||
for
|
||||
type: string
|
||||
disableOnlyOfficeExt:
|
||||
description: comma separated list of file extensions to disable onlyoffice
|
||||
preview for
|
||||
type: string
|
||||
disableSettings:
|
||||
description: disable the user from viewing the settings page
|
||||
type: boolean
|
||||
gallerySize:
|
||||
description: 0-9 - the size of the gallery thumbnails
|
||||
type: integer
|
||||
locale:
|
||||
description: 'language to use: eg. de, en, or fr'
|
||||
type: string
|
||||
lockPassword:
|
||||
description: disable the user from changing their password
|
||||
type: boolean
|
||||
loginMethod:
|
||||
description: 'login method to use: eg. password, proxy, oidc'
|
||||
type: string
|
||||
permissions:
|
||||
$ref: '#/definitions/users.Permissions'
|
||||
preview:
|
||||
$ref: '#/definitions/users.PreviewOptions'
|
||||
$ref: '#/definitions/users.Preview'
|
||||
quickDownload:
|
||||
description: show icon to download in one click
|
||||
type: boolean
|
||||
showHidden:
|
||||
description: show hidden files in the UI. On windows this includes files starting
|
||||
with a dot and windows hidden files
|
||||
type: boolean
|
||||
singleClick:
|
||||
description: open directory on single click, also enables middle click to
|
||||
open in new tab
|
||||
type: boolean
|
||||
stickySidebar:
|
||||
description: keep sidebar open when navigating
|
||||
type: boolean
|
||||
themeColor:
|
||||
description: 'theme color to use: eg. #ff0000, or var(--red), var(--purple),
|
||||
etc'
|
||||
type: string
|
||||
viewMode:
|
||||
description: 'view mode to use: eg. normal, list, grid, or compact'
|
||||
type: string
|
||||
type: object
|
||||
share.CreateBody:
|
||||
@@ -519,17 +560,25 @@ definitions:
|
||||
share:
|
||||
type: boolean
|
||||
type: object
|
||||
users.PreviewOptions:
|
||||
users.Preview:
|
||||
properties:
|
||||
highQuality:
|
||||
description: generate high quality preview images
|
||||
type: boolean
|
||||
image:
|
||||
description: show real image as icon instead of generic photo icon
|
||||
type: boolean
|
||||
motionVideoPreview:
|
||||
description: show multiple frames for videos in preview when hovering
|
||||
type: boolean
|
||||
office:
|
||||
description: show preview image for office files
|
||||
type: boolean
|
||||
popup:
|
||||
description: show larger popup preview when hovering
|
||||
type: boolean
|
||||
video:
|
||||
description: show preview image for video files
|
||||
type: boolean
|
||||
type: object
|
||||
users.Sorting:
|
||||
@@ -553,23 +602,37 @@ definitions:
|
||||
$ref: '#/definitions/users.AuthToken'
|
||||
type: object
|
||||
darkMode:
|
||||
description: should dark mode be enabled
|
||||
type: boolean
|
||||
dateFormat:
|
||||
description: when false, the date is relative, when true, the date is an exact
|
||||
timestamp
|
||||
type: boolean
|
||||
disableOfficePreviewExt:
|
||||
description: comma separated list of file extensions to disable office preview
|
||||
for
|
||||
type: string
|
||||
disableOnlyOfficeExt:
|
||||
description: comma separated list of file extensions to disable onlyoffice
|
||||
preview for
|
||||
type: string
|
||||
disableSettings:
|
||||
type: boolean
|
||||
gallerySize:
|
||||
description: 0-9 - the size of the gallery thumbnails
|
||||
type: integer
|
||||
id:
|
||||
type: integer
|
||||
locale:
|
||||
description: 'language to use: eg. de, en, or fr'
|
||||
type: string
|
||||
lockPassword:
|
||||
type: boolean
|
||||
loginMethod:
|
||||
$ref: '#/definitions/users.LoginMethod'
|
||||
otpEnabled:
|
||||
description: true if TOTP is enabled, false otherwise
|
||||
type: boolean
|
||||
password:
|
||||
type: string
|
||||
perm:
|
||||
@@ -579,8 +642,9 @@ definitions:
|
||||
permissions:
|
||||
$ref: '#/definitions/users.Permissions'
|
||||
preview:
|
||||
$ref: '#/definitions/users.PreviewOptions'
|
||||
$ref: '#/definitions/users.Preview'
|
||||
quickDownload:
|
||||
description: show icon to download in one click
|
||||
type: boolean
|
||||
scope:
|
||||
type: string
|
||||
@@ -589,23 +653,100 @@ definitions:
|
||||
$ref: '#/definitions/users.SourceScope'
|
||||
type: array
|
||||
showHidden:
|
||||
description: show hidden files in the UI. On windows this includes files starting
|
||||
with a dot and windows hidden files
|
||||
type: boolean
|
||||
singleClick:
|
||||
description: open directory on single click, also enables middle click to
|
||||
open in new tab
|
||||
type: boolean
|
||||
sorting:
|
||||
$ref: '#/definitions/users.Sorting'
|
||||
stickySidebar:
|
||||
description: keep sidebar open when navigating
|
||||
type: boolean
|
||||
themeColor:
|
||||
description: 'theme color to use: eg. #ff0000, or var(--red), var(--purple),
|
||||
etc'
|
||||
type: string
|
||||
totpNonce:
|
||||
type: string
|
||||
totpSecret:
|
||||
type: string
|
||||
username:
|
||||
type: string
|
||||
viewMode:
|
||||
description: 'view mode to use: eg. normal, list, grid, or compact'
|
||||
type: string
|
||||
type: object
|
||||
info:
|
||||
contact: {}
|
||||
paths:
|
||||
/api/auth/logout:
|
||||
get:
|
||||
description: logs a user out of the application.
|
||||
responses:
|
||||
"302":
|
||||
description: Redirect to redirect URL if configured in oidc config.
|
||||
schema:
|
||||
type: string
|
||||
summary: User Logout
|
||||
tags:
|
||||
- Auth
|
||||
/api/auth/otp/generate:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Generates a new TOTP secret and QR code for the authenticated user.
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OTP secret generated successfully.
|
||||
schema:
|
||||
additionalProperties:
|
||||
type: string
|
||||
type: object
|
||||
"500":
|
||||
description: Internal server error
|
||||
schema:
|
||||
additionalProperties:
|
||||
type: string
|
||||
type: object
|
||||
security:
|
||||
- ApiKeyAuth: []
|
||||
summary: Generate OTP
|
||||
tags:
|
||||
- OTP
|
||||
/api/auth/otp/verify:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Verifies the provided TOTP code for the authenticated user.
|
||||
parameters:
|
||||
- description: TOTP code to verify
|
||||
in: query
|
||||
name: code
|
||||
required: true
|
||||
type: string
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OTP token is valid.
|
||||
schema:
|
||||
$ref: '#/definitions/http.HttpResponse'
|
||||
"401":
|
||||
description: Unauthorized - invalid TOTP token
|
||||
schema:
|
||||
additionalProperties:
|
||||
type: string
|
||||
type: object
|
||||
security:
|
||||
- ApiKeyAuth: []
|
||||
summary: Verify OTP
|
||||
tags:
|
||||
- OTP
|
||||
/api/createApiKey:
|
||||
post:
|
||||
consumes:
|
||||
|
||||
+40
-1
@@ -6,9 +6,48 @@
|
||||
"extends": [
|
||||
"plugin:vue/vue3-essential",
|
||||
"eslint:recommended",
|
||||
"@vue/eslint-config-typescript"
|
||||
"@vue/eslint-config-typescript",
|
||||
"plugin:@intlify/vue-i18n/recommended"
|
||||
],
|
||||
"settings": {
|
||||
"vue-i18n": {
|
||||
// Path to your locale message directory or a glob pattern.
|
||||
// The plugin will use these files to determine available keys.
|
||||
// Make sure 'en.json' is present here.
|
||||
"localeDir": "./src/i18n/*.json"
|
||||
|
||||
// If your i18n instance is initialized with a fallbackLocale,
|
||||
// the linter might use that. Ensure 'en' is effectively the master.
|
||||
// fallbackLocale: 'en', // This might be part of your i18n setup, not ESLint settings
|
||||
}
|
||||
},
|
||||
"rules": {
|
||||
// vue-i18n rules:
|
||||
// This rule will check if the key used in $t() exists in your locale messages.
|
||||
// By default, it checks against all locales. We want it to primarily use 'en.json'
|
||||
// as the source of truth. The plugin often infers this from your i18n setup,
|
||||
// but we want to be explicit or ensure our sync script makes 'en.json' the master.
|
||||
"@intlify/vue-i18n/no-missing-keys": "error",
|
||||
// Optional: Warn about unused keys in your 'en.json'
|
||||
// This requires configuring the `localeDir` setting below.
|
||||
"@intlify/vue-i18n/no-unused-keys": ["warn", {
|
||||
"src": "./src", // Path to your source files
|
||||
"extensions": [".js", ".vue"]
|
||||
// Important: This tells the rule to check unused keys specifically in en.json
|
||||
// by making it the single source of truth for what "should" exist.
|
||||
// However, the rule usually checks keys NOT used in your Vue code.
|
||||
// The primary goal is `no-missing-keys` for keys used in the template.
|
||||
}],
|
||||
|
||||
"@intlify/vue-i18n/no-raw-text": [
|
||||
"warn",
|
||||
{
|
||||
"ignoreNodes": ["i", "v-icon"]
|
||||
}
|
||||
],
|
||||
|
||||
// If you have your sync script, you might not need this one for other locales.
|
||||
"@intlify/vue-i18n/no-missing-keys-in-other-locales": "off",
|
||||
"vue/multi-word-component-names": "off",
|
||||
"vue/no-mutating-props": [
|
||||
"error",
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
"typecheck": "vue-tsc -p ./tsconfig.json --noEmit",
|
||||
"lint": "eslint --ext .js,.vue,ts src",
|
||||
"lint:fix": "eslint --fix src/",
|
||||
"i18n:sync": "node ./scripts/sync-translations.js",
|
||||
"format": "prettier --write .",
|
||||
"test": "vitest run "
|
||||
},
|
||||
@@ -26,7 +27,11 @@
|
||||
"clipboard": "^2.0.4",
|
||||
"css-vars-ponyfill": "^2.4.3",
|
||||
"dompurify": "^3.2.4",
|
||||
"epubjs": "^0.3.93",
|
||||
"file-loader": "^6.2.0",
|
||||
"glob": "^9.3.5",
|
||||
"highlight.js": "^11.11.1",
|
||||
"mammoth": "^1.9.1",
|
||||
"marked": "^15.0.6",
|
||||
"normalize.css": "^8.0.1",
|
||||
"qrcode.vue": "^3.4.1",
|
||||
@@ -37,13 +42,16 @@
|
||||
"vue-router": "^4.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@intlify/eslint-plugin-vue-i18n": "^3.2.0",
|
||||
"@intlify/unplugin-vue-i18n": "^4.0.0",
|
||||
"@playwright/test": "^1.49.1",
|
||||
"@vitejs/plugin-vue": "^5.0.4",
|
||||
"@vue/eslint-config-typescript": "^13.0.0",
|
||||
"deepl-node": "^1.18.0",
|
||||
"eslint": "^8.57.0",
|
||||
"eslint-config-prettier": "^9.1.0",
|
||||
"eslint-plugin-vue": "^9.24.0",
|
||||
"fs-extra": "^11.3.0",
|
||||
"jsdom": "^25.0.1",
|
||||
"vite": "^6.2.0",
|
||||
"vite-plugin-compression2": "^1.0.0",
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
server:
|
||||
numImageProcessors: 8 # number of concurrent image processing jobs used to create previews, default is number of cpu cores available.
|
||||
socket: "" # socket to listen on
|
||||
tlsKey: "" # path to TLS key
|
||||
tlsCert: "" # path to TLS cert
|
||||
disablePreviews: false # disable all previews thumbnails, simple icons will be used
|
||||
disablePreviewResize: false # disable resizing of previews for faster loading over slow connections
|
||||
disableTypeDetectionByHeader: false # disable type detection by header, useful if filesystem is slow.
|
||||
port: 80 # port to listen on
|
||||
baseURL: / # base URL for the server, the subpath that the server is running on.
|
||||
logging:
|
||||
- levels: "" # separated list of log levels to enable. (eg. "info|warning|error|debug")
|
||||
apiLevels: "" # separated list of log levels to enable for the API. (eg. "info|warning|error")
|
||||
output: stdout # output location. (eg. "stdout" or "path/to/file.log")
|
||||
noColors: false # disable colors in the output
|
||||
json: false # output in json format, currently not supported
|
||||
utc: false # use UTC time in the output instead of local time
|
||||
debugMedia: false # output ffmpeg stdout for media integration -- careful can produces lots of output!
|
||||
database: database.db # path to the database file
|
||||
sources: # validate:required,dive
|
||||
- path: /relative/or/absolute/path # file system path. (Can be relative) validate:required
|
||||
name: backend # display name
|
||||
config:
|
||||
indexingInterval: 0 # optional manual overide interval in seconds to re-index the source
|
||||
disabled: false # disable the indexing of this source
|
||||
maxWatchers: 0 # number of concurrent watchers to use for this source, currently not supported
|
||||
neverWatchPaths: []
|
||||
ignoreHidden: false # ignore hidden files and folders.
|
||||
ignoreZeroSizeFolders: false # ignore folders with 0 size
|
||||
exclude: # exclude files and folders from indexing, if include is not set
|
||||
files: []
|
||||
folders: []
|
||||
fileEndsWith: []
|
||||
include: # include files and folders from indexing, if exclude is not set
|
||||
files: []
|
||||
folders: []
|
||||
fileEndsWith: []
|
||||
defaultUserScope: / # default "/" should match folders under path
|
||||
defaultEnabled: true # should be added as a default source for new users?
|
||||
createUserDir: false # create a user directory for each user
|
||||
externalUrl: "" # used by share links if set
|
||||
internalUrl: "" # used by integrations if set, this is the url that an integration service will use to communicate with filebrowser
|
||||
cacheDir: tmp # path to the cache directory, used for thumbnails and other cached files
|
||||
maxArchiveSize: 50 # max pre-archive combined size of files/folder that are allowed to be archived (in GB)
|
||||
auth:
|
||||
tokenExpirationHours: 2 # the number of hours until the token expires. Default is 2 hours.
|
||||
methods:
|
||||
proxy: # validate:omitempty
|
||||
enabled: false
|
||||
createUser: false # create user if not exists
|
||||
header: "" # required header to use for authentication. Security Warning: FileBrowser blindly accepts the header value as username.
|
||||
logoutRedirectUrl: "" # if provider logout url is provided, filebrowser will also redirect to logout url. Custom logout query params are respected.
|
||||
noauth: false # if set to true, overrides all other auth methods and disables authentication
|
||||
password: # validate:omitempty
|
||||
enabled: true
|
||||
minLength: 5 # minimum pasword length required. validate:omitempty,min=5
|
||||
signup: false # allow signups on login page if enabled -- not secure. validate:omitempty
|
||||
recaptcha: # recaptcha config, only used if signup is enabled validate:omitempty
|
||||
host: "" # validate:required
|
||||
key: "" # validate:required
|
||||
secret: "" # validate:required
|
||||
enforcedOtp: false # if set to true, TOTP is enforced for all password users users. Otherwise, users can choose to enable TOTP.
|
||||
oidc: # validate:omitempty
|
||||
enabled: false # whether to enable OIDC authentication
|
||||
clientId: "" # client id of the OIDC application
|
||||
clientSecret: "" # client secret of the OIDC application
|
||||
issuerUrl: "" # authorization URL of the OIDC provider
|
||||
scopes: "" # scopes to request from the OIDC provider
|
||||
userIdentifier: "" # the user identifier to use for authentication. Default is "username", can be "email" or "username", or "phone"
|
||||
disableVerifyTLS: false # disable TLS verification for the OIDC provider. This is insecure and should only be used for testing.
|
||||
logoutRedirectUrl: "" # if provider logout url is provided, filebrowser will also redirect to logout url. Custom logout query params are respected.
|
||||
key: "" # the key used to sign the JWT tokens. If not set, a random key will be generated.
|
||||
adminUsername: admin # the username of the admin user. If not set, the default is "admin".
|
||||
adminPassword: admin # the password of the admin user. If not set, the default is "admin".
|
||||
resetAdminOnStart: false # if set to true, the admin user will be reset to the default username and password on startup.
|
||||
totpSecret: "" # secret used to encrypt TOTP secrets
|
||||
frontend:
|
||||
name: FileBrowser Quantum # display name
|
||||
disableDefaultLinks: false # disable default links in the sidebar
|
||||
disableUsedPercentage: false # disable used percentage for the sources in the sidebar
|
||||
externalLinks:
|
||||
- text: (untracked) # the text to display on the link validate:required
|
||||
title: untracked # the title to display on hover
|
||||
url: https://github.com/gtsteffaniak/filebrowser/releases/ # the url to link to validate:required
|
||||
- text: Help # the text to display on the link validate:required
|
||||
title: "" # the title to display on hover
|
||||
url: https://github.com/gtsteffaniak/filebrowser/wiki # the url to link to validate:required
|
||||
userDefaults:
|
||||
stickySidebar: true # keep sidebar open when navigating
|
||||
darkMode: true # should dark mode be enabled
|
||||
locale: en # language to use: eg. de, en, or fr
|
||||
viewMode: normal # view mode to use: eg. normal, list, grid, or compact
|
||||
singleClick: false # open directory on single click, also enables middle click to open in new tab
|
||||
showHidden: false # show hidden files in the UI. On windows this includes files starting with a dot and windows hidden files
|
||||
dateFormat: false # when false, the date is relative, when true, the date is an exact timestamp
|
||||
gallerySize: 3 # 0-9 - the size of the gallery thumbnails
|
||||
themeColor: var(--blue) # theme color to use: eg. #ff0000, or var(--red), var(--purple), etc
|
||||
quickDownload: false # show icon to download in one click
|
||||
disableOnlyOfficeExt: .txt .csv .html .pdf # comma separated list of file extensions to disable onlyoffice preview for
|
||||
disableOfficePreviewExt: "" # comma separated list of file extensions to disable office preview for
|
||||
lockPassword: false # disable the user from changing their password
|
||||
disableSettings: false # disable the user from viewing the settings page
|
||||
preview:
|
||||
highQuality: false
|
||||
image: false
|
||||
video: false
|
||||
motionVideoPreview: false
|
||||
office: false
|
||||
popup: false
|
||||
permissions:
|
||||
api: false
|
||||
admin: false
|
||||
modify: false
|
||||
share: false
|
||||
realtime: false
|
||||
loginMethod: password # login method to use: eg. password, proxy, oidc
|
||||
integrations:
|
||||
office: # validate:omitempty
|
||||
url: "" # The URL to the OnlyOffice Document Server, needs to be accessible to the user. validate:required
|
||||
internalUrl: "" # An optional internal address that the filebrowser server can use to communicate with the OnlyOffice Document Server, could be useful to bypass proxy.
|
||||
secret: "" # validate:required
|
||||
media: # validate:omitempty
|
||||
ffmpegPath: "" # path to ffmpeg directory with ffmpeg and ffprobe (eg. /usr/local/bin)
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 9.5 KiB |
@@ -0,0 +1,152 @@
|
||||
// scripts/sync-translations.js
|
||||
import fs from 'fs-extra';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import * as glob from 'glob';
|
||||
import * as deepl from 'deepl-node';
|
||||
|
||||
// --- Configuration ---
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const localesDir = path.resolve(__dirname, '../src/i18n');
|
||||
const masterLocaleFile = path.join(localesDir, 'en.json');
|
||||
const masterLanguageCode = 'en';
|
||||
const targetLocaleFiles = glob.sync(path.join(localesDir, '*.json'))
|
||||
.filter(file => path.basename(file) !== `${masterLanguageCode}.json`);
|
||||
|
||||
const DEEPL_API_KEY = process.env.DEEPL_API_KEY;
|
||||
if (!DEEPL_API_KEY) {
|
||||
console.error("❌ Missing DEEPL_API_KEY in environment.");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const translator = new deepl.Translator(DEEPL_API_KEY);
|
||||
|
||||
// --- Translation Function using DeepL ---
|
||||
async function translateText(text, targetLanguage, keyPath = '') {
|
||||
if (!text || typeof text !== 'string' || text.trim() === '') {
|
||||
console.warn(`Skipping translation for empty or non-string text: "${text}"`);
|
||||
return text;
|
||||
}
|
||||
|
||||
if (keyPath === 'languages' || keyPath.startsWith('languages.')) {
|
||||
return text;
|
||||
}
|
||||
|
||||
if (/\{[^}]+\}/.test(text)) {
|
||||
console.log(`Skipping translation for placeholder string: "${text}"`);
|
||||
return text;
|
||||
}
|
||||
|
||||
try {
|
||||
console.log(`Translating "${text}" from '${masterLanguageCode}' to '${targetLanguage}'...`);
|
||||
|
||||
const result = await translator.translateText(text, masterLanguageCode, targetLanguage.toUpperCase());
|
||||
|
||||
// Delay to avoid rate-limiting
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
return result.text;
|
||||
|
||||
} catch (err) {
|
||||
console.error(`⚠️ Translation failed for "${text}" (${keyPath}):`, err?.message || err);
|
||||
return ``;
|
||||
}
|
||||
}
|
||||
|
||||
// --- Recursive key processor ---
|
||||
async function processKeys(masterObj, targetObj, targetLangCode, currentPathParts = []) {
|
||||
let changesMade = false;
|
||||
for (const key in masterObj) {
|
||||
if (Object.prototype.hasOwnProperty.call(masterObj, key)) {
|
||||
const currentPathPartsNext = [...currentPathParts, key];
|
||||
const currentKeyPath = currentPathPartsNext.join('.');
|
||||
if (currentPathParts[0] === 'languages') continue;
|
||||
|
||||
const masterValue = masterObj[key];
|
||||
|
||||
if (typeof masterValue === 'object' && masterValue !== null && !Array.isArray(masterValue)) {
|
||||
if (!targetObj[key] || typeof targetObj[key] !== 'object') {
|
||||
console.log(`Creating missing object structure for "${currentKeyPath}" in ${targetLangCode}.json`);
|
||||
targetObj[key] = {};
|
||||
changesMade = true;
|
||||
}
|
||||
const result = await processKeys(masterValue, targetObj[key], targetLangCode, currentPathPartsNext);
|
||||
if (result == "UNSUPPORTED") {
|
||||
console.log(`Skipping translation for "${targetLangCode}" due to unsupported structure.`);
|
||||
return "UNSUPPORTED";
|
||||
}
|
||||
if (result) {
|
||||
changesMade = true;
|
||||
}
|
||||
} else if (typeof masterValue === 'string') {
|
||||
if (!targetObj.hasOwnProperty(key) || targetObj[key] === '' || targetObj[key] === null) {
|
||||
const result = await translateText(masterValue, targetLangCode, currentKeyPath);
|
||||
if (result == "") {
|
||||
return "UNSUPPORTED";
|
||||
}
|
||||
targetObj[key] = result;
|
||||
changesMade = true;
|
||||
}
|
||||
} else {
|
||||
if (!targetObj.hasOwnProperty(key)) {
|
||||
console.log(`Key "${currentKeyPath}" (non-string) missing in ${targetLangCode}.json. Copying from English.`);
|
||||
targetObj[key] = masterValue;
|
||||
changesMade = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return changesMade;
|
||||
}
|
||||
|
||||
// --- Main synchronization ---
|
||||
async function syncAllTranslations() {
|
||||
console.warn("--- Using DeepL API for translation ---");
|
||||
|
||||
if (!await fs.pathExists(masterLocaleFile)) {
|
||||
console.error(`Master locale file not found: ${masterLocaleFile}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const masterContent = await fs.readJson(masterLocaleFile);
|
||||
console.log(`Loaded master translations from ${masterLocaleFile}`);
|
||||
|
||||
for (const targetFile of targetLocaleFiles) {
|
||||
const targetLangCode = path.basename(targetFile, '.json');
|
||||
let targetContent = {};
|
||||
let fileExisted = await fs.pathExists(targetFile);
|
||||
|
||||
if (fileExisted) {
|
||||
try {
|
||||
targetContent = await fs.readJson(targetFile);
|
||||
console.log(`\nProcessing target language: ${targetLangCode} (from ${targetFile})`);
|
||||
} catch (e) {
|
||||
console.warn(`Warning: Could not parse ${targetFile}. Starting fresh. Error: ${e.message}`);
|
||||
targetContent = {};
|
||||
}
|
||||
} else {
|
||||
console.log(`\nTarget file ${targetFile} not found. Will create for language: ${targetLangCode}.`);
|
||||
}
|
||||
|
||||
const wasUpdated = await processKeys(masterContent, targetContent, targetLangCode);
|
||||
|
||||
if (wasUpdated || !fileExisted) {
|
||||
try {
|
||||
await fs.writeJson(targetFile, targetContent, { spaces: 2 });
|
||||
console.log(`Successfully ${wasUpdated ? 'updated' : 'created'} ${targetFile}`);
|
||||
} catch (error) {
|
||||
console.error(`Error writing to ${targetFile}:`, error);
|
||||
}
|
||||
} else {
|
||||
console.log(`No changes needed for ${targetFile}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('\n✅ Translation synchronization complete (via DeepL).');
|
||||
}
|
||||
|
||||
syncAllTranslations().catch(error => {
|
||||
console.error("\n❌ An error occurred during translation synchronization:", error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -229,8 +229,7 @@ export function getPreviewURL(source, path, modified) {
|
||||
try {
|
||||
const params = {
|
||||
path: encodeURIComponent(path),
|
||||
size: state.user.preview.highQuality ? 'large' : 'small',
|
||||
key: Date.parse(modified),
|
||||
key: Date.parse(modified), // Use modified date as cache key
|
||||
source: source,
|
||||
inline: 'true'
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { fetchURL, fetchJSON, adjustedData } from "./utils";
|
||||
import { state } from '@/store'
|
||||
import { notify } from "@/notify";
|
||||
import { getApiPath,removePrefix } from "@/utils/url.js";
|
||||
import { externalUrl,baseURL } from "@/utils/constants";
|
||||
@@ -54,7 +53,7 @@ export function getPreviewURL(hash, path) {
|
||||
try {
|
||||
const params = {
|
||||
path: encodeURIComponent(path),
|
||||
size: state.user.preview.highQuality ? 'large' : 'small',
|
||||
size: 'small',
|
||||
hash: hash,
|
||||
inline: 'true'
|
||||
}
|
||||
|
||||
+152
-67
@@ -1,118 +1,203 @@
|
||||
import { fetchURL, fetchJSON } from "@/api/utils";
|
||||
import { getApiPath } from "@/utils/url.js";
|
||||
import { notify } from "@/notify"; // Import notify for error handling
|
||||
import { fetchURL, fetchJSON } from '@/api/utils'
|
||||
import { getApiPath } from '@/utils/url.js'
|
||||
import { notify } from '@/notify' // Import notify for error handling
|
||||
import { setNewToken } from '@/utils/auth.js' // Import setNewToken for token management
|
||||
|
||||
export async function getAllUsers() {
|
||||
export async function getAllUsers () {
|
||||
try {
|
||||
const apiPath = getApiPath("api/users");
|
||||
return await fetchJSON(apiPath);
|
||||
const apiPath = getApiPath('api/users')
|
||||
return await fetchJSON(apiPath)
|
||||
} catch (err) {
|
||||
notify.showError(err.message || "Failed to fetch users");
|
||||
throw err; // Re-throw to handle further if needed
|
||||
notify.showError(err.message || 'Failed to fetch users')
|
||||
throw err // Re-throw to handle further if needed
|
||||
}
|
||||
}
|
||||
|
||||
export async function generateOTP (username, password) {
|
||||
const params = { username }
|
||||
try {
|
||||
let apiPath = getApiPath('api/auth/otp/generate', params)
|
||||
const res = await fetch(apiPath, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-Password': password,
|
||||
}
|
||||
})
|
||||
return await res.json()
|
||||
} catch (error) {
|
||||
notify.showError(error || 'Failed to generate OTP')
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function verifyOtp (username, password, otp) {
|
||||
const params = { username }
|
||||
try {
|
||||
let apiPath = getApiPath('api/auth/otp/verify', params)
|
||||
const res = await fetch(apiPath, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-Password': password,
|
||||
'X-Secret': otp,
|
||||
}
|
||||
})
|
||||
if (res.status != 200) {
|
||||
throw new Error('Failed to verify OTP')
|
||||
}
|
||||
} catch (error) {
|
||||
notify.showError(error || 'Failed to generate OTP')
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function login(username, password, recaptcha, otp) {
|
||||
if (!otp) {
|
||||
otp = ''
|
||||
}
|
||||
if (!recaptcha) {
|
||||
recaptcha = ''
|
||||
}
|
||||
if (!password) {
|
||||
password = ''
|
||||
}
|
||||
|
||||
const params = { username, recaptcha };
|
||||
let apiPath = getApiPath('api/auth/login', params);
|
||||
const res = await fetch(apiPath, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-Password': password,
|
||||
'X-Secret': otp,
|
||||
}
|
||||
});
|
||||
|
||||
const bodyText = await res.text();
|
||||
let body;
|
||||
|
||||
try {
|
||||
body = JSON.parse(bodyText);
|
||||
} catch {
|
||||
body = { message: bodyText };
|
||||
}
|
||||
|
||||
if (res.status === 200) {
|
||||
await setNewToken(bodyText);
|
||||
} else if (res.status === 403) {
|
||||
const msg = body.message || 'Forbidden';
|
||||
throw new Error(msg);
|
||||
} else {
|
||||
throw new Error(body.message || bodyText || 'Failed to login');
|
||||
}
|
||||
}
|
||||
export async function get(id) {
|
||||
try {
|
||||
const apiPath = getApiPath("api/users", { id: id });
|
||||
return await fetchJSON(apiPath);
|
||||
const apiPath = getApiPath('api/users', { id: id })
|
||||
return await fetchJSON(apiPath)
|
||||
} catch (err) {
|
||||
notify.showError(err.message || `Failed to fetch user with ID: ${id}`);
|
||||
throw err;
|
||||
notify.showError(err.message || `Failed to fetch user with ID: ${id}`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
export async function getApiKeys() {
|
||||
export async function getApiKeys () {
|
||||
try {
|
||||
const apiPath = getApiPath("api/auth/tokens");
|
||||
return await fetchJSON(apiPath);
|
||||
const apiPath = getApiPath('api/auth/tokens')
|
||||
return await fetchJSON(apiPath)
|
||||
} catch (err) {
|
||||
notify.showError(err.message || `Failed to get api keys`);
|
||||
throw err;
|
||||
notify.showError(err.message || `Failed to get api keys`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
export async function signupLogin (username, password, otp) {
|
||||
const params = { username, password, otp }
|
||||
let apiPath = getApiPath('api/auth/signup', params)
|
||||
const res = await fetch(apiPath, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
})
|
||||
|
||||
export async function createApiKey(params) {
|
||||
if (res.status !== 201) {
|
||||
throw new Error(res.status)
|
||||
}
|
||||
}
|
||||
|
||||
export async function createApiKey (params) {
|
||||
try {
|
||||
const apiPath = getApiPath("api/auth/token", params);
|
||||
const apiPath = getApiPath('api/auth/token', params)
|
||||
await fetchURL(apiPath, {
|
||||
method: "PUT",
|
||||
});
|
||||
method: 'PUT'
|
||||
})
|
||||
} catch (err) {
|
||||
notify.showError(err.message || `Failed to create API key`);
|
||||
throw err;
|
||||
notify.showError(err.message || `Failed to create API key`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
export function deleteApiKey(params) {
|
||||
export function deleteApiKey (params) {
|
||||
try {
|
||||
const apiPath = getApiPath("api/auth/token", params);
|
||||
const apiPath = getApiPath('api/auth/token', params)
|
||||
fetchURL(apiPath, {
|
||||
method: "DELETE",
|
||||
});
|
||||
method: 'DELETE'
|
||||
})
|
||||
} catch (err) {
|
||||
notify.showError(err.message || `Failed to delete API key`);
|
||||
throw err;
|
||||
notify.showError(err.message || `Failed to delete API key`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
export async function create(user) {
|
||||
export async function create (user) {
|
||||
try {
|
||||
const apiPath = getApiPath("api/users");
|
||||
const apiPath = getApiPath('api/users')
|
||||
const res = await fetchURL(apiPath, {
|
||||
method: "POST",
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
what: "user",
|
||||
what: 'user',
|
||||
which: [],
|
||||
data: user,
|
||||
}),
|
||||
});
|
||||
data: user
|
||||
})
|
||||
})
|
||||
|
||||
if (res.status === 201) {
|
||||
return res.headers.get("Location");
|
||||
return res.headers.get('Location')
|
||||
} else {
|
||||
throw new Error("Failed to create user");
|
||||
throw new Error('Failed to create user')
|
||||
}
|
||||
} catch (err) {
|
||||
notify.showError(err.message || "Error creating user");
|
||||
throw err;
|
||||
notify.showError(err.message || 'Error creating user')
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
export async function update(user, which = ["all"]) {
|
||||
try {
|
||||
// List of keys to exclude from the "which" array
|
||||
const excludeKeys = ["id", "name"];
|
||||
// Filter out the keys from "which"
|
||||
which = which.filter(item => !excludeKeys.includes(item));
|
||||
if (user.username === "publicUser") {
|
||||
return;
|
||||
}
|
||||
const apiPath = getApiPath("api/users", { id: user.id });
|
||||
await fetchURL(apiPath, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({
|
||||
what: "user",
|
||||
which: which,
|
||||
data: user,
|
||||
}),
|
||||
});
|
||||
} catch (err) {
|
||||
notify.showError(err.message || `Failed to update user with ID: ${user.id}`);
|
||||
throw err;
|
||||
export async function update (user, which = ['all']) {
|
||||
// List of keys to exclude from the "which" array
|
||||
const excludeKeys = ['id', 'name']
|
||||
// Filter out the keys from "which"
|
||||
which = which.filter(item => !excludeKeys.includes(item))
|
||||
if (user.username === 'publicUser') {
|
||||
return
|
||||
}
|
||||
const apiPath = getApiPath('api/users', { id: user.id })
|
||||
await fetchURL(apiPath, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
what: 'user',
|
||||
which: which,
|
||||
data: user
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export async function remove(id) {
|
||||
export async function remove (id) {
|
||||
try {
|
||||
const apiPath = getApiPath("api/users", { id: id });
|
||||
const apiPath = getApiPath('api/users', { id: id })
|
||||
await fetchURL(apiPath, {
|
||||
method: "DELETE",
|
||||
});
|
||||
method: 'DELETE'
|
||||
})
|
||||
} catch (err) {
|
||||
notify.showError(err.message || `Failed to delete user with ID: ${id}`);
|
||||
throw err;
|
||||
notify.showError(err.message || `Failed to delete user with ID: ${id}`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
@@ -49,7 +49,7 @@ export default {
|
||||
return state.req;
|
||||
},
|
||||
multistate() {
|
||||
if (!state.multiButtonState) {
|
||||
if (!state.multiButtonState && getters.currentView() == "settings") {
|
||||
return "close";
|
||||
}
|
||||
return state.multiButtonState;
|
||||
@@ -63,23 +63,30 @@ export default {
|
||||
},
|
||||
watch: {
|
||||
$route() {
|
||||
this.reEvalAction()
|
||||
this.reEvalAction();
|
||||
},
|
||||
req() {
|
||||
this.reEvalAction()
|
||||
this.reEvalAction();
|
||||
},
|
||||
currentView() {
|
||||
this.reEvalAction()
|
||||
this.reEvalAction();
|
||||
},
|
||||
},
|
||||
methods: {
|
||||
reEvalAction() {
|
||||
const currentView = getters.currentView()
|
||||
if (currentView == "settings" ) {
|
||||
const currentView = getters.currentView();
|
||||
if (currentView == "settings") {
|
||||
mutations.setActiveSettingsView(getters.currentHash());
|
||||
mutations.setMultiButtonState("close")
|
||||
} else if (currentView == "editor" || currentView == "preview" || currentView == "onlyOfficeEditor" || currentView == "markdownViewer") {
|
||||
mutations.setMultiButtonState("close")
|
||||
mutations.setMultiButtonState("close");
|
||||
} else if (
|
||||
currentView == "editor" ||
|
||||
currentView == "preview" ||
|
||||
currentView == "onlyOfficeEditor" ||
|
||||
currentView == "markdownViewer" ||
|
||||
currentView == "epubViewer" ||
|
||||
currentView == "docViewer"
|
||||
) {
|
||||
mutations.setMultiButtonState("close");
|
||||
} else {
|
||||
mutations.setMultiButtonState("menu");
|
||||
}
|
||||
@@ -121,7 +128,8 @@ export default {
|
||||
stroke: var(--textPrimary);
|
||||
stroke-width: 5.5;
|
||||
stroke-linecap: round;
|
||||
transition: stroke 400ms ease, transform 400ms ease, opacity 400ms ease, stroke-dasharray 400ms ease, stroke-dashoffset 400ms ease;
|
||||
transition: stroke 400ms ease, transform 400ms ease, opacity 400ms ease,
|
||||
stroke-dasharray 400ms ease, stroke-dashoffset 400ms ease;
|
||||
transform-origin: 50% 50%;
|
||||
}
|
||||
|
||||
@@ -150,7 +158,7 @@ export default {
|
||||
|
||||
/* Back (Arrow) */
|
||||
.ham5.back .top {
|
||||
transform: translate(0,0.2em) rotate(45deg) scaleX(0.5);
|
||||
transform: translate(0, 0.2em) rotate(45deg) scaleX(0.5);
|
||||
}
|
||||
|
||||
.ham5.back .bottom {
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
</li>
|
||||
</ul>
|
||||
<div v-if="isCardView" class="gallery-size">
|
||||
Size:
|
||||
{{ $t("files.size") }}<span class="sr-only">:</span> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
|
||||
<input
|
||||
v-model="gallerySize"
|
||||
type="range"
|
||||
@@ -215,6 +215,7 @@ export default {
|
||||
}
|
||||
|
||||
.gallery-size {
|
||||
display: flex;
|
||||
background: var(--alt-background);
|
||||
width: fit-content;
|
||||
padding: 0.5em;
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
:class="{ 'dark-mode': isDarkMode, centered: centered }"
|
||||
>
|
||||
<div v-if="selectedCount > 0" class="button selected-count-header">
|
||||
<span>{{ selectedCount }} selected</span>
|
||||
<span>{{ selectedCount }} {{ $t("prompts.selected") }} </span>
|
||||
</div>
|
||||
|
||||
<action
|
||||
@@ -55,7 +55,7 @@
|
||||
@action="toggleMultipleSelection"
|
||||
/>
|
||||
<action
|
||||
v-if="!showCreate && selectedCount > 0"
|
||||
v-if="(!showCreate && selectedCount > 0)"
|
||||
icon="file_download"
|
||||
:label="$t('buttons.download')"
|
||||
@action="startDownload"
|
||||
@@ -103,14 +103,10 @@
|
||||
class="button no-select"
|
||||
:class="{ 'dark-mode': isDarkMode }"
|
||||
>
|
||||
<action
|
||||
v-if="showDelete"
|
||||
icon="delete"
|
||||
:label="$t('buttons.delete')"
|
||||
show="delete"
|
||||
/>
|
||||
<action v-if="isPreview" icon="file_download" :label="$t('buttons.download')" @action="startDownload" />
|
||||
<action v-if="showEdit" icon="edit" :label="$t('buttons.edit')" @action="edit()" />
|
||||
<action v-if="showSave" icon="save" :label="$t('buttons.save')" @action="save()" />
|
||||
<action v-if="showEdit" icon="edit" @action="edit()" />
|
||||
<action v-if="showDelete" icon="delete" :label="$t('buttons.delete')" show="delete" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -137,13 +133,23 @@ export default {
|
||||
},
|
||||
computed: {
|
||||
noItems() {
|
||||
return !this.showEdit && !this.showSave && !this.showDelete
|
||||
return !this.showEdit && !this.showSave && !this.showDelete;
|
||||
},
|
||||
showEdit() {
|
||||
return window.location.hash == "#edit" && state.user.permissions.modify;
|
||||
return getters.currentView() == "markdownViewer" && state.user.permissions.modify;
|
||||
},
|
||||
showDelete() {
|
||||
return state.user.permissions.modify && getters.currentView() == "preview"
|
||||
return state.user.permissions.modify && this.isPreview;
|
||||
},
|
||||
isPreview() {
|
||||
const cv = getters.currentView();
|
||||
return (
|
||||
cv == "preview" ||
|
||||
cv == "onlyOfficeEditor" ||
|
||||
cv == "markdownViewer" ||
|
||||
cv == "epubViewer" ||
|
||||
cv == "docViewer"
|
||||
);
|
||||
},
|
||||
showSave() {
|
||||
return getters.currentView() == "editor" && state.user.permissions.modify;
|
||||
@@ -265,6 +271,7 @@ export default {
|
||||
buttons.done(button);
|
||||
notify.showError("Error saving file: ", e);
|
||||
}
|
||||
|
||||
mutations.closeHovers();
|
||||
},
|
||||
},
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<div class="card" id="popup-notification">
|
||||
<i v-on:click="closePopUp" class="material-icons">close</i>
|
||||
<canvas class="notification-spinner hidden" width="100" height="100"></canvas>
|
||||
<div id="popup-notification-content">no info</div>
|
||||
<div id="popup-notification-content"></div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -81,25 +81,23 @@
|
||||
<!-- Inputs for filtering by file size -->
|
||||
<div class="sizeConstraints">
|
||||
<div class="sizeInputWrapper">
|
||||
<p>Smaller Than:</p>
|
||||
<p>{{ $t("search.smallerThan") }}</p>
|
||||
<input
|
||||
class="sizeInput"
|
||||
v-model="smallerThan"
|
||||
type="number"
|
||||
min="0"
|
||||
placeholder="number"
|
||||
/>
|
||||
<p>MB</p>
|
||||
/><p>MB</p> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
|
||||
</div>
|
||||
<div class="sizeInputWrapper">
|
||||
<p>Larger Than:</p>
|
||||
<p>{{ $t("search.largerThan") }}</p>
|
||||
<input
|
||||
class="sizeInput"
|
||||
v-model="largerThan"
|
||||
type="number"
|
||||
placeholder="number"
|
||||
/>
|
||||
<p>MB</p>
|
||||
/><p>MB</p> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -112,27 +110,12 @@
|
||||
<!-- Message when no results are found -->
|
||||
<div class="searchPrompt" v-show="isEmpty && !isRunning">
|
||||
<p>{{ noneMessage }}</p>
|
||||
<div class="helpButton" @click="toggleHelp()">Help</div>
|
||||
<div class="helpButton" @click="toggleHelp()">{{ $t("sidebar.help") }}</div>
|
||||
</div>
|
||||
<!-- Help text section -->
|
||||
<div class="helpText" v-if="showHelp">
|
||||
<p>
|
||||
Search occurs on each character you type (3 character minimum for search
|
||||
terms).
|
||||
</p>
|
||||
<p>
|
||||
<b>The index:</b> Search utilizes the index which automatically gets updated
|
||||
on the configured interval (default: 5 minutes). Searching when the program
|
||||
has just started may result in incomplete results.
|
||||
</p>
|
||||
<p>
|
||||
<b>Filter by type:</b> You can have multiple type filters by adding
|
||||
<code>type:condition</code> followed by search terms.
|
||||
</p>
|
||||
<p>
|
||||
<b>Multiple Search terms:</b> Additional terms separated by <code>|</code>,
|
||||
for example <code>"test|not"</code> searches for both terms independently.
|
||||
</p>
|
||||
<p>{{ $t("search.helpText1") }}</p>
|
||||
<p>{{ $t("search.helpText2") }}</p>
|
||||
</div>
|
||||
<!-- List of search results -->
|
||||
<ul v-show="results.length > 0">
|
||||
@@ -144,9 +127,9 @@
|
||||
:aria-label="baseName(s.path)"
|
||||
>
|
||||
<a :href="getRelative(s.path)" @contextmenu="addSelected(event, s)">
|
||||
<Icon :mimetype="s.type" />
|
||||
<Icon :mimetype="s.type" :filename="s.name" />
|
||||
<span class="text-container">
|
||||
{{ basePath(s.path, s.type == "directory") }}/{{ baseName(s.path) }}/
|
||||
{{ basePath(s.path, s.type == "directory") }}/{{ baseName(s.path) }}/<!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
|
||||
</span>
|
||||
<div class="filesize">{{ humanSize(s.size) }}</div>
|
||||
</a>
|
||||
@@ -409,11 +392,12 @@ export default {
|
||||
if (path.startsWith("/")) {
|
||||
path = path.slice(1); // remove leading slash
|
||||
}
|
||||
const encodedPath = encodeURIComponent(path).replace("/%20/g", "/");
|
||||
let fullpath = path;
|
||||
if (serverHasMultipleSources) {
|
||||
fullpath = "/files/" + this.selectedSource + "/" + encodeURIComponent(path);
|
||||
fullpath = "/files/" + this.selectedSource + "/" + encodedPath;
|
||||
} else {
|
||||
fullpath = "/files/" + encodeURIComponent(path);
|
||||
fullpath = "/files/" + encodedPath;
|
||||
}
|
||||
return fullpath;
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<div class="image-ex-container" ref="container" @touchstart="touchStart" @touchmove="touchMove" @dblclick="zoomAuto"
|
||||
@mousedown="mousedownStart" @mousemove="mouseMove" @mouseup="mouseUp" @wheel="wheelMove">
|
||||
<div v-if="!isLoaded">Loading image...</div>
|
||||
<div v-if="!isLoaded">{{ $t('files.loading') }}</div>
|
||||
|
||||
<img v-if="!isTiff && isLoaded" :src="src" class="image-ex-img" ref="imgex" @load="onLoad" />
|
||||
<canvas v-else-if="isLoaded" ref="imgex" class="image-ex-img"></canvas>
|
||||
|
||||
@@ -1,26 +1,48 @@
|
||||
<template>
|
||||
<span v-if="isPreviewImg">
|
||||
<span
|
||||
@mouseenter="handleMouseEnter($event)"
|
||||
@mouseleave="handleMouseLeave($event)"
|
||||
v-if="isPreviewImg && imageState !== 'error'"
|
||||
>
|
||||
<i
|
||||
v-if="hasMotion"
|
||||
class="material-icons"
|
||||
:class="{ larger: showLarger, smaller: !showLarger }"
|
||||
>animation</i
|
||||
>
|
||||
<img
|
||||
@mouseenter="handleMouseEnter($event)"
|
||||
@mouseleave="handleMouseLeave($event)"
|
||||
v-lazy="thumbnailUrl"
|
||||
:key="imageTargetSrc"
|
||||
:src="imageDisplaySrc"
|
||||
class="icon"
|
||||
ref="thumbnail"
|
||||
/>
|
||||
</span>
|
||||
<span v-else>
|
||||
<!-- Material Icon -->
|
||||
<i :class="[classes, { active: active }]" class="icon"> {{ materialIcon }} </i>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { onlyOfficeUrl, mediaAvailable } from "@/utils/constants";
|
||||
import {
|
||||
onlyOfficeUrl,
|
||||
mediaAvailable,
|
||||
muPdfAvailable,
|
||||
baseURL,
|
||||
} from "@/utils/constants";
|
||||
import { getTypeInfo } from "@/utils/mimetype";
|
||||
import { mutations, state } from "@/store";
|
||||
|
||||
// NEW: Define placeholder and error image URLs for easy configuration
|
||||
const PLACEHOLDER_URL = baseURL + "static/img/placeholder.png"; // A generic loading placeholder
|
||||
const ERROR_URL = baseURL + "static/img/placeholder.png";
|
||||
|
||||
export default {
|
||||
name: "Icon",
|
||||
props: {
|
||||
filename: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
mimetype: {
|
||||
type: String,
|
||||
required: true,
|
||||
@@ -38,9 +60,67 @@ export default {
|
||||
materialIcon: "",
|
||||
classes: "",
|
||||
svgPath: "",
|
||||
previewTimeouts: [],
|
||||
// UPDATED: Manage image state directly
|
||||
imageState: "loading", // Can be 'loading', 'loaded', or 'error'
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
imageTargetSrc() {
|
||||
if (this.showLargeIcon) {
|
||||
// Use the large version of the thumbnail if available
|
||||
return this.thumbnailUrl + "&size=large" || PLACEHOLDER_URL;
|
||||
}
|
||||
return this.thumbnailUrl || PLACEHOLDER_URL;
|
||||
},
|
||||
pdfConvertable() {
|
||||
const ext = "." + this.filename.split(".").pop().toLowerCase(); // Ensure lowercase and dot
|
||||
const pdfConvertCompatibleFileExtensions = {
|
||||
".pdf": true,
|
||||
".xps": true,
|
||||
".epub": true,
|
||||
".mobi": true,
|
||||
".fb2": true,
|
||||
".cbz": true,
|
||||
".svg": true,
|
||||
".txt": true,
|
||||
".docx": true,
|
||||
".ppt": true,
|
||||
".pptx": true,
|
||||
".xlsx": true,
|
||||
".hwp": true,
|
||||
".hwpx": true,
|
||||
".md": true,
|
||||
};
|
||||
const textType = this.mimetype.startsWith("text/");
|
||||
const disabled = state.user.disableOfficePreviewExt?.includes(ext);
|
||||
return (!!pdfConvertCompatibleFileExtensions[ext] || textType) && !disabled;
|
||||
},
|
||||
// NEW: A single computed property to determine the final image src
|
||||
imageDisplaySrc() {
|
||||
if (this.imageState === "error") {
|
||||
return ERROR_URL;
|
||||
}
|
||||
// Show placeholder only for the initial load, not during hover animations
|
||||
if (this.imageState === "loading" && this.imageTargetSrc === this.thumbnailUrl) {
|
||||
return PLACEHOLDER_URL;
|
||||
}
|
||||
return this.imageTargetSrc;
|
||||
},
|
||||
showLargeIcon() {
|
||||
return state.user.viewMode === "gallery" && state.user.preview.highQuality;
|
||||
},
|
||||
showLarger() {
|
||||
return state.user.viewMode === "gallery" || state.user.viewMode === "normal";
|
||||
},
|
||||
hasMotion() {
|
||||
return (
|
||||
this.getIconForType().simpleType === "video" &&
|
||||
state.user.preview?.video &&
|
||||
mediaAvailable &&
|
||||
state.user.preview.motionVideoPreview
|
||||
);
|
||||
},
|
||||
isMaterialIcon() {
|
||||
return this.materialIcon !== "";
|
||||
},
|
||||
@@ -48,10 +128,12 @@ export default {
|
||||
if (this.thumbnailUrl == "") {
|
||||
return false;
|
||||
}
|
||||
// todo support webp previews
|
||||
if (this.mimetype == "text/csv") {
|
||||
return false;
|
||||
}
|
||||
if (this.pdfConvertable && muPdfAvailable) {
|
||||
return true;
|
||||
}
|
||||
if (this.getIconForType().simpleType === "image" && state.user.preview?.image) {
|
||||
return true;
|
||||
}
|
||||
@@ -69,42 +151,126 @@ export default {
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
this.getIconForType().simpleType === "pdf" &&
|
||||
state.user.preview?.office &&
|
||||
onlyOfficeUrl != ""
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
},
|
||||
methods: {
|
||||
handleMouseEnter() {
|
||||
if (state.user.viewMode == "gallery" && !state.user.preview.highQuality) {
|
||||
// skip popup for gallary view with small images
|
||||
// NEW: Centralized method to load any image and handle its state
|
||||
loadImage(url) {
|
||||
if (!url) {
|
||||
this.imageState = "error";
|
||||
return;
|
||||
}
|
||||
mutations.setPreviewSource(this.thumbnailUrl);
|
||||
|
||||
this.imageState = "loading";
|
||||
const targetImage = new Image();
|
||||
|
||||
targetImage.onload = () => {
|
||||
// Prevent race conditions: only update if this is the image we still want.
|
||||
if (this.imageTargetSrc === url) {
|
||||
this.imageState = "loaded";
|
||||
}
|
||||
};
|
||||
|
||||
targetImage.onerror = () => {
|
||||
// Prevent race conditions: only show an error if this is the image that failed.
|
||||
if (this.imageTargetSrc === url) {
|
||||
this.imageState = "error";
|
||||
}
|
||||
};
|
||||
|
||||
targetImage.src = url;
|
||||
},
|
||||
handleMouseEnter() {
|
||||
const imageUrl = this.thumbnailUrl + "&size=large";
|
||||
if (this.imageState == "loaded") {
|
||||
mutations.setPreviewSource(imageUrl);
|
||||
}
|
||||
if (!state.user.preview.motionVideoPreview || !this.hasMotion) {
|
||||
return;
|
||||
}
|
||||
|
||||
const sequence = [
|
||||
imageUrl,
|
||||
imageUrl + "&atPercentage=25",
|
||||
imageUrl + "&atPercentage=50",
|
||||
imageUrl + "&atPercentage=75",
|
||||
];
|
||||
let index = 0;
|
||||
|
||||
const updateThumbnail = () => {
|
||||
if (state.popupPreviewSource === "") {
|
||||
this.previewTimeouts.forEach(clearTimeout);
|
||||
this.previewTimeouts = [];
|
||||
return;
|
||||
}
|
||||
// Set the thumbnail or popup preview
|
||||
if (state.user.preview.popup) {
|
||||
mutations.setPreviewSource(sequence[index]);
|
||||
} else {
|
||||
this.currentThumbnail = sequence[index];
|
||||
}
|
||||
|
||||
// Preload the next image
|
||||
const nextIndex = (index + 1) % sequence.length;
|
||||
const preloadImg = new Image();
|
||||
preloadImg.src = sequence[nextIndex];
|
||||
|
||||
// Schedule next update
|
||||
index = nextIndex;
|
||||
const timeoutId = setTimeout(updateThumbnail, 750);
|
||||
this.previewTimeouts.push(timeoutId);
|
||||
};
|
||||
updateThumbnail();
|
||||
},
|
||||
handleMouseLeave() {
|
||||
this.previewTimeouts.forEach(clearTimeout);
|
||||
this.previewTimeouts = [];
|
||||
mutations.setPreviewSource("");
|
||||
// UPDATED: Reset to the base thumbnail URL. The watcher will handle reloading it.
|
||||
this.imageTargetSrc = this.thumbnailUrl;
|
||||
},
|
||||
getIconForType() {
|
||||
return getTypeInfo(this.mimetype);
|
||||
},
|
||||
},
|
||||
watch: {
|
||||
// UPDATED: Added a check for isPreviewImg
|
||||
imageTargetSrc: {
|
||||
handler(newSrc) {
|
||||
// ONLY trigger the image loader if the component is meant to show a preview.
|
||||
if (this.isPreviewImg) {
|
||||
this.loadImage(newSrc);
|
||||
}
|
||||
},
|
||||
immediate: true, // Run this watcher on component mount
|
||||
},
|
||||
},
|
||||
mounted() {
|
||||
const result = this.getIconForType();
|
||||
this.classes = result.classes || "material-icons"; // Default class
|
||||
this.color = result.color || "lightgray"; // Default color
|
||||
this.classes = result.classes || "material-icons";
|
||||
this.color = result.color || "lightgray";
|
||||
this.materialIcon = result.materialIcon || "";
|
||||
this.svgPath = result.svgPath || ""; // For SVG file paths
|
||||
this.svgPath = result.svgPath || "";
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.larger {
|
||||
position: absolute;
|
||||
opacity: 0.5;
|
||||
padding: 0.1em !important;
|
||||
font-size: 2em !important;
|
||||
}
|
||||
|
||||
.smaller {
|
||||
position: absolute;
|
||||
opacity: 0.5;
|
||||
padding: 0.1em !important;
|
||||
font-size: 1em !important;
|
||||
}
|
||||
|
||||
.file-icons [aria-label^="."] {
|
||||
opacity: 0.33;
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
@mouseup="cancelContext($event)"
|
||||
>
|
||||
<div @click="toggleClick" :class="{ 'gallery-div': galleryView }">
|
||||
<Icon :mimetype="type" :active="isSelected" :thumbnailUrl />
|
||||
<Icon :mimetype="type" :active="isSelected" :thumbnailUrl="thumbnailUrl" :filename="name" />
|
||||
</div>
|
||||
|
||||
<div class="text" :class="{ activecontent: isMaximized && isSelected }">
|
||||
@@ -48,6 +48,7 @@
|
||||
<Icon
|
||||
@click="downloadFile"
|
||||
v-if="quickDownloadEnabled"
|
||||
:filename="name"
|
||||
mimetype="file_download"
|
||||
style="padding-right: 0.5em"
|
||||
/>
|
||||
@@ -364,7 +365,6 @@ export default {
|
||||
mutations.removeSelected(this.index);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.shiftKey && this.selected.length > 0) {
|
||||
let fi = 0;
|
||||
let la = 0;
|
||||
|
||||
@@ -62,7 +62,7 @@ export default {
|
||||
this.popupStyle = {
|
||||
"max-width": "90%",
|
||||
"max-height": "75%",
|
||||
"margin": "1em",
|
||||
margin: "1em",
|
||||
transform: "translate(0, 4em)",
|
||||
};
|
||||
return;
|
||||
@@ -113,6 +113,7 @@ export default {
|
||||
overflow: hidden;
|
||||
z-index: 1000;
|
||||
transition: all 0.3s ease-in-out;
|
||||
background: gray;
|
||||
}
|
||||
|
||||
.popup-preview img {
|
||||
|
||||
@@ -19,9 +19,7 @@
|
||||
<hr />
|
||||
</div>
|
||||
<div v-else class="thumb-letters no-select">
|
||||
<i class="material-icons" :class="{ 'primary-icons': isFolder }">
|
||||
{{ isFolder ? "folder" : "description" }}
|
||||
</i>
|
||||
<i class="material-icons" :class="{ 'primary-icons': isFolder }"> {{ isFolder ? "folder" : "description" }} </i> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
@@ -130,6 +128,7 @@ export default {
|
||||
const content = this.$refs.wrapper;
|
||||
this.isVisible = true;
|
||||
this.scheduleHide();
|
||||
mutations.setPreviewSource("");
|
||||
this.updateThumbPosition(content.scrollTop);
|
||||
mutations.updateListing({
|
||||
...state.listing,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<div class="card floating">
|
||||
<div class="card-title">
|
||||
<h2>API Key Details</h2>
|
||||
<h2>{{ $t('api.title') }}:</h2> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
|
||||
</div>
|
||||
|
||||
<div class="card-content">
|
||||
@@ -11,20 +11,20 @@
|
||||
:aria-label="$t('buttons.copyToClipboard')"
|
||||
:title="$t('buttons.copyToClipboard')"
|
||||
>
|
||||
API Key Name : {{ name }}
|
||||
{{ $t('api.keyName') }}{{ name }}
|
||||
<i class="material-icons">content_paste</i>
|
||||
</button>
|
||||
|
||||
<h3>Created At :</h3>
|
||||
<h3>{{ $t('api.createdAt') }}</h3>
|
||||
{{ formatTime(info.created) }}
|
||||
<h3>Expires At :</h3>
|
||||
<h3>{{ $t('api.expiresAt') }}</h3>
|
||||
{{ formatTime(info.expires) }}
|
||||
<h3>Permissions:</h3>
|
||||
<h3>{{ $t('api.permissions') }}</h3>
|
||||
<table>
|
||||
<tbody>
|
||||
<tr v-for="(isEnabled, permission) in info.Permissions" :key="permission">
|
||||
<td>{{ permission }}</td>
|
||||
<td>{{ isEnabled ? "✓" : "✗" }}</td>
|
||||
<td>{{ isEnabled ? '✓' : '✗' }}</td> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -37,14 +37,14 @@
|
||||
:aria-label="$t('buttons.close')"
|
||||
:title="$t('buttons.close')"
|
||||
>
|
||||
{{ $t("buttons.close") }}
|
||||
{{ $t('buttons.close') }}
|
||||
</button>
|
||||
<button
|
||||
class="button button--flat button--red"
|
||||
@click="deleteApi"
|
||||
:title="$t('buttons.delete')"
|
||||
>
|
||||
{{ $t("buttons.delete") }}
|
||||
{{ $t('buttons.delete') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -34,6 +34,7 @@
|
||||
{{ $t("buttons.cancel") }}
|
||||
</button>
|
||||
<button
|
||||
:disabled="destContainsSrc"
|
||||
class="button button--flat"
|
||||
@click="copy"
|
||||
:aria-label="$t('buttons.copy')"
|
||||
@@ -52,6 +53,7 @@ import FileList from "./FileList.vue";
|
||||
import { filesApi } from "@/api";
|
||||
import buttons from "@/utils/buttons";
|
||||
import * as upload from "@/utils/upload";
|
||||
import { removeLastDir } from "@/utils/url";
|
||||
import { notify } from "@/notify";
|
||||
|
||||
export default {
|
||||
@@ -65,6 +67,14 @@ export default {
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
destContainsSrc() {
|
||||
if (!this.dest) {
|
||||
return false; // If dest is not set, we can't check containment
|
||||
}
|
||||
const itemPath = this.items[0]?.from
|
||||
const parentDir = removeLastDir(itemPath) + "/"
|
||||
return this.dest == parentDir || this.dest.startsWith(itemPath);
|
||||
},
|
||||
user() {
|
||||
return state.user;
|
||||
},
|
||||
|
||||
@@ -1,40 +1,37 @@
|
||||
<template>
|
||||
<div class="card floating create-api__prompt__card" id="create-api">
|
||||
<div class="card-title">
|
||||
<h2>Create API Key</h2>
|
||||
<h2>{{ $t('api.createTitle') }}</h2>
|
||||
</div>
|
||||
|
||||
<div class="card-content">
|
||||
<!-- API Key Name Input -->
|
||||
<p>API Key Name</p>
|
||||
<p>{{ $t('api.keyName') }}</p>
|
||||
<input
|
||||
class="input input--block"
|
||||
type="text"
|
||||
v-model.trim="apiName"
|
||||
placeholder="enter a uinque api key name"
|
||||
:placeholder="$t('api.keyNamePlaceholder')"
|
||||
/>
|
||||
|
||||
<!-- Duration Input -->
|
||||
<p>Token Duration</p>
|
||||
<p>{{ $t('api.tokenDuration') }}</p>
|
||||
<div class="inputWrapper">
|
||||
<input
|
||||
class="sizeInput roundedInputLeft input"
|
||||
v-model.number="duration"
|
||||
type="number"
|
||||
min="1"
|
||||
placeholder="number"
|
||||
:placeholder="$t('api.durationNumberPlaceholder')"
|
||||
/>
|
||||
<select v-model="unit" class="roundedInputRight input">
|
||||
<option value="days">days</option>
|
||||
<option value="months">months</option>
|
||||
<option value="days">{{ $t('api.days') }}</option>
|
||||
<option value="months">{{ $t('api.months') }}</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Permissions Input -->
|
||||
<p>
|
||||
Choose at least one permission for the key. Your User must also have the
|
||||
permission.
|
||||
</p>
|
||||
<p>{{ $t('api.permissionNote') }}</p>
|
||||
<div class="settings-items">
|
||||
<ToggleSwitch
|
||||
v-for="(isEnabled, permission) in permissions"
|
||||
@@ -114,10 +111,10 @@ export default {
|
||||
};
|
||||
|
||||
await usersApi.createApiKey(params);
|
||||
notify.showSuccess("successfully created!");
|
||||
notify.showSuccess($t("api.createKeySuccess"));
|
||||
window.location.reload();
|
||||
} catch (error) {
|
||||
notify.showError(this.$t("errors.createKeyFailed"));
|
||||
notify.showError($t("api.createKeyFailed"));
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<div class="card floating">
|
||||
<div class="card-content">
|
||||
<p>Are you sure you want to delete this user?</p>
|
||||
<p>{{$t('prompts.deleteUserMessage')}}</p>
|
||||
</div>
|
||||
<div class="card-action">
|
||||
<button
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<template>
|
||||
<div>
|
||||
<div aria-label="filelist-path" class="searchContext">Path: {{ nav }}</div>
|
||||
<div>Source: {{ sourcePath.source }} </div> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
|
||||
<div aria-label="filelist-path" class="searchContext">{{$t('search.path')}} {{ sourcePath.path }}</div>
|
||||
<ul class="file-list">
|
||||
<li
|
||||
@click="itemClick"
|
||||
@@ -23,7 +24,7 @@
|
||||
<script>
|
||||
import { state, mutations } from "@/store";
|
||||
import url from "@/utils/url.js";
|
||||
import { removePrefix } from "@/utils/url.js";
|
||||
import { extractSourceFromPath } from "@/utils/url.js";
|
||||
import { filesApi } from "@/api";
|
||||
|
||||
export default {
|
||||
@@ -40,8 +41,8 @@ export default {
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
nav() {
|
||||
return removePrefix(decodeURIComponent(this.current), "files");
|
||||
sourcePath() {
|
||||
return extractSourceFromPath(decodeURIComponent(this.current), "files");
|
||||
},
|
||||
},
|
||||
mounted() {
|
||||
|
||||
Loaded 100 of 167 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user