Compare commits
226 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1a7bc54ea | ||
|
|
8e1815944b | ||
|
|
db924c475a | ||
|
|
d970bb7de7 | ||
|
|
1fa91adae4 | ||
|
|
604487920d | ||
|
|
72e74d421c | ||
|
|
df5fc427ef | ||
|
|
12088154fe | ||
|
|
8ec27734bb | ||
|
|
1e6a0939a2 | ||
|
|
e58daaac83 | ||
|
|
7d0f25e530 | ||
|
|
cba41a1a32 | ||
|
|
997f21fc55 | ||
|
|
4590884a34 | ||
|
|
cc6689ac3a | ||
|
|
3ab225a101 | ||
|
|
b8169b6ebe | ||
|
|
e5b8684e7f | ||
|
|
912c4b4eee | ||
|
|
b8dfd79dfe | ||
|
|
579f3ccd7d | ||
|
|
f5b3ab8db6 | ||
|
|
51f34eaadb | ||
|
|
6699993088 | ||
|
|
4257a775c8 | ||
|
|
331c7bf387 | ||
|
|
4c64aa7d11 | ||
|
|
1f8ec36eef | ||
|
|
586bb63ee7 | ||
|
|
2ca921b01b | ||
|
|
61cf3eb11a | ||
|
|
a1573b2b64 | ||
|
|
de2c2021d7 | ||
|
|
243b12d4c2 | ||
|
|
fa86894550 | ||
|
|
4a1e21baec | ||
|
|
0607e0df2d | ||
|
|
c2f1d07abc | ||
|
|
0d1074b6d9 | ||
|
|
65a53514d5 | ||
|
|
ce68f48fb4 | ||
|
|
5a03c75dc3 | ||
|
|
20d80bb054 | ||
|
|
cbdf3cafb6 | ||
|
|
1259fc1bbc | ||
|
|
4cf1f2f6b4 | ||
|
|
a90bb28cae | ||
|
|
e86dfbe8ff | ||
|
|
437a238aca | ||
|
|
e5fa0772c6 | ||
|
|
ba5c67d9da | ||
|
|
f3d007025e | ||
|
|
e7a39808dd | ||
|
|
2b7aa7a0c9 | ||
|
|
4d8f0c532b | ||
|
|
367e251a0e | ||
|
|
cc6f2f8bec | ||
|
|
007fde8186 | ||
|
|
552f8168ea | ||
|
|
42426e3e69 | ||
|
|
e706391934 | ||
|
|
58ff28f84d | ||
|
|
74a1ecbb89 | ||
|
|
5fa1711a30 | ||
|
|
4bc6a23143 | ||
|
|
b578e2196a | ||
|
|
866375141f | ||
|
|
a3b9807717 | ||
|
|
d47774c828 | ||
|
|
bc4ac5eb9b | ||
|
|
f16ec4b45c | ||
|
|
f8da8bc985 | ||
|
|
0ec589ca74 | ||
|
|
4e4ac88cbe | ||
|
|
0762516a18 | ||
|
|
41272e67a3 | ||
|
|
da7d1db06c | ||
|
|
cc428d3cd6 | ||
|
|
9a54abfe62 | ||
|
|
c50a9b29bd | ||
|
|
3396218ff0 | ||
|
|
04392a7328 | ||
|
|
e1026a1fb4 | ||
|
|
4703e0d36f | ||
|
|
2e1553542b | ||
|
|
438371fc9a | ||
|
|
6712fa580b | ||
|
|
b660404bfe | ||
|
|
6ab8779948 | ||
|
|
dd16a2e836 | ||
|
|
870b5b4079 | ||
|
|
66d485f639 | ||
|
|
684366e050 | ||
|
|
01929c72ea | ||
|
|
802318f903 | ||
|
|
b9acd275a2 | ||
|
|
1809a3638b | ||
|
|
5a83d6736b | ||
|
|
77e1fe83db | ||
|
|
1133f0f826 | ||
|
|
981b42fb5c | ||
|
|
c59d42b601 | ||
|
|
f70fc2d954 | ||
|
|
1aec3744d7 | ||
|
|
25792232e6 | ||
|
|
2869570a20 | ||
|
|
3a4ff6dbb2 | ||
|
|
42134a4849 | ||
|
|
e5c150e83f | ||
|
|
f1a89f5ec4 | ||
|
|
f2d952bf0e | ||
|
|
70733ff846 | ||
|
|
94619341f2 | ||
|
|
36bd2907f8 | ||
|
|
f879944346 | ||
|
|
d821418bca | ||
|
|
a21198be11 | ||
|
|
70042f4489 | ||
|
|
3890a9a416 | ||
|
|
a58b64085d | ||
|
|
90b7f4aaf6 | ||
|
|
2def76df83 | ||
|
|
1db210a24f | ||
|
|
b0586d985c | ||
|
|
a52374e288 | ||
|
|
277f13a350 | ||
|
|
ea434ffc04 | ||
|
|
12b2c21522 | ||
|
|
53a4601361 | ||
|
|
4c7c507830 | ||
|
|
bc8d19feff | ||
|
|
f77009365f | ||
|
|
74e93b8df0 | ||
|
|
901dc2c160 | ||
|
|
b5ee82c943 | ||
|
|
8e4805ba69 | ||
|
|
694c750561 | ||
|
|
efa3b3f198 | ||
|
|
998dd9430d | ||
|
|
c8b5728743 | ||
|
|
fab33e3ed1 | ||
|
|
5079f405fc | ||
|
|
b85a07536d | ||
|
|
7e3a15e073 | ||
|
|
aeb4e2aab3 | ||
|
|
bd65bc9e44 | ||
|
|
59468830bb | ||
|
|
d7c3665e2b | ||
|
|
679b0f0f4e | ||
|
|
7d912dd257 | ||
|
|
a92d7aab8e | ||
|
|
0536d8342c | ||
|
|
93acf4a6f7 | ||
|
|
dd8f47fade | ||
|
|
3f4db6b81e | ||
|
|
e471e79d50 | ||
|
|
6b4bce5daf | ||
|
|
b66adcb582 | ||
|
|
5ec06fa0cd | ||
|
|
c163318ce5 | ||
|
|
98dabff1e7 | ||
|
|
50dcf35eda | ||
|
|
769e634bdd | ||
|
|
dead024e53 | ||
|
|
f4982cff5e | ||
|
|
bfbb7b5ee1 | ||
|
|
7c09473312 | ||
|
|
b6a8472722 | ||
|
|
db01cfa2f0 | ||
|
|
4267ebf0b4 | ||
|
|
d4e9f5ba53 | ||
|
|
4ace991b8a | ||
|
|
e0c91bb747 | ||
|
|
557e5922d2 | ||
|
|
cea4d2aae9 | ||
|
|
bb5c041d5c | ||
|
|
bf1ef5b0f8 | ||
|
|
08ebe0fbb0 | ||
|
|
bdd7c269ed | ||
|
|
292ef7ea8a | ||
|
|
03ab2199d4 | ||
|
|
41489f9e89 | ||
|
|
3bc5f6e0df | ||
|
|
42d33cf595 | ||
|
|
0fbde826bf | ||
|
|
578f3e9bdd | ||
|
|
f1e5cd490e | ||
|
|
40b0cd4b66 | ||
|
|
f9e3923ae7 | ||
|
|
32f7efbde5 | ||
|
|
56e5005484 | ||
|
|
6bf0e8c063 | ||
|
|
7445d73cf6 | ||
|
|
af095a71e7 | ||
|
|
ab87f76dcb | ||
|
|
2cbe941202 | ||
|
|
5e58c25aa4 | ||
|
|
bdfca1be33 | ||
|
|
281b8dca23 | ||
|
|
2761302ddf | ||
|
|
06f0d36dd8 | ||
|
|
a8863ec90b | ||
|
|
3ed5a64cef | ||
|
|
013c24733e | ||
|
|
d9d6fb656a | ||
|
|
eb72c5d959 | ||
|
|
03bdc57334 | ||
|
|
00e80365da | ||
|
|
aeba656a3b | ||
|
|
dd40590ee6 | ||
|
|
3ffb64abcd | ||
|
|
2dbb080fa2 | ||
|
|
f014828ee6 | ||
|
|
bab6b7760b | ||
|
|
e278dbba65 | ||
|
|
5a8c28fa6d | ||
|
|
e7e2edf76c | ||
|
|
dd2d02e492 | ||
|
|
735e74a858 | ||
|
|
7fc2414476 | ||
|
|
822b8f8e05 | ||
|
|
2d63c288e4 | ||
|
|
218a96eebd | ||
|
|
4fbef557ee |
@@ -1,83 +1,108 @@
|
||||
version: 2
|
||||
jobs:
|
||||
linting:
|
||||
lint:
|
||||
docker:
|
||||
- image: circleci/golang:1.10
|
||||
working_directory: /go/src/github.com/filebrowser/filebrowser
|
||||
- image: golangci/golangci-lint:v1.16
|
||||
steps:
|
||||
- checkout
|
||||
- run: golangci-lint run -v -D errcheck
|
||||
build-node:
|
||||
docker:
|
||||
- image: circleci/node
|
||||
steps:
|
||||
- checkout
|
||||
- run:
|
||||
name: Install Dependencies
|
||||
name: "Pull Submodules"
|
||||
command: |
|
||||
curl -sL -o $GOPATH/bin/dep https://github.com/golang/dep/releases/download/v0.4.1/dep-linux-amd64
|
||||
chmod +x $GOPATH/bin/dep
|
||||
dep ensure -v
|
||||
go get github.com/alecthomas/gometalinter
|
||||
gometalinter --install
|
||||
git submodule init
|
||||
git submodule update --remote
|
||||
- run:
|
||||
name: Run linting
|
||||
command: |
|
||||
gometalinter --exclude="rice-box.go" \
|
||||
--deadline=300s \
|
||||
-D goconst \
|
||||
-D gocyclo \
|
||||
-D vetshadow \
|
||||
-D errcheck \
|
||||
-D golint \
|
||||
-D gas
|
||||
build:
|
||||
name: "Build"
|
||||
command: ./wizard.sh -a
|
||||
- run:
|
||||
name: "Cleanup"
|
||||
command: rm -rf frontend/node_modules
|
||||
- persist_to_workspace:
|
||||
root: .
|
||||
paths:
|
||||
- '*'
|
||||
build-go:
|
||||
docker:
|
||||
- image: circleci/golang:1.10
|
||||
working_directory: /go/src/github.com/filebrowser/filebrowser
|
||||
- image: circleci/golang:1.12
|
||||
steps:
|
||||
- checkout
|
||||
- attach_workspace:
|
||||
at: '~/project'
|
||||
- run:
|
||||
name: Install Dependencies
|
||||
name: "Compile"
|
||||
command: ./wizard.sh -c
|
||||
- run:
|
||||
name: "Cleanup"
|
||||
command: |
|
||||
curl -sL -o $GOPATH/bin/dep https://github.com/golang/dep/releases/download/v0.4.1/dep-linux-amd64
|
||||
chmod +x $GOPATH/bin/dep
|
||||
dep ensure -v
|
||||
- run:
|
||||
name: Building
|
||||
command: go build github.com/filebrowser/filebrowser/cmd/filebrowser
|
||||
deploy:
|
||||
rm -rf frontend/build
|
||||
git checkout -- go.sum # TODO: why is it being changed?
|
||||
- persist_to_workspace:
|
||||
root: .
|
||||
paths:
|
||||
- '*'
|
||||
docker-latest:
|
||||
docker:
|
||||
- image: circleci/golang:1.10
|
||||
working_directory: /go/src/github.com/filebrowser/filebrowser
|
||||
- image: docker
|
||||
steps:
|
||||
- checkout
|
||||
- run:
|
||||
name: Install Dependencies
|
||||
command: |
|
||||
curl -sL -o $GOPATH/bin/dep https://github.com/golang/dep/releases/download/v0.4.1/dep-linux-amd64
|
||||
chmod +x $GOPATH/bin/dep
|
||||
dep ensure -v
|
||||
- run:
|
||||
name: Deploy
|
||||
command: curl -sL https://git.io/goreleaser | bash
|
||||
|
||||
- attach_workspace:
|
||||
at: '~/project'
|
||||
- setup_remote_docker
|
||||
- run: docker build -t filebrowser/filebrowser .
|
||||
- run: docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD
|
||||
- run: docker push filebrowser/filebrowser
|
||||
- run: docker logout
|
||||
- persist_to_workspace:
|
||||
root: .
|
||||
paths:
|
||||
- '*'
|
||||
release:
|
||||
docker:
|
||||
- image: circleci/golang:1.12
|
||||
steps:
|
||||
- attach_workspace:
|
||||
at: '~/project'
|
||||
- setup_remote_docker
|
||||
- run: docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD
|
||||
- run: curl -sL https://git.io/goreleaser | bash
|
||||
- run: docker logout
|
||||
workflows:
|
||||
version: 2
|
||||
lint-build-deploy:
|
||||
build-workflow:
|
||||
jobs:
|
||||
- linting:
|
||||
filters:
|
||||
tags:
|
||||
only: /.*/
|
||||
branches:
|
||||
only: /.*/
|
||||
- build:
|
||||
filters:
|
||||
tags:
|
||||
only: /.*/
|
||||
branches:
|
||||
only: /.*/
|
||||
- deploy:
|
||||
requires:
|
||||
- linting
|
||||
- build
|
||||
- lint:
|
||||
filters:
|
||||
tags:
|
||||
only: /v[0-9]+(\.[0-9]+)*(-.*)*/
|
||||
only: /.*/
|
||||
- build-node:
|
||||
filters:
|
||||
tags:
|
||||
only: /.*/
|
||||
- build-go:
|
||||
filters:
|
||||
tags:
|
||||
only: /.*/
|
||||
requires:
|
||||
- build-node
|
||||
- lint
|
||||
- release:
|
||||
context: deploy
|
||||
requires:
|
||||
- build-go
|
||||
filters:
|
||||
tags:
|
||||
only: /^v.*/
|
||||
branches:
|
||||
ignore: /.*/
|
||||
- docker-latest:
|
||||
context: deploy
|
||||
requires:
|
||||
- build-go
|
||||
filters:
|
||||
branches:
|
||||
only: master
|
||||
tags:
|
||||
ignore: /.*/
|
||||
|
||||
8
.docker.json
Normal file
8
.docker.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"port": 80,
|
||||
"baseURL": "",
|
||||
"address": "",
|
||||
"log": "stdout",
|
||||
"database": "/database.db",
|
||||
"root": "/srv"
|
||||
}
|
||||
@@ -1,2 +1,3 @@
|
||||
testdata/
|
||||
.github/
|
||||
testdata/
|
||||
.github/
|
||||
**.git
|
||||
|
||||
24
.github/ISSUE_TEMPLATE.md
vendored
24
.github/ISSUE_TEMPLATE.md
vendored
@@ -1,24 +0,0 @@
|
||||
### Instructions (remove before submitting):
|
||||
|
||||
1. Are you asking for help with using Caddy or File Manager? Please use our forum instead: https://forum.caddyserver.com.
|
||||
2. If you are filing a bug report, please answer the following questions.
|
||||
3. If your issue is not a bug report, you do not need to use this template.
|
||||
4. If not using with Caddy, ignore questions 1 and 2.
|
||||
|
||||
### 1. Have you downloaded File Manager from caddyserver.com? If yes, when have you done that? If no, and you are running a custom build, which is the revision of File Manager's repository?
|
||||
|
||||
### 2. What is your entire Caddyfile?
|
||||
```text
|
||||
(Put Caddyfile here)
|
||||
```
|
||||
|
||||
### 3. What are you trying to do?
|
||||
|
||||
|
||||
### 4. What did you expect to see?
|
||||
|
||||
|
||||
### 5. What did you see instead (give full error messages and/or log)?
|
||||
|
||||
|
||||
### 6. How can someone who is starting from scratch reproduce this behaviour as minimally as possible?
|
||||
22
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
22
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
---
|
||||
|
||||
**Description**
|
||||
A clear and concise description of what the issue is about. What are you trying to do?
|
||||
|
||||
**Expected behaviour**
|
||||
What did you expect to happen?
|
||||
|
||||
**What is happening instead?**
|
||||
Please, give full error messages and/or log.
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here. If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**How to reproduce?**
|
||||
Tell us how to reproduce this issue. How can someone who is starting from scratch reproduce this behaviour as minimally as possible?
|
||||
|
||||
**Files**
|
||||
A list of relevant files for this issue. Large files can be uploaded one-by-one or in a tarball/zipfile.
|
||||
16
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
16
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
Add a clear and concise description of what the problem is. E.g. *I'm always frustrated when [...]*
|
||||
|
||||
**Describe the solution you'd like**
|
||||
Add a clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
Add a clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
16
.github/PULL_REQUEST_TEMPLATE.md
vendored
Normal file
16
.github/PULL_REQUEST_TEMPLATE.md
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
**Description**
|
||||
Please explain the changes you made here.
|
||||
If the feature changes current behaviour, explain why your solution is better.
|
||||
|
||||
:rotating_light: Before submitting your PR, please read [community](https://github.com/filebrowser/community), and indicate which issues (in any of the repos) are either fixed or closed by this PR. See [GitHub Help: Closing issues using keywords](https://help.github.com/articles/closing-issues-via-commit-messages/).
|
||||
|
||||
- [ ] DO make sure you are requesting to **pull a topic/feature/bugfix branch** (right side). Don't request your master!
|
||||
- [ ] DO make sure you are making a pull request against the **master branch** (left side). Also you should start *your branch* off *our master*.
|
||||
- [ ] DO make sure that File Browser can be successfully built. See [builds](https://github.com/filebrowser/community/blob/master/builds.md) and [development](https://github.com/filebrowser/community/blob/master/development.md).
|
||||
- [ ] DO make sure that related issues are opened in other repositories. I.e., the frontend, caddy plugins or the web page need to be updated accordingly.
|
||||
- [ ] AVOID breaking the continuous integration build.
|
||||
|
||||
**Further comments**
|
||||
If this is a relatively large or complex change, kick off the discussion by explaining why you chose the solution you did, what alternatives you considered, etc.
|
||||
|
||||
:heart: Thank you!
|
||||
18
.gitignore
vendored
18
.gitignore
vendored
@@ -1,13 +1,7 @@
|
||||
.DS_Store
|
||||
node_modules/
|
||||
*/dist/*
|
||||
*.db
|
||||
*.db.lock
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.idea
|
||||
.vscode
|
||||
package-lock.json
|
||||
yarn.lock
|
||||
vendor
|
||||
*.lock
|
||||
*.bak
|
||||
_old
|
||||
rice-box.go
|
||||
.idea/
|
||||
filebrowser
|
||||
|
||||
3
.gitmodules
vendored
Normal file
3
.gitmodules
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
[submodule "frontend"]
|
||||
path = frontend
|
||||
url = https://github.com/filebrowser/frontend
|
||||
@@ -1,33 +1,56 @@
|
||||
build:
|
||||
main: cmd/filebrowser/main.go
|
||||
binary: filebrowser
|
||||
goos:
|
||||
- darwin
|
||||
- linux
|
||||
- windows
|
||||
- freebsd
|
||||
- netbsd
|
||||
- openbsd
|
||||
- dragonfly
|
||||
- solaris
|
||||
goarch:
|
||||
- amd64
|
||||
- 386
|
||||
- arm
|
||||
- arm64
|
||||
ignore:
|
||||
- goos: openbsd
|
||||
goarch: arm
|
||||
goarm: 6
|
||||
- goos: freebsd
|
||||
goarch: arm
|
||||
goarm: 6
|
||||
- goos: linux
|
||||
goarch: arm64
|
||||
|
||||
archive:
|
||||
name_template: "{{.Os}}-{{.Arch}}-{{ .ProjectName }}"
|
||||
format: tar.gz
|
||||
format_overrides:
|
||||
- goos: windows
|
||||
format: zip
|
||||
project_name: filebrowser
|
||||
|
||||
build:
|
||||
env:
|
||||
- CGO_ENABLED=0
|
||||
main: main.go
|
||||
binary: filebrowser
|
||||
goos:
|
||||
- darwin
|
||||
- linux
|
||||
- windows
|
||||
- freebsd
|
||||
- netbsd
|
||||
- openbsd
|
||||
- dragonfly
|
||||
- solaris
|
||||
goarch:
|
||||
- amd64
|
||||
- 386
|
||||
- arm
|
||||
- arm64
|
||||
goarm:
|
||||
- 5
|
||||
- 6
|
||||
- 7
|
||||
ignore:
|
||||
- goos: darwin
|
||||
goarch: 386
|
||||
- goos: openbsd
|
||||
goarch: arm
|
||||
- goos: freebsd
|
||||
goarch: arm
|
||||
- goos: netbsd
|
||||
goarch: arm
|
||||
- goos: solaris
|
||||
goarch: arm
|
||||
|
||||
archives:
|
||||
-
|
||||
name_template: "{{.Os}}-{{.Arch}}{{if .Arm}}v{{.Arm}}{{end}}-{{ .ProjectName }}"
|
||||
format: tar.gz
|
||||
format_overrides:
|
||||
- goos: windows
|
||||
format: zip
|
||||
|
||||
dockers:
|
||||
-
|
||||
goos: linux
|
||||
goarch: amd64
|
||||
goarm: ''
|
||||
image_templates:
|
||||
- "filebrowser/filebrowser:latest"
|
||||
- "filebrowser/filebrowser:{{ .Tag }}"
|
||||
- "filebrowser/filebrowser:v{{ .Major }}"
|
||||
extra_files:
|
||||
- .docker.json
|
||||
|
||||
10
Docker.json
10
Docker.json
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"port": 80,
|
||||
"address": "",
|
||||
"database": "/database.db",
|
||||
"scope": "/srv",
|
||||
"allowCommands": true,
|
||||
"allowEdit": true,
|
||||
"allowNew": true,
|
||||
"commands": []
|
||||
}
|
||||
24
Dockerfile
24
Dockerfile
@@ -1,25 +1,13 @@
|
||||
FROM golang:alpine
|
||||
|
||||
COPY . /go/src/github.com/filebrowser/filebrowser
|
||||
|
||||
WORKDIR /go/src/github.com/filebrowser/filebrowser
|
||||
RUN apk add --no-cache git curl && \
|
||||
curl -fsSL -o /usr/local/bin/dep https://github.com/golang/dep/releases/download/v0.4.1/dep-linux-amd64 && \
|
||||
chmod +x /usr/local/bin/dep
|
||||
RUN dep ensure -vendor-only
|
||||
|
||||
WORKDIR /go/src/github.com/filebrowser/filebrowser/cmd/filebrowser
|
||||
RUN CGO_ENABLED=0 go build -a
|
||||
RUN mv filebrowser /go/bin/filebrowser
|
||||
FROM alpine:latest as certs
|
||||
RUN apk --update add ca-certificates
|
||||
|
||||
FROM scratch
|
||||
COPY --from=0 /go/bin/filebrowser /filebrowser
|
||||
COPY --from=certs /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
||||
|
||||
VOLUME /tmp
|
||||
VOLUME /srv
|
||||
EXPOSE 80
|
||||
|
||||
COPY Docker.json /config.json
|
||||
COPY .docker.json /.filebrowser.json
|
||||
COPY filebrowser /filebrowser
|
||||
|
||||
ENTRYPOINT ["/filebrowser"]
|
||||
CMD ["--config", "/config.json"]
|
||||
ENTRYPOINT [ "/filebrowser" ]
|
||||
|
||||
423
Gopkg.lock
generated
423
Gopkg.lock
generated
@@ -1,423 +0,0 @@
|
||||
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
|
||||
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/BurntSushi/toml"
|
||||
packages = ["."]
|
||||
revision = "a368813c5e648fee92e5f6c30e3944ff9d5e8895"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/GeertJohan/go.rice"
|
||||
packages = [
|
||||
".",
|
||||
"embedded"
|
||||
]
|
||||
revision = "c02ca9a983da5807ddf7d796784928f5be4afd09"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/aead/chacha20"
|
||||
packages = [
|
||||
".",
|
||||
"chacha"
|
||||
]
|
||||
revision = "c8d29375923a8e1d2a0f0dc0fc1d8a0aba5b97ba"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/asdine/storm"
|
||||
packages = [
|
||||
".",
|
||||
"codec",
|
||||
"codec/json",
|
||||
"index",
|
||||
"internal",
|
||||
"q"
|
||||
]
|
||||
revision = "68fc73b635f890fe7ba2f3b15ce80c85b28a744f"
|
||||
version = "v2.0.2"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/bifurcation/mint"
|
||||
packages = [
|
||||
".",
|
||||
"syntax"
|
||||
]
|
||||
revision = "340be3ae8c0ff8edce24cf59e7acdb1432bd5ce5"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/chaseadamsio/goorgeous"
|
||||
packages = ["."]
|
||||
revision = "dcf1ef873b8987bf12596fe6951c48347986eb2f"
|
||||
version = "v1.1.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/codahale/aesnicheck"
|
||||
packages = ["."]
|
||||
revision = "349fcc471aaccc29cd074e1275f1a494323826cd"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/coreos/bbolt"
|
||||
packages = ["."]
|
||||
revision = "583e8937c61f1af6513608ccc75c97b6abdf4ff9"
|
||||
version = "v1.3.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/daaku/go.zipexe"
|
||||
packages = ["."]
|
||||
revision = "a5fe2436ffcb3236e175e5149162b41cd28bd27d"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/dgrijalva/jwt-go"
|
||||
packages = [
|
||||
".",
|
||||
"request"
|
||||
]
|
||||
revision = "dbeaa9332f19a944acb5736b4456cfcc02140e29"
|
||||
version = "v3.1.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/dsnet/compress"
|
||||
packages = [
|
||||
".",
|
||||
"bzip2",
|
||||
"bzip2/internal/sais",
|
||||
"internal",
|
||||
"internal/errors",
|
||||
"internal/prefix"
|
||||
]
|
||||
revision = "cc9eb1d7ad760af14e8f918698f745e80377af4f"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/flynn/go-shlex"
|
||||
packages = ["."]
|
||||
revision = "3f9db97f856818214da2e1057f8ad84803971cff"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/fsnotify/fsnotify"
|
||||
packages = ["."]
|
||||
revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9"
|
||||
version = "v1.4.7"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/gohugoio/hugo"
|
||||
packages = ["parser"]
|
||||
revision = "25e88ccabe9b04c42ffb43528c86743f623fac46"
|
||||
version = "v0.36.1"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/golang/snappy"
|
||||
packages = ["."]
|
||||
revision = "553a641470496b2327abcac10b36396bd98e45c9"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/gorilla/websocket"
|
||||
packages = ["."]
|
||||
revision = "ea4d1f681babbce9545c9c5f3d5194a789c89f5b"
|
||||
version = "v1.2.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/hacdias/fileutils"
|
||||
packages = ["."]
|
||||
revision = "76b1c6ab906773727a1ce2f7fb22830685166f85"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/hacdias/varutils"
|
||||
packages = ["."]
|
||||
revision = "82d3b57f667a756cfc4b1535951b46878881f3e1"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/hashicorp/go-syslog"
|
||||
packages = ["."]
|
||||
revision = "326bf4a7f709d263f964a6a96558676b103f3534"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/hashicorp/golang-lru"
|
||||
packages = [
|
||||
".",
|
||||
"simplelru"
|
||||
]
|
||||
revision = "0fb14efe8c47ae851c0034ed7a448854d3d34cf3"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/hashicorp/hcl"
|
||||
packages = [
|
||||
".",
|
||||
"hcl/ast",
|
||||
"hcl/parser",
|
||||
"hcl/scanner",
|
||||
"hcl/strconv",
|
||||
"hcl/token",
|
||||
"json/parser",
|
||||
"json/scanner",
|
||||
"json/token"
|
||||
]
|
||||
revision = "23c074d0eceb2b8a5bfdbb271ab780cde70f05a8"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/kardianos/osext"
|
||||
packages = ["."]
|
||||
revision = "ae77be60afb1dcacde03767a8c37337fad28ac14"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/lucas-clemente/aes12"
|
||||
packages = ["."]
|
||||
revision = "cd47fb39b79f867c6e4e5cd39cf7abd799f71670"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/lucas-clemente/fnv128a"
|
||||
packages = ["."]
|
||||
revision = "393af48d391698c6ae4219566bfbdfef67269997"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/lucas-clemente/quic-go"
|
||||
packages = [
|
||||
".",
|
||||
"h2quic",
|
||||
"internal/ackhandler",
|
||||
"internal/congestion",
|
||||
"internal/crypto",
|
||||
"internal/flowcontrol",
|
||||
"internal/handshake",
|
||||
"internal/protocol",
|
||||
"internal/utils",
|
||||
"internal/wire",
|
||||
"qerr"
|
||||
]
|
||||
revision = "30851b9a3b4e958490b476fe72adafa67641361a"
|
||||
version = "v0.7.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/lucas-clemente/quic-go-certificates"
|
||||
packages = ["."]
|
||||
revision = "d2f86524cced5186554df90d92529757d22c1cb6"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/magiconair/properties"
|
||||
packages = ["."]
|
||||
revision = "c3beff4c2358b44d0493c7dda585e7db7ff28ae6"
|
||||
version = "v1.7.6"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/mholt/archiver"
|
||||
packages = ["."]
|
||||
revision = "26cf5bb32d07aa4e8d0de15f56ce516f4641d7df"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/mholt/caddy"
|
||||
packages = [
|
||||
".",
|
||||
"caddyfile",
|
||||
"caddyhttp/httpserver",
|
||||
"caddyhttp/staticfiles",
|
||||
"caddytls"
|
||||
]
|
||||
revision = "d3f338ddab9ee24b376b5c9c51e202581e2d43ba"
|
||||
version = "v0.10.11"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/miekg/dns"
|
||||
packages = ["."]
|
||||
revision = "5364553f1ee9cddc7ac8b62dce148309c386695b"
|
||||
version = "v1.0.4"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/mitchellh/mapstructure"
|
||||
packages = ["."]
|
||||
revision = "00c29f56e2386353d58c599509e8dc3801b0d716"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/nwaples/rardecode"
|
||||
packages = ["."]
|
||||
revision = "e06696f847aeda6f39a8f0b7cdff193b7690aef6"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/pelletier/go-toml"
|
||||
packages = ["."]
|
||||
revision = "acdc4509485b587f5e675510c4f2c63e90ff68a8"
|
||||
version = "v1.1.0"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/pierrec/lz4"
|
||||
packages = ["."]
|
||||
revision = "2fcda4cb7018ce05a25959d2fe08c83e3329f169"
|
||||
version = "v1.1"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/pierrec/xxHash"
|
||||
packages = ["xxHash32"]
|
||||
revision = "f051bb7f1d1aaf1b5a665d74fb6b0217712c69f7"
|
||||
version = "v0.1.1"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/robfig/cron"
|
||||
packages = ["."]
|
||||
revision = "b024fc5ea0e34bc3f83d9941c8d60b0622bfaca4"
|
||||
version = "v1"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/russross/blackfriday"
|
||||
packages = ["."]
|
||||
revision = "4048872b16cc0fc2c5fd9eacf0ed2c2fedaa0c8c"
|
||||
version = "v1.5"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/shurcooL/sanitized_anchor_name"
|
||||
packages = ["."]
|
||||
revision = "86672fcb3f950f35f2e675df2240550f2a50762f"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/spf13/afero"
|
||||
packages = [
|
||||
".",
|
||||
"mem"
|
||||
]
|
||||
revision = "bb8f1927f2a9d3ab41c9340aa034f6b803f4359c"
|
||||
version = "v1.0.2"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/spf13/cast"
|
||||
packages = ["."]
|
||||
revision = "8965335b8c7107321228e3e3702cab9832751bac"
|
||||
version = "v1.2.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/spf13/jwalterweatherman"
|
||||
packages = ["."]
|
||||
revision = "7c0cea34c8ece3fbeb2b27ab9b59511d360fb394"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/spf13/pflag"
|
||||
packages = ["."]
|
||||
revision = "e57e3eeb33f795204c1ca35f56c44f83227c6e66"
|
||||
version = "v1.0.0"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/spf13/viper"
|
||||
packages = ["."]
|
||||
revision = "25b30aa063fc18e48662b86996252eabdcf2f0c7"
|
||||
version = "v1.0.0"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/ulikunitz/xz"
|
||||
packages = [
|
||||
".",
|
||||
"internal/hash",
|
||||
"internal/xlog",
|
||||
"lzma"
|
||||
]
|
||||
revision = "0c6b41e72360850ca4f98dc341fd999726ea007f"
|
||||
version = "v0.5.4"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/xenolf/lego"
|
||||
packages = ["acme"]
|
||||
revision = "67c86d860a797ce2483f50d9174d4ed24984bef2"
|
||||
version = "v0.4.1"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/crypto"
|
||||
packages = [
|
||||
"bcrypt",
|
||||
"blowfish",
|
||||
"curve25519",
|
||||
"ed25519",
|
||||
"ed25519/internal/edwards25519",
|
||||
"hkdf",
|
||||
"ocsp"
|
||||
]
|
||||
revision = "49796115aa4b964c318aad4f3084fdb41e9aa067"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/net"
|
||||
packages = [
|
||||
"bpf",
|
||||
"http2",
|
||||
"http2/hpack",
|
||||
"idna",
|
||||
"internal/iana",
|
||||
"internal/socket",
|
||||
"ipv4",
|
||||
"ipv6",
|
||||
"lex/httplex",
|
||||
"publicsuffix"
|
||||
]
|
||||
revision = "cbe0f9307d0156177f9dd5dc85da1a31abc5f2fb"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/sys"
|
||||
packages = ["unix"]
|
||||
revision = "88d2dcc510266da9f7f8c7f34e1940716cab5f5c"
|
||||
|
||||
[[projects]]
|
||||
name = "golang.org/x/text"
|
||||
packages = [
|
||||
"collate",
|
||||
"collate/build",
|
||||
"internal/colltab",
|
||||
"internal/gen",
|
||||
"internal/tag",
|
||||
"internal/triegen",
|
||||
"internal/ucd",
|
||||
"language",
|
||||
"secure/bidirule",
|
||||
"transform",
|
||||
"unicode/bidi",
|
||||
"unicode/cldr",
|
||||
"unicode/norm",
|
||||
"unicode/rangetable"
|
||||
]
|
||||
revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0"
|
||||
version = "v0.3.0"
|
||||
|
||||
[[projects]]
|
||||
name = "gopkg.in/natefinch/lumberjack.v2"
|
||||
packages = ["."]
|
||||
revision = "a96e63847dc3c67d17befa69c303767e2f84e54f"
|
||||
version = "v2.1"
|
||||
|
||||
[[projects]]
|
||||
name = "gopkg.in/square/go-jose.v1"
|
||||
packages = [
|
||||
".",
|
||||
"cipher",
|
||||
"json"
|
||||
]
|
||||
revision = "aa2e30fdd1fe9dd3394119af66451ae790d50e0d"
|
||||
version = "v1.1.0"
|
||||
|
||||
[[projects]]
|
||||
name = "gopkg.in/yaml.v2"
|
||||
packages = ["."]
|
||||
revision = "7f97868eec74b32b0982dd158a51a446d1da7eb5"
|
||||
version = "v2.1.1"
|
||||
|
||||
[solve-meta]
|
||||
analyzer-name = "dep"
|
||||
analyzer-version = 1
|
||||
inputs-digest = "1f68bed4490068370884abaa296aa651c27b3f2e0d0451a1ab567f059d44f820"
|
||||
solver-name = "gps-cdcl"
|
||||
solver-version = 1
|
||||
70
Gopkg.toml
70
Gopkg.toml
@@ -1,70 +0,0 @@
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/GeertJohan/go.rice"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/asdine/storm"
|
||||
version = "2.0.2"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/dgrijalva/jwt-go"
|
||||
version = "3.1.0"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/gohugoio/hugo"
|
||||
version = "0.36.1"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/gorilla/websocket"
|
||||
version = "1.2.0"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/hacdias/fileutils"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/hacdias/varutils"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/mholt/archiver"
|
||||
# TODO: switch to version when it's available
|
||||
# this is for Archiver.Write() which was introduced in 548c791
|
||||
revision = "26cf5bb32d07aa4e8d0de15f56ce516f4641d7df"
|
||||
# version = "2.0.0"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/mholt/caddy"
|
||||
version = "0.10.11"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/mitchellh/mapstructure"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/robfig/cron"
|
||||
version = "1.0.0"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/spf13/pflag"
|
||||
version = "1.0.0"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/spf13/viper"
|
||||
version = "1.0.0"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/crypto"
|
||||
|
||||
[[constraint]]
|
||||
name = "gopkg.in/natefinch/lumberjack.v2"
|
||||
version = "2.1.0"
|
||||
|
||||
[[override]]
|
||||
name = "github.com/russross/blackfriday"
|
||||
version = "^1.0.0"
|
||||
|
||||
[prune]
|
||||
go-tests = true
|
||||
unused-packages = true
|
||||
106
README.md
106
README.md
@@ -1,75 +1,31 @@
|
||||

|
||||
|
||||
# filebrowser
|
||||
|
||||
[](https://circleci.com/gh/filebrowser/filebrowser)
|
||||
[](https://goreportcard.com/report/github.com/filebrowser/filebrowser)
|
||||
[](http://godoc.org/github.com/filebrowser/filebrowser)
|
||||
[](https://github.com/filebrowser/filebrowser/releases/latest)
|
||||
|
||||
filebrowser provides a file managing interface within a specified directory and it can be used to upload, delete, preview, rename and edit your files. It allows the creation of multiple users and each user can have its own directory. It can be used as a standalone app or as a middleware.
|
||||
|
||||
# Table of contents
|
||||
|
||||
+ [Getting started](#getting-started)
|
||||
+ [Features](#features)
|
||||
- [Users](#users)
|
||||
- [Search](#search)
|
||||
+ [Contributing](#contributing)
|
||||
+ [Donate](#donate)
|
||||
|
||||
# Getting started
|
||||
|
||||
You can find the Getting Started guide on the [documentation](https://filebrowser.github.io/quick-start/).
|
||||
|
||||
# Features
|
||||
|
||||
Easy login system.
|
||||
|
||||

|
||||
|
||||
Listings of your files, available in two styles: mosaic and list. You can delete, move, rename, upload and create new files, as well as directories. Single files can be downloaded directly, and multiple files as *.zip*, *.tar*, *.tar.gz*, *.tar.bz2* or *.tar.xz*.
|
||||
|
||||

|
||||
|
||||
File Manager editor is powered by [Codemirror](https://codemirror.net/) and if you're working with markdown files with metadata, both parts will be separated from each other so you can focus on the content.
|
||||
|
||||

|
||||
|
||||
On the settings page, a regular user can set its own custom CSS to personalize the experience and change its password. For admins, they can manage the permissions of each user, set commands which can be executed when certain events are triggered (such as before saving and after saving) and change plugin's settings.
|
||||
|
||||

|
||||
|
||||
We also allow the users to search in the directories and execute commands if allowed.
|
||||
|
||||
## Users
|
||||
|
||||
We support multiple users and each user can have its own scope and custom stylesheet. The administrator is able to choose which permissions should be given to the users, as well as the commands they can execute. Each user also have a set of rules, in which he can be prevented or allowed to access some directories (regular expressions included!).
|
||||
|
||||

|
||||
|
||||
## Search
|
||||
|
||||
File Browser allows you to search through your files and it has some options. By default, your search will be something like this:
|
||||
|
||||
```
|
||||
this are keywords
|
||||
```
|
||||
|
||||
If you search for that it will look at every file that contains "this", "are" or "keywords" on their name. If you want to search for an exact term, you should surround your search by double quotes:
|
||||
|
||||
```
|
||||
"this is the name"
|
||||
```
|
||||
|
||||
That will search for any file that contains "this is the name" on its name. It won't search for each separated term this time.
|
||||
|
||||
By default, every search will be case sensitive. Although, you can make a case insensitive search by adding `case:insensitive` to the search terms, like this:
|
||||
|
||||
```
|
||||
this are keywords case:insensitive
|
||||
```
|
||||
|
||||
# Contributing
|
||||
|
||||
The contributing guidelines can be found [here](https://github.com/filebrowser/community).
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/filebrowser/logo/master/banner.png" width="550"/>
|
||||
</p>
|
||||
|
||||

|
||||
|
||||
[](https://travis-ci.com/filebrowser/filebrowser)
|
||||
[](https://goreportcard.com/report/github.com/filebrowser/filebrowser)
|
||||
[](http://godoc.org/github.com/filebrowser/filebrowser)
|
||||
[](https://github.com/filebrowser/filebrowser/releases/latest)
|
||||
[](http://webchat.freenode.net/?channels=%23filebrowser)
|
||||
|
||||
> ℹ INFO: **This project is not under active development ATM. A small group of developers keeps the project alive, but due to lack of time, we can't continue adding new features or doing deep changes. Please read [#532](https://github.com/filebrowser/filebrowser/issues/532) for more info!**
|
||||
|
||||
filebrowser provides a file managing interface within a specified directory and it can be used to upload, delete, preview, rename and edit your files. It allows the creation of multiple users and each user can have its own directory. It can be used as a standalone app or as a middleware.
|
||||
|
||||
## Features
|
||||
|
||||
Please refer to our docs at [docs.filebrowser.xyz/features](https://docs.filebrowser.xyz/features)
|
||||
|
||||
## Install
|
||||
|
||||
Please refer to our docs at [docs.filebrowser.xyz](https://docs.filebrowser.xyz/).
|
||||
|
||||
## Usage
|
||||
|
||||
Please refer to our docs at [docs.filebrowser.xyz/usage](https://docs.filebrowser.xyz/usage).
|
||||
|
||||
## Contributing
|
||||
|
||||
Please refer to our docs at [docs.filebrowser.xyz/contributing](https://docs.filebrowser.xyz/contributing).
|
||||
|
||||
15
auth/auth.go
Normal file
15
auth/auth.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
// Auther is the authentication interface.
|
||||
type Auther interface {
|
||||
// Auth is called to authenticate a request.
|
||||
Auth(r *http.Request, s *users.Storage, root string) (*users.User, error)
|
||||
// LoginPage indicates if this auther needs a login page.
|
||||
LoginPage() bool
|
||||
}
|
||||
107
auth/json.go
Normal file
107
auth/json.go
Normal file
@@ -0,0 +1,107 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
// MethodJSONAuth is used to identify json auth.
|
||||
const MethodJSONAuth settings.AuthMethod = "json"
|
||||
|
||||
type jsonCred struct {
|
||||
Password string `json:"password"`
|
||||
Username string `json:"username"`
|
||||
ReCaptcha string `json:"recaptcha"`
|
||||
}
|
||||
|
||||
// JSONAuth is a json implementaion 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, sto *users.Storage, root string) (*users.User, error) {
|
||||
var cred jsonCred
|
||||
|
||||
if r.Body == nil {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
|
||||
err := json.NewDecoder(r.Body).Decode(&cred)
|
||||
if err != nil {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
|
||||
// If ReCaptcha is enabled, check the code.
|
||||
if a.ReCaptcha != nil && len(a.ReCaptcha.Secret) > 0 {
|
||||
ok, err := a.ReCaptcha.Ok(cred.ReCaptcha)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !ok {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
}
|
||||
|
||||
u, err := sto.Get(root, cred.Username)
|
||||
if err != nil || !users.CheckPwd(cred.Password, u.Password) {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// LoginPage tells that json auth doesn't require a login page.
|
||||
func (a JSONAuth) LoginPage() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
const reCaptchaAPI = "/recaptcha/api/siteverify"
|
||||
|
||||
// ReCaptcha identifies a recaptcha conenction.
|
||||
type ReCaptcha struct {
|
||||
Host string `json:"host"`
|
||||
Key string `json:"key"`
|
||||
Secret string `json:"secret"`
|
||||
}
|
||||
|
||||
// Ok checks if a reCaptcha responde is correct.
|
||||
func (r *ReCaptcha) Ok(response string) (bool, error) {
|
||||
body := url.Values{}
|
||||
body.Set("secret", r.Key)
|
||||
body.Add("response", response)
|
||||
|
||||
client := &http.Client{}
|
||||
|
||||
resp, err := client.Post(
|
||||
r.Host+reCaptchaAPI,
|
||||
"application/x-www-form-urlencoded",
|
||||
strings.NewReader(body.Encode()),
|
||||
)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
var data struct {
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
err = json.NewDecoder(resp.Body).Decode(&data)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return data.Success, nil
|
||||
}
|
||||
24
auth/none.go
Normal file
24
auth/none.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
// MethodNoAuth is used to identify no auth.
|
||||
const MethodNoAuth settings.AuthMethod = "noauth"
|
||||
|
||||
// NoAuth is no auth implementation of auther.
|
||||
type NoAuth struct{}
|
||||
|
||||
// Auth uses authenticates user 1.
|
||||
func (a NoAuth) Auth(r *http.Request, sto *users.Storage, root string) (*users.User, error) {
|
||||
return sto.Get(root, uint(1))
|
||||
}
|
||||
|
||||
// LoginPage tells that no auth doesn't require a login page.
|
||||
func (a NoAuth) LoginPage() bool {
|
||||
return false
|
||||
}
|
||||
34
auth/proxy.go
Normal file
34
auth/proxy.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/errors"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
// MethodProxyAuth is used to identify no auth.
|
||||
const MethodProxyAuth settings.AuthMethod = "proxy"
|
||||
|
||||
// ProxyAuth is a proxy implementation of an auther.
|
||||
type ProxyAuth struct {
|
||||
Header string `json:"header"`
|
||||
}
|
||||
|
||||
// Auth authenticates the user via an HTTP header.
|
||||
func (a ProxyAuth) Auth(r *http.Request, sto *users.Storage, root string) (*users.User, error) {
|
||||
username := r.Header.Get(a.Header)
|
||||
user, err := sto.Get(root, username)
|
||||
if err == errors.ErrNotExist {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
|
||||
return user, err
|
||||
}
|
||||
|
||||
// LoginPage tells that proxy auth doesn't require a login page.
|
||||
func (a ProxyAuth) LoginPage() bool {
|
||||
return false
|
||||
}
|
||||
33
auth/storage.go
Normal file
33
auth/storage.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
// StorageBackend is a storage backend for auth storage.
|
||||
type StorageBackend interface {
|
||||
Get(settings.AuthMethod) (Auther, error)
|
||||
Save(Auther) error
|
||||
}
|
||||
|
||||
// Storage is a auth storage.
|
||||
type Storage struct {
|
||||
back StorageBackend
|
||||
users *users.Storage
|
||||
}
|
||||
|
||||
// NewStorage creates a auth storage from a backend.
|
||||
func NewStorage(back StorageBackend, users *users.Storage) *Storage {
|
||||
return &Storage{back: back, users: users}
|
||||
}
|
||||
|
||||
// Get wraps a StorageBackend.Get.
|
||||
func (s *Storage) Get(t settings.AuthMethod) (Auther, error) {
|
||||
return s.back.Get(t)
|
||||
}
|
||||
|
||||
// Save wraps a StorageBackend.Save.
|
||||
func (s *Storage) Save(a Auther) error {
|
||||
return s.back.Save(a)
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package bolt
|
||||
|
||||
import (
|
||||
"github.com/asdine/storm"
|
||||
fm "github.com/filebrowser/filebrowser"
|
||||
)
|
||||
|
||||
// ConfigStore is a configuration store.
|
||||
type ConfigStore struct {
|
||||
DB *storm.DB
|
||||
}
|
||||
|
||||
// Get gets a configuration from the database to an interface.
|
||||
func (c ConfigStore) Get(name string, to interface{}) error {
|
||||
err := c.DB.Get("config", name, to)
|
||||
if err == storm.ErrNotFound {
|
||||
return fm.ErrNotExist
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// Save saves a configuration from an interface to the database.
|
||||
func (c ConfigStore) Save(name string, from interface{}) error {
|
||||
return c.DB.Set("config", name, from)
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package bolt
|
||||
|
||||
import (
|
||||
"github.com/asdine/storm"
|
||||
"github.com/asdine/storm/q"
|
||||
fm "github.com/filebrowser/filebrowser"
|
||||
)
|
||||
|
||||
// ShareStore is a shareable links store.
|
||||
type ShareStore struct {
|
||||
DB *storm.DB
|
||||
}
|
||||
|
||||
// Get gets a Share Link from an hash.
|
||||
func (s ShareStore) Get(hash string) (*fm.ShareLink, error) {
|
||||
var v fm.ShareLink
|
||||
err := s.DB.One("Hash", hash, &v)
|
||||
if err == storm.ErrNotFound {
|
||||
return nil, fm.ErrNotExist
|
||||
}
|
||||
|
||||
return &v, err
|
||||
}
|
||||
|
||||
// GetPermanent gets the permanent link from a path.
|
||||
func (s ShareStore) GetPermanent(path string) (*fm.ShareLink, error) {
|
||||
var v fm.ShareLink
|
||||
err := s.DB.Select(q.Eq("Path", path), q.Eq("Expires", false)).First(&v)
|
||||
if err == storm.ErrNotFound {
|
||||
return nil, fm.ErrNotExist
|
||||
}
|
||||
|
||||
return &v, err
|
||||
}
|
||||
|
||||
// GetByPath gets all the links for a specific path.
|
||||
func (s ShareStore) GetByPath(hash string) ([]*fm.ShareLink, error) {
|
||||
var v []*fm.ShareLink
|
||||
err := s.DB.Find("Path", hash, &v)
|
||||
if err == storm.ErrNotFound {
|
||||
return v, fm.ErrNotExist
|
||||
}
|
||||
|
||||
return v, err
|
||||
}
|
||||
|
||||
// Gets retrieves all the shareable links.
|
||||
func (s ShareStore) Gets() ([]*fm.ShareLink, error) {
|
||||
var v []*fm.ShareLink
|
||||
err := s.DB.All(&v)
|
||||
if err == storm.ErrNotFound {
|
||||
return v, fm.ErrNotExist
|
||||
}
|
||||
|
||||
return v, err
|
||||
}
|
||||
|
||||
// Save stores a Share Link on the database.
|
||||
func (s ShareStore) Save(l *fm.ShareLink) error {
|
||||
return s.DB.Save(l)
|
||||
}
|
||||
|
||||
// Delete deletes a Share Link from the database.
|
||||
func (s ShareStore) Delete(hash string) error {
|
||||
return s.DB.DeleteStruct(&fm.ShareLink{Hash: hash})
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
package bolt
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
|
||||
"github.com/asdine/storm"
|
||||
fm "github.com/filebrowser/filebrowser"
|
||||
)
|
||||
|
||||
// UsersStore is a users store.
|
||||
type UsersStore struct {
|
||||
DB *storm.DB
|
||||
}
|
||||
|
||||
// Get gets a user with a certain id from the database.
|
||||
func (u UsersStore) Get(id int, builder fm.FSBuilder) (*fm.User, error) {
|
||||
var us fm.User
|
||||
err := u.DB.One("ID", id, &us)
|
||||
if err == storm.ErrNotFound {
|
||||
return nil, fm.ErrNotExist
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
us.FileSystem = builder(us.Scope)
|
||||
return &us, nil
|
||||
}
|
||||
|
||||
// GetByUsername gets a user with a certain username from the database.
|
||||
func (u UsersStore) GetByUsername(username string, builder fm.FSBuilder) (*fm.User, error) {
|
||||
var us fm.User
|
||||
err := u.DB.One("Username", username, &us)
|
||||
if err == storm.ErrNotFound {
|
||||
return nil, fm.ErrNotExist
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
us.FileSystem = builder(us.Scope)
|
||||
return &us, nil
|
||||
}
|
||||
|
||||
// Gets gets all the users from the database.
|
||||
func (u UsersStore) Gets(builder fm.FSBuilder) ([]*fm.User, error) {
|
||||
var us []*fm.User
|
||||
err := u.DB.All(&us)
|
||||
if err == storm.ErrNotFound {
|
||||
return nil, fm.ErrNotExist
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return us, err
|
||||
}
|
||||
|
||||
for _, user := range us {
|
||||
user.FileSystem = builder(user.Scope)
|
||||
}
|
||||
|
||||
return us, err
|
||||
}
|
||||
|
||||
// Update updates the whole user object or only certain fields.
|
||||
func (u UsersStore) Update(us *fm.User, fields ...string) error {
|
||||
if len(fields) == 0 {
|
||||
return u.Save(us)
|
||||
}
|
||||
|
||||
for _, field := range fields {
|
||||
val := reflect.ValueOf(us).Elem().FieldByName(field).Interface()
|
||||
if err := u.DB.UpdateField(us, field, val); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Save saves a user to the database.
|
||||
func (u UsersStore) Save(us *fm.User) error {
|
||||
return u.DB.Save(us)
|
||||
}
|
||||
|
||||
// Delete deletes a user from the database.
|
||||
func (u UsersStore) Delete(id int) error {
|
||||
return u.DB.DeleteStruct(&fm.User{ID: id})
|
||||
}
|
||||
14
build.sh
14
build.sh
@@ -1,14 +0,0 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# Install rice tool if not present
|
||||
if ! [ -x "$(command -v rice)" ]; then
|
||||
go get github.com/GeertJohan/go.rice/rice
|
||||
fi
|
||||
|
||||
# Clean the dist folder and build the assets
|
||||
rm -rf node_modules
|
||||
npm install
|
||||
|
||||
# Embed the assets using rice
|
||||
rice embed-go
|
||||
@@ -1,52 +0,0 @@
|
||||
package filemanager
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/filebrowser/filebrowser"
|
||||
"github.com/filebrowser/filebrowser/caddy/parser"
|
||||
h "github.com/filebrowser/filebrowser/http"
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func init() {
|
||||
caddy.RegisterPlugin("filemanager", caddy.Plugin{
|
||||
ServerType: "http",
|
||||
Action: setup,
|
||||
})
|
||||
}
|
||||
|
||||
type plugin struct {
|
||||
Next httpserver.Handler
|
||||
Configs []*filebrowser.FileBrowser
|
||||
}
|
||||
|
||||
// ServeHTTP determines if the request is for this plugin, and if all prerequisites are met.
|
||||
func (f plugin) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
for i := range f.Configs {
|
||||
// Checks if this Path should be handled by File Manager.
|
||||
if !httpserver.Path(r.URL.Path).Matches(f.Configs[i].BaseURL) {
|
||||
continue
|
||||
}
|
||||
|
||||
h.Handler(f.Configs[i]).ServeHTTP(w, r)
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
return f.Next.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// setup configures a new FileManager middleware instance.
|
||||
func setup(c *caddy.Controller) error {
|
||||
configs, err := parser.Parse(c, "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
|
||||
return plugin{Configs: configs, Next: next}
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package hugo
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/filebrowser/filebrowser"
|
||||
"github.com/filebrowser/filebrowser/caddy/parser"
|
||||
h "github.com/filebrowser/filebrowser/http"
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func init() {
|
||||
caddy.RegisterPlugin("hugo", caddy.Plugin{
|
||||
ServerType: "http",
|
||||
Action: setup,
|
||||
})
|
||||
}
|
||||
|
||||
type plugin struct {
|
||||
Next httpserver.Handler
|
||||
Configs []*filebrowser.FileBrowser
|
||||
}
|
||||
|
||||
// ServeHTTP determines if the request is for this plugin, and if all prerequisites are met.
|
||||
func (f plugin) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
for i := range f.Configs {
|
||||
// Checks if this Path should be handled by File Manager.
|
||||
if !httpserver.Path(r.URL.Path).Matches(f.Configs[i].BaseURL) {
|
||||
continue
|
||||
}
|
||||
|
||||
h.Handler(f.Configs[i]).ServeHTTP(w, r)
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
return f.Next.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// setup configures a new FileManager middleware instance.
|
||||
func setup(c *caddy.Controller) error {
|
||||
configs, err := parser.Parse(c, "hugo")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
|
||||
return plugin{Configs: configs, Next: next}
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package jekyll
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/filebrowser/filebrowser"
|
||||
"github.com/filebrowser/filebrowser/caddy/parser"
|
||||
h "github.com/filebrowser/filebrowser/http"
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func init() {
|
||||
caddy.RegisterPlugin("jekyll", caddy.Plugin{
|
||||
ServerType: "http",
|
||||
Action: setup,
|
||||
})
|
||||
}
|
||||
|
||||
type plugin struct {
|
||||
Next httpserver.Handler
|
||||
Configs []*filebrowser.FileBrowser
|
||||
}
|
||||
|
||||
// ServeHTTP determines if the request is for this plugin, and if all prerequisites are met.
|
||||
func (f plugin) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
for i := range f.Configs {
|
||||
// Checks if this Path should be handled by File Manager.
|
||||
if !httpserver.Path(r.URL.Path).Matches(f.Configs[i].BaseURL) {
|
||||
continue
|
||||
}
|
||||
|
||||
h.Handler(f.Configs[i]).ServeHTTP(w, r)
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
return f.Next.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// setup configures a new FileManager middleware instance.
|
||||
func setup(c *caddy.Controller) error {
|
||||
configs, err := parser.Parse(c, "jekyll")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
|
||||
return plugin{Configs: configs, Next: next}
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,312 +0,0 @@
|
||||
package parser
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/asdine/storm"
|
||||
"github.com/filebrowser/filebrowser"
|
||||
"github.com/filebrowser/filebrowser/bolt"
|
||||
"github.com/filebrowser/filebrowser/staticgen"
|
||||
"github.com/hacdias/fileutils"
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
var databases = map[string]*storm.DB{}
|
||||
|
||||
// Parse ...
|
||||
func Parse(c *caddy.Controller, plugin string) ([]*filebrowser.FileBrowser, error) {
|
||||
var (
|
||||
configs []*filebrowser.FileBrowser
|
||||
err error
|
||||
)
|
||||
|
||||
for c.Next() {
|
||||
u := &filebrowser.User{
|
||||
Locale: "en",
|
||||
AllowCommands: true,
|
||||
AllowEdit: true,
|
||||
AllowNew: true,
|
||||
AllowPublish: true,
|
||||
Commands: []string{"git", "svn", "hg"},
|
||||
CSS: "",
|
||||
ViewMode: "mosaic",
|
||||
Rules: []*filebrowser.Rule{{
|
||||
Regex: true,
|
||||
Allow: false,
|
||||
Regexp: &filebrowser.Regexp{Raw: "\\/\\..+"},
|
||||
}},
|
||||
}
|
||||
|
||||
baseURL := "/"
|
||||
scope := "."
|
||||
database := ""
|
||||
noAuth := false
|
||||
alterRecaptcha := false
|
||||
reCaptchaKey := ""
|
||||
reCaptchaSecret := ""
|
||||
|
||||
if plugin != "" {
|
||||
baseURL = "/admin"
|
||||
}
|
||||
|
||||
// Get the baseURL and scope
|
||||
args := c.RemainingArgs()
|
||||
|
||||
if plugin == "" {
|
||||
if len(args) >= 1 {
|
||||
baseURL = args[0]
|
||||
}
|
||||
|
||||
if len(args) > 1 {
|
||||
scope = args[1]
|
||||
}
|
||||
} else {
|
||||
if len(args) >= 1 {
|
||||
scope = args[0]
|
||||
}
|
||||
|
||||
if len(args) > 1 {
|
||||
baseURL = args[1]
|
||||
}
|
||||
}
|
||||
|
||||
for c.NextBlock() {
|
||||
switch c.Val() {
|
||||
case "database":
|
||||
if !c.NextArg() {
|
||||
return nil, c.ArgErr()
|
||||
}
|
||||
|
||||
database = c.Val()
|
||||
case "locale":
|
||||
if !c.NextArg() {
|
||||
return nil, c.ArgErr()
|
||||
}
|
||||
|
||||
u.Locale = c.Val()
|
||||
case "allow_commands":
|
||||
if !c.NextArg() {
|
||||
u.AllowCommands = true
|
||||
continue
|
||||
}
|
||||
|
||||
u.AllowCommands, err = strconv.ParseBool(c.Val())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "allow_edit":
|
||||
if !c.NextArg() {
|
||||
u.AllowEdit = true
|
||||
continue
|
||||
}
|
||||
|
||||
u.AllowEdit, err = strconv.ParseBool(c.Val())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "allow_new":
|
||||
if !c.NextArg() {
|
||||
u.AllowNew = true
|
||||
continue
|
||||
}
|
||||
|
||||
u.AllowNew, err = strconv.ParseBool(c.Val())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "allow_publish":
|
||||
if !c.NextArg() {
|
||||
u.AllowPublish = true
|
||||
continue
|
||||
}
|
||||
|
||||
u.AllowPublish, err = strconv.ParseBool(c.Val())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "commands":
|
||||
if !c.NextArg() {
|
||||
return nil, c.ArgErr()
|
||||
}
|
||||
|
||||
u.Commands = strings.Split(c.Val(), " ")
|
||||
case "css":
|
||||
if !c.NextArg() {
|
||||
return nil, c.ArgErr()
|
||||
}
|
||||
|
||||
file := c.Val()
|
||||
css, err := ioutil.ReadFile(file)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
u.CSS = string(css)
|
||||
case "view_mode":
|
||||
if !c.NextArg() {
|
||||
return nil, c.ArgErr()
|
||||
}
|
||||
|
||||
u.ViewMode = c.Val()
|
||||
if u.ViewMode != filebrowser.MosaicViewMode && u.ViewMode != filebrowser.ListViewMode {
|
||||
return nil, c.ArgErr()
|
||||
}
|
||||
case "alternative_recaptcha":
|
||||
if !c.NextArg() {
|
||||
alterRecaptcha = true
|
||||
continue
|
||||
}
|
||||
|
||||
alterRecaptcha, err = strconv.ParseBool(c.Val())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "recaptcha_key":
|
||||
if !c.NextArg() {
|
||||
return nil, c.ArgErr()
|
||||
}
|
||||
|
||||
reCaptchaKey = c.Val()
|
||||
case "recaptcha_secret":
|
||||
if !c.NextArg() {
|
||||
return nil, c.ArgErr()
|
||||
}
|
||||
|
||||
reCaptchaSecret = c.Val()
|
||||
case "no_auth":
|
||||
if !c.NextArg() {
|
||||
noAuth = true
|
||||
continue
|
||||
}
|
||||
|
||||
noAuth, err = strconv.ParseBool(c.Val())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
caddyConf := httpserver.GetConfig(c)
|
||||
|
||||
path := filepath.Join(caddy.AssetsPath(), "filemanager")
|
||||
err := os.MkdirAll(path, 0700)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// if there is a database path and it is not absolute,
|
||||
// it will be relative to Caddy folder.
|
||||
if !filepath.IsAbs(database) && database != "" {
|
||||
database = filepath.Join(path, database)
|
||||
}
|
||||
|
||||
// If there is no database path on the settings,
|
||||
// store one in .caddy/filemanager/name.db.
|
||||
if database == "" {
|
||||
// The name of the database is the hashed value of a string composed
|
||||
// by the host, address path and the baseurl of this File Manager
|
||||
// instance.
|
||||
hasher := md5.New()
|
||||
hasher.Write([]byte(caddyConf.Addr.Host + caddyConf.Addr.Path + baseURL))
|
||||
sha := hex.EncodeToString(hasher.Sum(nil))
|
||||
database = filepath.Join(path, sha+".db")
|
||||
|
||||
fmt.Println("[WARNING] A database is going to be created for your File Manager instance at " + database +
|
||||
". It is highly recommended that you set the 'database' option to '" + sha + ".db'\n")
|
||||
}
|
||||
|
||||
u.Scope = scope
|
||||
u.FileSystem = fileutils.Dir(scope)
|
||||
|
||||
var db *storm.DB
|
||||
if stored, ok := databases[database]; ok {
|
||||
db = stored
|
||||
} else {
|
||||
db, err = storm.Open(database)
|
||||
databases[database] = db
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
recaptchaHost := "https://www.google.com"
|
||||
if alterRecaptcha {
|
||||
recaptchaHost = "https://recaptcha.net"
|
||||
}
|
||||
|
||||
m := &filebrowser.FileBrowser{
|
||||
NoAuth: noAuth,
|
||||
BaseURL: "",
|
||||
PrefixURL: "",
|
||||
ReCaptchaHost: recaptchaHost,
|
||||
ReCaptchaKey: reCaptchaKey,
|
||||
ReCaptchaSecret: reCaptchaSecret,
|
||||
DefaultUser: u,
|
||||
Store: &filebrowser.Store{
|
||||
Config: bolt.ConfigStore{DB: db},
|
||||
Users: bolt.UsersStore{DB: db},
|
||||
Share: bolt.ShareStore{DB: db},
|
||||
},
|
||||
NewFS: func(scope string) filebrowser.FileSystem {
|
||||
return fileutils.Dir(scope)
|
||||
},
|
||||
}
|
||||
|
||||
err = m.Setup()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch plugin {
|
||||
case "hugo":
|
||||
// Initialize the default settings for Hugo.
|
||||
hugo := &staticgen.Hugo{
|
||||
Root: scope,
|
||||
Public: filepath.Join(scope, "public"),
|
||||
Args: []string{},
|
||||
CleanPublic: true,
|
||||
}
|
||||
|
||||
// Attaches Hugo plugin to this file manager instance.
|
||||
err = m.Attach(hugo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "jekyll":
|
||||
// Initialize the default settings for Jekyll.
|
||||
jekyll := &staticgen.Jekyll{
|
||||
Root: scope,
|
||||
Public: filepath.Join(scope, "_site"),
|
||||
Args: []string{},
|
||||
CleanPublic: true,
|
||||
}
|
||||
|
||||
// Attaches Hugo plugin to this file manager instance.
|
||||
err = m.Attach(jekyll)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
m.NoAuth = noAuth
|
||||
m.SetBaseURL(baseURL)
|
||||
m.SetPrefixURL(strings.TrimSuffix(caddyConf.Addr.Path, "/"))
|
||||
|
||||
configs = append(configs, m)
|
||||
}
|
||||
|
||||
return configs, nil
|
||||
}
|
||||
12
cmd/cmd.go
Normal file
12
cmd/cmd.go
Normal file
@@ -0,0 +1,12 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"log"
|
||||
)
|
||||
|
||||
// Execute executes the commands.
|
||||
func Execute() {
|
||||
if err := rootCmd.Execute(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
26
cmd/cmds.go
Normal file
26
cmd/cmds.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(cmdsCmd)
|
||||
}
|
||||
|
||||
var cmdsCmd = &cobra.Command{
|
||||
Use: "cmds",
|
||||
Short: "Command runner management utility",
|
||||
Long: `Command runner management utility.`,
|
||||
Args: cobra.NoArgs,
|
||||
}
|
||||
|
||||
func printEvents(m map[string][]string) {
|
||||
for evt, cmds := range m {
|
||||
for i, cmd := range cmds {
|
||||
fmt.Printf("%s(%d): %s\n", evt, i, cmd)
|
||||
}
|
||||
}
|
||||
}
|
||||
27
cmd/cmds_add.go
Normal file
27
cmd/cmds_add.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
cmdsCmd.AddCommand(cmdsAddCmd)
|
||||
}
|
||||
|
||||
var cmdsAddCmd = &cobra.Command{
|
||||
Use: "add <event> <command>",
|
||||
Short: "Add a command to run on a specific event",
|
||||
Long: `Add a command to run on a specific event.`,
|
||||
Args: cobra.MinimumNArgs(2),
|
||||
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
|
||||
s, err := d.store.Settings.Get()
|
||||
checkErr(err)
|
||||
command := strings.Join(args[1:], " ")
|
||||
s.Commands[args[0]] = append(s.Commands[args[0]], command)
|
||||
err = d.store.Settings.Save(s)
|
||||
checkErr(err)
|
||||
printEvents(s.Commands)
|
||||
}, pythonConfig{}),
|
||||
}
|
||||
31
cmd/cmds_ls.go
Normal file
31
cmd/cmds_ls.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
cmdsCmd.AddCommand(cmdsLsCmd)
|
||||
cmdsLsCmd.Flags().StringP("event", "e", "", "event name, without 'before' or 'after'")
|
||||
}
|
||||
|
||||
var cmdsLsCmd = &cobra.Command{
|
||||
Use: "ls",
|
||||
Short: "List all commands for each event",
|
||||
Long: `List all commands for each event.`,
|
||||
Args: cobra.NoArgs,
|
||||
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
|
||||
s, err := d.store.Settings.Get()
|
||||
checkErr(err)
|
||||
evt := mustGetString(cmd.Flags(), "event")
|
||||
|
||||
if evt == "" {
|
||||
printEvents(s.Commands)
|
||||
} else {
|
||||
show := map[string][]string{}
|
||||
show["before_"+evt] = s.Commands["before_"+evt]
|
||||
show["after_"+evt] = s.Commands["after_"+evt]
|
||||
printEvents(show)
|
||||
}
|
||||
}, pythonConfig{}),
|
||||
}
|
||||
56
cmd/cmds_rm.go
Normal file
56
cmd/cmds_rm.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
cmdsCmd.AddCommand(cmdsRmCmd)
|
||||
}
|
||||
|
||||
var cmdsRmCmd = &cobra.Command{
|
||||
Use: "rm <event> <index> [index_end]",
|
||||
Short: "Removes a command from an event hooker",
|
||||
Long: `Removes a command from an event hooker. The provided index
|
||||
is the same that's printed when you run 'cmds ls'. Note
|
||||
that after each removal/addition, the index of the
|
||||
commands change. So be careful when removing them after each
|
||||
other.
|
||||
|
||||
You can also specify an optional parameter (index_end) so
|
||||
you can remove all commands from 'index' to 'index_end',
|
||||
including 'index_end'.`,
|
||||
Args: func(cmd *cobra.Command, args []string) error {
|
||||
if err := cobra.RangeArgs(2, 3)(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, arg := range args[1:] {
|
||||
if _, err := strconv.Atoi(arg); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
|
||||
s, err := d.store.Settings.Get()
|
||||
checkErr(err)
|
||||
evt := args[0]
|
||||
|
||||
i, err := strconv.Atoi(args[1])
|
||||
checkErr(err)
|
||||
f := i
|
||||
if len(args) == 3 {
|
||||
f, err = strconv.Atoi(args[2])
|
||||
checkErr(err)
|
||||
}
|
||||
|
||||
s.Commands[evt] = append(s.Commands[evt][:i], s.Commands[evt][f+1:]...)
|
||||
err = d.store.Settings.Save(s)
|
||||
checkErr(err)
|
||||
printEvents(s.Commands)
|
||||
}, pythonConfig{}),
|
||||
}
|
||||
129
cmd/config.go
Normal file
129
cmd/config.go
Normal file
@@ -0,0 +1,129 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
nerrors "errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/auth"
|
||||
"github.com/filebrowser/filebrowser/v2/errors"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(configCmd)
|
||||
}
|
||||
|
||||
var configCmd = &cobra.Command{
|
||||
Use: "config",
|
||||
Short: "Configuration management utility",
|
||||
Long: `Configuration management utility.`,
|
||||
Args: cobra.NoArgs,
|
||||
}
|
||||
|
||||
func addConfigFlags(flags *pflag.FlagSet) {
|
||||
addServerFlags(flags)
|
||||
addUserFlags(flags)
|
||||
flags.BoolP("signup", "s", false, "allow users to signup")
|
||||
flags.String("shell", "", "shell command to which other commands should be appended")
|
||||
|
||||
flags.String("auth.method", string(auth.MethodJSONAuth), "authentication type")
|
||||
flags.String("auth.header", "", "HTTP header for auth.method=proxy")
|
||||
|
||||
flags.String("recaptcha.host", "https://www.google.com", "use another host for ReCAPTCHA. recaptcha.net might be useful in China")
|
||||
flags.String("recaptcha.key", "", "ReCaptcha site key")
|
||||
flags.String("recaptcha.secret", "", "ReCaptcha secret")
|
||||
|
||||
flags.String("branding.name", "", "replace 'File Browser' by this name")
|
||||
flags.String("branding.files", "", "path to directory with images and custom styles")
|
||||
flags.Bool("branding.disableExternal", false, "disable external links such as GitHub links")
|
||||
}
|
||||
|
||||
func getAuthentication(flags *pflag.FlagSet) (settings.AuthMethod, auth.Auther) {
|
||||
method := settings.AuthMethod(mustGetString(flags, "auth.method"))
|
||||
|
||||
var auther auth.Auther
|
||||
if method == auth.MethodProxyAuth {
|
||||
header := mustGetString(flags, "auth.header")
|
||||
if header == "" {
|
||||
panic(nerrors.New("you must set the flag 'auth.header' for method 'proxy'"))
|
||||
}
|
||||
auther = &auth.ProxyAuth{Header: header}
|
||||
}
|
||||
|
||||
if method == auth.MethodNoAuth {
|
||||
auther = &auth.NoAuth{}
|
||||
}
|
||||
|
||||
if method == auth.MethodJSONAuth {
|
||||
jsonAuth := &auth.JSONAuth{}
|
||||
|
||||
host := mustGetString(flags, "recaptcha.host")
|
||||
key := mustGetString(flags, "recaptcha.key")
|
||||
secret := mustGetString(flags, "recaptcha.secret")
|
||||
|
||||
if key != "" && secret != "" {
|
||||
jsonAuth.ReCaptcha = &auth.ReCaptcha{
|
||||
Host: host,
|
||||
Key: key,
|
||||
Secret: secret,
|
||||
}
|
||||
}
|
||||
|
||||
auther = jsonAuth
|
||||
}
|
||||
|
||||
if auther == nil {
|
||||
panic(errors.ErrInvalidAuthMethod)
|
||||
}
|
||||
|
||||
return method, auther
|
||||
}
|
||||
|
||||
func printSettings(ser *settings.Server, set *settings.Settings, auther auth.Auther) {
|
||||
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
|
||||
|
||||
fmt.Fprintf(w, "Sign up:\t%t\n", set.Signup)
|
||||
fmt.Fprintf(w, "Create User Dir:\t%t\n", set.CreateUserDir)
|
||||
fmt.Fprintf(w, "Auth method:\t%s\n", set.AuthMethod)
|
||||
fmt.Fprintf(w, "Shell:\t%s\t\n", strings.Join(set.Shell, " "))
|
||||
fmt.Fprintln(w, "\nBranding:")
|
||||
fmt.Fprintf(w, "\tName:\t%s\n", set.Branding.Name)
|
||||
fmt.Fprintf(w, "\tFiles override:\t%s\n", set.Branding.Files)
|
||||
fmt.Fprintf(w, "\tDisable external links:\t%t\n", set.Branding.DisableExternal)
|
||||
fmt.Fprintln(w, "\nServer:")
|
||||
fmt.Fprintf(w, "\tLog:\t%s\n", ser.Log)
|
||||
fmt.Fprintf(w, "\tPort:\t%s\n", ser.Port)
|
||||
fmt.Fprintf(w, "\tBase URL:\t%s\n", ser.BaseURL)
|
||||
fmt.Fprintf(w, "\tRoot:\t%s\n", ser.Root)
|
||||
fmt.Fprintf(w, "\tAddress:\t%s\n", ser.Address)
|
||||
fmt.Fprintf(w, "\tTLS Cert:\t%s\n", ser.TLSCert)
|
||||
fmt.Fprintf(w, "\tTLS Key:\t%s\n", ser.TLSKey)
|
||||
fmt.Fprintln(w, "\nDefaults:")
|
||||
fmt.Fprintf(w, "\tScope:\t%s\n", set.Defaults.Scope)
|
||||
fmt.Fprintf(w, "\tLocale:\t%s\n", set.Defaults.Locale)
|
||||
fmt.Fprintf(w, "\tView mode:\t%s\n", set.Defaults.ViewMode)
|
||||
fmt.Fprintf(w, "\tCommands:\t%s\n", strings.Join(set.Defaults.Commands, " "))
|
||||
fmt.Fprintf(w, "\tSorting:\n")
|
||||
fmt.Fprintf(w, "\t\tBy:\t%s\n", set.Defaults.Sorting.By)
|
||||
fmt.Fprintf(w, "\t\tAsc:\t%t\n", set.Defaults.Sorting.Asc)
|
||||
fmt.Fprintf(w, "\tPermissions:\n")
|
||||
fmt.Fprintf(w, "\t\tAdmin:\t%t\n", set.Defaults.Perm.Admin)
|
||||
fmt.Fprintf(w, "\t\tExecute:\t%t\n", set.Defaults.Perm.Execute)
|
||||
fmt.Fprintf(w, "\t\tCreate:\t%t\n", set.Defaults.Perm.Create)
|
||||
fmt.Fprintf(w, "\t\tRename:\t%t\n", set.Defaults.Perm.Rename)
|
||||
fmt.Fprintf(w, "\t\tModify:\t%t\n", set.Defaults.Perm.Modify)
|
||||
fmt.Fprintf(w, "\t\tDelete:\t%t\n", set.Defaults.Perm.Delete)
|
||||
fmt.Fprintf(w, "\t\tShare:\t%t\n", set.Defaults.Perm.Share)
|
||||
fmt.Fprintf(w, "\t\tDownload:\t%t\n", set.Defaults.Perm.Download)
|
||||
w.Flush()
|
||||
|
||||
b, err := json.MarshalIndent(auther, "", " ")
|
||||
checkErr(err)
|
||||
fmt.Printf("\nAuther configuration (raw):\n\n%s\n\n", string(b))
|
||||
}
|
||||
25
cmd/config_cat.go
Normal file
25
cmd/config_cat.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
configCmd.AddCommand(configCatCmd)
|
||||
}
|
||||
|
||||
var configCatCmd = &cobra.Command{
|
||||
Use: "cat",
|
||||
Short: "Prints the configuration",
|
||||
Long: `Prints the configuration.`,
|
||||
Args: cobra.NoArgs,
|
||||
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
|
||||
set, err := d.store.Settings.Get()
|
||||
checkErr(err)
|
||||
ser, err := d.store.Settings.GetServer()
|
||||
checkErr(err)
|
||||
auther, err := d.store.Auth.Get(set.AuthMethod)
|
||||
checkErr(err)
|
||||
printSettings(ser, set, auther)
|
||||
}, pythonConfig{}),
|
||||
}
|
||||
37
cmd/config_export.go
Normal file
37
cmd/config_export.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
configCmd.AddCommand(configExportCmd)
|
||||
}
|
||||
|
||||
var configExportCmd = &cobra.Command{
|
||||
Use: "export <path>",
|
||||
Short: "Export the configuration to a file",
|
||||
Long: `Export the configuration to a file. The path must be for a
|
||||
json or yaml file. This exported configuration can be changed,
|
||||
and imported again with 'config import' command.`,
|
||||
Args: jsonYamlArg,
|
||||
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
|
||||
settings, err := d.store.Settings.Get()
|
||||
checkErr(err)
|
||||
|
||||
server, err := d.store.Settings.GetServer()
|
||||
checkErr(err)
|
||||
|
||||
auther, err := d.store.Auth.Get(settings.AuthMethod)
|
||||
checkErr(err)
|
||||
|
||||
data := &settingsFile{
|
||||
Settings: settings,
|
||||
Auther: auther,
|
||||
Server: server,
|
||||
}
|
||||
|
||||
err = marshal(args[0], data)
|
||||
checkErr(err)
|
||||
}, pythonConfig{}),
|
||||
}
|
||||
91
cmd/config_import.go
Normal file
91
cmd/config_import.go
Normal file
@@ -0,0 +1,91 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/auth"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
configCmd.AddCommand(configImportCmd)
|
||||
}
|
||||
|
||||
type settingsFile struct {
|
||||
Settings *settings.Settings `json:"settings"`
|
||||
Server *settings.Server `json:"server"`
|
||||
Auther interface{} `json:"auther"`
|
||||
}
|
||||
|
||||
var configImportCmd = &cobra.Command{
|
||||
Use: "import <path>",
|
||||
Short: "Import a configuration file",
|
||||
Long: `Import a configuration file. This will replace all the existing
|
||||
configuration. Can be used with or without unexisting databases.
|
||||
|
||||
If used with a nonexisting database, a key will be generated
|
||||
automatically. Otherwise the key will be kept the same as in the
|
||||
database.
|
||||
|
||||
The path must be for a json or yaml file.`,
|
||||
Args: jsonYamlArg,
|
||||
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
|
||||
var key []byte
|
||||
if d.hadDB {
|
||||
settings, err := d.store.Settings.Get()
|
||||
checkErr(err)
|
||||
key = settings.Key
|
||||
} else {
|
||||
key = generateKey()
|
||||
}
|
||||
|
||||
file := settingsFile{}
|
||||
err := unmarshal(args[0], &file)
|
||||
checkErr(err)
|
||||
|
||||
file.Settings.Key = key
|
||||
err = d.store.Settings.Save(file.Settings)
|
||||
checkErr(err)
|
||||
|
||||
err = d.store.Settings.SaveServer(file.Server)
|
||||
checkErr(err)
|
||||
|
||||
var rawAuther interface{}
|
||||
if filepath.Ext(args[0]) != ".json" {
|
||||
rawAuther = cleanUpInterfaceMap(file.Auther.(map[interface{}]interface{}))
|
||||
} else {
|
||||
rawAuther = file.Auther
|
||||
}
|
||||
|
||||
var auther auth.Auther
|
||||
switch file.Settings.AuthMethod {
|
||||
case auth.MethodJSONAuth:
|
||||
auther = getAuther(auth.JSONAuth{}, rawAuther).(*auth.JSONAuth)
|
||||
case auth.MethodNoAuth:
|
||||
auther = getAuther(auth.NoAuth{}, rawAuther).(*auth.NoAuth)
|
||||
case auth.MethodProxyAuth:
|
||||
auther = getAuther(auth.ProxyAuth{}, rawAuther).(*auth.ProxyAuth)
|
||||
default:
|
||||
checkErr(errors.New("invalid auth method"))
|
||||
}
|
||||
|
||||
err = d.store.Auth.Save(auther)
|
||||
checkErr(err)
|
||||
|
||||
printSettings(file.Server, file.Settings, auther)
|
||||
}, pythonConfig{allowNoDB: true}),
|
||||
}
|
||||
|
||||
func getAuther(sample auth.Auther, data interface{}) interface{} {
|
||||
authType := reflect.TypeOf(sample)
|
||||
auther := reflect.New(authType).Interface()
|
||||
bytes, err := json.Marshal(data)
|
||||
checkErr(err)
|
||||
err = json.Unmarshal(bytes, &auther)
|
||||
checkErr(err)
|
||||
return auther
|
||||
}
|
||||
68
cmd/config_init.go
Normal file
68
cmd/config_init.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
configCmd.AddCommand(configInitCmd)
|
||||
addConfigFlags(configInitCmd.Flags())
|
||||
}
|
||||
|
||||
var configInitCmd = &cobra.Command{
|
||||
Use: "init",
|
||||
Short: "Initialize a new database",
|
||||
Long: `Initialize a new database to use with File Browser. All of
|
||||
this options can be changed in the future with the command
|
||||
'filebrowser config set'. The user related flags apply
|
||||
to the defaults when creating new users and you don't
|
||||
override the options.`,
|
||||
Args: cobra.NoArgs,
|
||||
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
|
||||
defaults := settings.UserDefaults{}
|
||||
flags := cmd.Flags()
|
||||
getUserDefaults(flags, &defaults, true)
|
||||
authMethod, auther := getAuthentication(flags)
|
||||
|
||||
s := &settings.Settings{
|
||||
Key: generateKey(),
|
||||
Signup: mustGetBool(flags, "signup"),
|
||||
Shell: strings.Split(strings.TrimSpace(mustGetString(flags, "shell")), " "),
|
||||
AuthMethod: authMethod,
|
||||
Defaults: defaults,
|
||||
Branding: settings.Branding{
|
||||
Name: mustGetString(flags, "branding.name"),
|
||||
DisableExternal: mustGetBool(flags, "branding.disableExternal"),
|
||||
Files: mustGetString(flags, "branding.files"),
|
||||
},
|
||||
}
|
||||
|
||||
ser := &settings.Server{
|
||||
Address: mustGetString(flags, "address"),
|
||||
Root: mustGetString(flags, "root"),
|
||||
BaseURL: mustGetString(flags, "baseurl"),
|
||||
TLSKey: mustGetString(flags, "key"),
|
||||
TLSCert: mustGetString(flags, "cert"),
|
||||
Port: mustGetString(flags, "port"),
|
||||
Log: mustGetString(flags, "log"),
|
||||
}
|
||||
|
||||
err := d.store.Settings.Save(s)
|
||||
checkErr(err)
|
||||
err = d.store.Settings.SaveServer(ser)
|
||||
checkErr(err)
|
||||
err = d.store.Auth.Save(auther)
|
||||
checkErr(err)
|
||||
|
||||
fmt.Printf(`
|
||||
Congratulations! You've set up your database to use with File Browser.
|
||||
Now add your first user via 'filebrowser users new' and then you just
|
||||
need to call the main command to boot up the server.
|
||||
`)
|
||||
printSettings(ser, s, auther)
|
||||
}, pythonConfig{noDB: true}),
|
||||
}
|
||||
80
cmd/config_set.go
Normal file
80
cmd/config_set.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/auth"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
func init() {
|
||||
configCmd.AddCommand(configSetCmd)
|
||||
addConfigFlags(configSetCmd.Flags())
|
||||
}
|
||||
|
||||
var configSetCmd = &cobra.Command{
|
||||
Use: "set",
|
||||
Short: "Updates the configuration",
|
||||
Long: `Updates the configuration. Set the flags for the options
|
||||
you want to change. Other options will remain unchanged.`,
|
||||
Args: cobra.NoArgs,
|
||||
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
|
||||
flags := cmd.Flags()
|
||||
set, err := d.store.Settings.Get()
|
||||
checkErr(err)
|
||||
|
||||
ser, err := d.store.Settings.GetServer()
|
||||
checkErr(err)
|
||||
|
||||
hasAuth := false
|
||||
flags.Visit(func(flag *pflag.Flag) {
|
||||
switch flag.Name {
|
||||
case "baseurl":
|
||||
ser.BaseURL = mustGetString(flags, flag.Name)
|
||||
case "root":
|
||||
ser.Root = mustGetString(flags, flag.Name)
|
||||
case "cert":
|
||||
ser.TLSCert = mustGetString(flags, flag.Name)
|
||||
case "key":
|
||||
ser.TLSKey = mustGetString(flags, flag.Name)
|
||||
case "address":
|
||||
ser.Address = mustGetString(flags, flag.Name)
|
||||
case "port":
|
||||
ser.Port = mustGetString(flags, flag.Name)
|
||||
case "log":
|
||||
ser.Log = mustGetString(flags, flag.Name)
|
||||
case "signup":
|
||||
set.Signup = mustGetBool(flags, flag.Name)
|
||||
case "auth.method":
|
||||
hasAuth = true
|
||||
case "shell":
|
||||
set.Shell = strings.Split(strings.TrimSpace(mustGetString(flags, flag.Name)), " ")
|
||||
case "branding.name":
|
||||
set.Branding.Name = mustGetString(flags, flag.Name)
|
||||
case "branding.disableExternal":
|
||||
set.Branding.DisableExternal = mustGetBool(flags, flag.Name)
|
||||
case "branding.files":
|
||||
set.Branding.Files = mustGetString(flags, flag.Name)
|
||||
}
|
||||
})
|
||||
|
||||
getUserDefaults(flags, &set.Defaults, false)
|
||||
|
||||
var auther auth.Auther
|
||||
if hasAuth {
|
||||
set.AuthMethod, auther = getAuthentication(flags)
|
||||
err = d.store.Auth.Save(auther)
|
||||
checkErr(err)
|
||||
} else {
|
||||
auther, err = d.store.Auth.Get(set.AuthMethod)
|
||||
checkErr(err)
|
||||
}
|
||||
|
||||
err = d.store.Settings.Save(set)
|
||||
checkErr(err)
|
||||
err = d.store.Settings.SaveServer(ser)
|
||||
checkErr(err)
|
||||
printSettings(ser, set, auther)
|
||||
}, pythonConfig{}),
|
||||
}
|
||||
139
cmd/docs.go
Normal file
139
cmd/docs.go
Normal file
@@ -0,0 +1,139 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(docsCmd)
|
||||
docsCmd.Flags().StringP("path", "p", "./docs", "path to save the docs")
|
||||
}
|
||||
|
||||
func printToc(names []string) {
|
||||
for i, name := range names {
|
||||
name = strings.TrimSuffix(name, filepath.Ext(name))
|
||||
name = strings.Replace(name, "-", " ", -1)
|
||||
names[i] = name
|
||||
}
|
||||
|
||||
sort.Strings(names)
|
||||
|
||||
toc := ""
|
||||
for _, name := range names {
|
||||
toc += "* [" + name + "](cli/" + strings.Replace(name, " ", "-", -1) + ".md)\n"
|
||||
}
|
||||
|
||||
fmt.Println(toc)
|
||||
}
|
||||
|
||||
var docsCmd = &cobra.Command{
|
||||
Use: "docs",
|
||||
Hidden: true,
|
||||
Args: cobra.NoArgs,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
dir := mustGetString(cmd.Flags(), "path")
|
||||
generateDocs(rootCmd, dir)
|
||||
names := []string{}
|
||||
|
||||
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil || info.IsDir() {
|
||||
return err
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(info.Name(), "filebrowser") {
|
||||
return nil
|
||||
}
|
||||
|
||||
names = append(names, info.Name())
|
||||
return nil
|
||||
})
|
||||
|
||||
checkErr(err)
|
||||
printToc(names)
|
||||
},
|
||||
}
|
||||
|
||||
func generateDocs(cmd *cobra.Command, dir string) {
|
||||
for _, c := range cmd.Commands() {
|
||||
if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
|
||||
continue
|
||||
}
|
||||
|
||||
generateDocs(c, dir)
|
||||
}
|
||||
|
||||
basename := strings.Replace(cmd.CommandPath(), " ", "-", -1) + ".md"
|
||||
filename := filepath.Join(dir, basename)
|
||||
f, err := os.Create(filename)
|
||||
checkErr(err)
|
||||
defer f.Close()
|
||||
generateMarkdown(cmd, f)
|
||||
}
|
||||
|
||||
func generateMarkdown(cmd *cobra.Command, w io.Writer) {
|
||||
cmd.InitDefaultHelpCmd()
|
||||
cmd.InitDefaultHelpFlag()
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
name := cmd.CommandPath()
|
||||
|
||||
short := cmd.Short
|
||||
long := cmd.Long
|
||||
if len(long) == 0 {
|
||||
long = short
|
||||
}
|
||||
|
||||
buf.WriteString("---\ndescription: " + short + "\n---\n\n")
|
||||
buf.WriteString("# " + name + "\n\n")
|
||||
buf.WriteString("## Synopsis\n\n")
|
||||
buf.WriteString(long + "\n\n")
|
||||
|
||||
if cmd.Runnable() {
|
||||
buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.UseLine()))
|
||||
}
|
||||
|
||||
if len(cmd.Example) > 0 {
|
||||
buf.WriteString("## Examples\n\n")
|
||||
buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.Example))
|
||||
}
|
||||
|
||||
printOptions(buf, cmd, name)
|
||||
_, err := buf.WriteTo(w)
|
||||
checkErr(err)
|
||||
}
|
||||
|
||||
func generateFlagsTable(fs *pflag.FlagSet, buf io.StringWriter) {
|
||||
buf.WriteString("| Name | Shorthand | Usage |\n")
|
||||
buf.WriteString("|------|-----------|-------|\n")
|
||||
|
||||
fs.VisitAll(func(f *pflag.Flag) {
|
||||
buf.WriteString("|" + f.Name + "|" + f.Shorthand + "|" + f.Usage + "|\n")
|
||||
})
|
||||
}
|
||||
|
||||
func printOptions(buf *bytes.Buffer, cmd *cobra.Command, name string) {
|
||||
flags := cmd.NonInheritedFlags()
|
||||
flags.SetOutput(buf)
|
||||
if flags.HasAvailableFlags() {
|
||||
buf.WriteString("## Options\n\n")
|
||||
generateFlagsTable(flags, buf)
|
||||
buf.WriteString("\n")
|
||||
}
|
||||
|
||||
parentFlags := cmd.InheritedFlags()
|
||||
parentFlags.SetOutput(buf)
|
||||
if parentFlags.HasAvailableFlags() {
|
||||
buf.WriteString("### Inherited\n\n")
|
||||
generateFlagsTable(parentFlags, buf)
|
||||
buf.WriteString("\n")
|
||||
}
|
||||
}
|
||||
@@ -1,259 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/asdine/storm"
|
||||
|
||||
"gopkg.in/natefinch/lumberjack.v2"
|
||||
|
||||
"github.com/filebrowser/filebrowser"
|
||||
"github.com/filebrowser/filebrowser/bolt"
|
||||
h "github.com/filebrowser/filebrowser/http"
|
||||
"github.com/filebrowser/filebrowser/staticgen"
|
||||
"github.com/hacdias/fileutils"
|
||||
flag "github.com/spf13/pflag"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var (
|
||||
addr string
|
||||
config string
|
||||
database string
|
||||
scope string
|
||||
commands string
|
||||
logfile string
|
||||
staticg string
|
||||
locale string
|
||||
baseurl string
|
||||
prefixurl string
|
||||
viewMode string
|
||||
recaptchakey string
|
||||
recaptchasecret string
|
||||
port int
|
||||
noAuth bool
|
||||
allowCommands bool
|
||||
allowEdit bool
|
||||
allowNew bool
|
||||
allowPublish bool
|
||||
showVer bool
|
||||
alterRecaptcha bool
|
||||
)
|
||||
|
||||
func init() {
|
||||
flag.StringVarP(&config, "config", "c", "", "Configuration file")
|
||||
flag.IntVarP(&port, "port", "p", 0, "HTTP Port (default is random)")
|
||||
flag.StringVarP(&addr, "address", "a", "", "Address to listen to (default is all of them)")
|
||||
flag.StringVarP(&database, "database", "d", "./filebrowser.db", "Database file")
|
||||
flag.StringVarP(&logfile, "log", "l", "stdout", "Errors logger; can use 'stdout', 'stderr' or file")
|
||||
flag.StringVarP(&scope, "scope", "s", ".", "Default scope option for new users")
|
||||
flag.StringVarP(&baseurl, "baseurl", "b", "", "Base URL")
|
||||
flag.StringVar(&commands, "commands", "git svn hg", "Default commands option for new users")
|
||||
flag.StringVar(&prefixurl, "prefixurl", "", "Prefix URL")
|
||||
flag.StringVar(&viewMode, "view-mode", "mosaic", "Default view mode for new users")
|
||||
flag.StringVar(&recaptchakey, "recaptcha-key", "", "ReCaptcha site key")
|
||||
flag.StringVar(&recaptchasecret, "recaptcha-secret", "", "ReCaptcha secret")
|
||||
flag.BoolVar(&allowCommands, "allow-commands", true, "Default allow commands option for new users")
|
||||
flag.BoolVar(&allowEdit, "allow-edit", true, "Default allow edit option for new users")
|
||||
flag.BoolVar(&allowPublish, "allow-publish", true, "Default allow publish option for new users")
|
||||
flag.BoolVar(&allowNew, "allow-new", true, "Default allow new option for new users")
|
||||
flag.BoolVar(&noAuth, "no-auth", false, "Disables authentication")
|
||||
flag.BoolVar(&alterRecaptcha, "alternative-recaptcha", false, "Use recaptcha.net for serving and handling, useful in China")
|
||||
flag.StringVar(&locale, "locale", "", "Default locale for new users, set it empty to enable auto detect from browser")
|
||||
flag.StringVar(&staticg, "staticgen", "", "Static Generator you want to enable")
|
||||
flag.BoolVarP(&showVer, "version", "v", false, "Show version")
|
||||
}
|
||||
|
||||
func setupViper() {
|
||||
viper.SetDefault("Address", "")
|
||||
viper.SetDefault("Port", "0")
|
||||
viper.SetDefault("Database", "./filebrowser.db")
|
||||
viper.SetDefault("Scope", ".")
|
||||
viper.SetDefault("Logger", "stdout")
|
||||
viper.SetDefault("Commands", []string{"git", "svn", "hg"})
|
||||
viper.SetDefault("AllowCommmands", true)
|
||||
viper.SetDefault("AllowEdit", true)
|
||||
viper.SetDefault("AllowNew", true)
|
||||
viper.SetDefault("AllowPublish", true)
|
||||
viper.SetDefault("StaticGen", "")
|
||||
viper.SetDefault("Locale", "")
|
||||
viper.SetDefault("NoAuth", false)
|
||||
viper.SetDefault("BaseURL", "")
|
||||
viper.SetDefault("PrefixURL", "")
|
||||
viper.SetDefault("ViewMode", filebrowser.MosaicViewMode)
|
||||
viper.SetDefault("AlternativeRecaptcha", false)
|
||||
viper.SetDefault("ReCaptchaKey", "")
|
||||
viper.SetDefault("ReCaptchaSecret", "")
|
||||
|
||||
viper.BindPFlag("Port", flag.Lookup("port"))
|
||||
viper.BindPFlag("Address", flag.Lookup("address"))
|
||||
viper.BindPFlag("Database", flag.Lookup("database"))
|
||||
viper.BindPFlag("Scope", flag.Lookup("scope"))
|
||||
viper.BindPFlag("Logger", flag.Lookup("log"))
|
||||
viper.BindPFlag("Commands", flag.Lookup("commands"))
|
||||
viper.BindPFlag("AllowCommands", flag.Lookup("allow-commands"))
|
||||
viper.BindPFlag("AllowEdit", flag.Lookup("allow-edit"))
|
||||
viper.BindPFlag("AlowNew", flag.Lookup("allow-new"))
|
||||
viper.BindPFlag("AllowPublish", flag.Lookup("allow-publish"))
|
||||
viper.BindPFlag("Locale", flag.Lookup("locale"))
|
||||
viper.BindPFlag("StaticGen", flag.Lookup("staticgen"))
|
||||
viper.BindPFlag("NoAuth", flag.Lookup("no-auth"))
|
||||
viper.BindPFlag("BaseURL", flag.Lookup("baseurl"))
|
||||
viper.BindPFlag("PrefixURL", flag.Lookup("prefixurl"))
|
||||
viper.BindPFlag("ViewMode", flag.Lookup("view-mode"))
|
||||
viper.BindPFlag("AlternativeRecaptcha", flag.Lookup("alternative-recaptcha"))
|
||||
viper.BindPFlag("ReCaptchaKey", flag.Lookup("recaptcha-key"))
|
||||
viper.BindPFlag("ReCaptchaSecret", flag.Lookup("recaptcha-secret"))
|
||||
|
||||
viper.SetConfigName("filebrowser")
|
||||
viper.AddConfigPath(".")
|
||||
}
|
||||
|
||||
func printVersion() {
|
||||
fmt.Println("filebrowser version", filebrowser.Version)
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
func main() {
|
||||
setupViper()
|
||||
flag.Parse()
|
||||
|
||||
if showVer {
|
||||
printVersion()
|
||||
}
|
||||
|
||||
// Add a configuration file if set.
|
||||
if config != "" {
|
||||
ext := filepath.Ext(config)
|
||||
dir := filepath.Dir(config)
|
||||
config = strings.TrimSuffix(config, ext)
|
||||
|
||||
if dir != "" {
|
||||
viper.AddConfigPath(dir)
|
||||
config = strings.TrimPrefix(config, dir)
|
||||
}
|
||||
|
||||
viper.SetConfigName(config)
|
||||
}
|
||||
|
||||
// Read configuration from a file if exists.
|
||||
err := viper.ReadInConfig()
|
||||
if err != nil {
|
||||
if _, ok := err.(viper.ConfigParseError); ok {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Set up process log before anything bad happens.
|
||||
switch viper.GetString("Logger") {
|
||||
case "stdout":
|
||||
log.SetOutput(os.Stdout)
|
||||
case "stderr":
|
||||
log.SetOutput(os.Stderr)
|
||||
case "":
|
||||
log.SetOutput(ioutil.Discard)
|
||||
default:
|
||||
log.SetOutput(&lumberjack.Logger{
|
||||
Filename: logfile,
|
||||
MaxSize: 100,
|
||||
MaxAge: 14,
|
||||
MaxBackups: 10,
|
||||
})
|
||||
}
|
||||
|
||||
// Builds the address and a listener.
|
||||
laddr := viper.GetString("Address") + ":" + viper.GetString("Port")
|
||||
listener, err := net.Listen("tcp", laddr)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Tell the user the port in which is listening.
|
||||
fmt.Println("Listening on", listener.Addr().String())
|
||||
|
||||
// Starts the server.
|
||||
if err := http.Serve(listener, handler()); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func handler() http.Handler {
|
||||
db, err := storm.Open(viper.GetString("Database"))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
recaptchaHost := "https://www.google.com"
|
||||
if viper.GetBool("AlternativeRecaptcha") {
|
||||
recaptchaHost = "https://recaptcha.net"
|
||||
}
|
||||
|
||||
fm := &filebrowser.FileBrowser{
|
||||
NoAuth: viper.GetBool("NoAuth"),
|
||||
BaseURL: viper.GetString("BaseURL"),
|
||||
PrefixURL: viper.GetString("PrefixURL"),
|
||||
ReCaptchaHost: recaptchaHost,
|
||||
ReCaptchaKey: viper.GetString("ReCaptchaKey"),
|
||||
ReCaptchaSecret: viper.GetString("ReCaptchaSecret"),
|
||||
DefaultUser: &filebrowser.User{
|
||||
AllowCommands: viper.GetBool("AllowCommands"),
|
||||
AllowEdit: viper.GetBool("AllowEdit"),
|
||||
AllowNew: viper.GetBool("AllowNew"),
|
||||
AllowPublish: viper.GetBool("AllowPublish"),
|
||||
Commands: viper.GetStringSlice("Commands"),
|
||||
Rules: []*filebrowser.Rule{},
|
||||
Locale: viper.GetString("Locale"),
|
||||
CSS: "",
|
||||
Scope: viper.GetString("Scope"),
|
||||
FileSystem: fileutils.Dir(viper.GetString("Scope")),
|
||||
ViewMode: viper.GetString("ViewMode"),
|
||||
},
|
||||
Store: &filebrowser.Store{
|
||||
Config: bolt.ConfigStore{DB: db},
|
||||
Users: bolt.UsersStore{DB: db},
|
||||
Share: bolt.ShareStore{DB: db},
|
||||
},
|
||||
NewFS: func(scope string) filebrowser.FileSystem {
|
||||
return fileutils.Dir(scope)
|
||||
},
|
||||
}
|
||||
|
||||
err = fm.Setup()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
switch viper.GetString("StaticGen") {
|
||||
case "hugo":
|
||||
hugo := &staticgen.Hugo{
|
||||
Root: viper.GetString("Scope"),
|
||||
Public: filepath.Join(viper.GetString("Scope"), "public"),
|
||||
Args: []string{},
|
||||
CleanPublic: true,
|
||||
}
|
||||
|
||||
if err = fm.Attach(hugo); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
case "jekyll":
|
||||
jekyll := &staticgen.Jekyll{
|
||||
Root: viper.GetString("Scope"),
|
||||
Public: filepath.Join(viper.GetString("Scope"), "_site"),
|
||||
Args: []string{"build"},
|
||||
CleanPublic: true,
|
||||
}
|
||||
|
||||
if err = fm.Attach(jekyll); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
return h.Handler(fm)
|
||||
}
|
||||
24
cmd/hash.go
Normal file
24
cmd/hash.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(hashCmd)
|
||||
}
|
||||
|
||||
var hashCmd = &cobra.Command{
|
||||
Use: "hash <password>",
|
||||
Short: "Hashes a password",
|
||||
Long: `Hashes a password using bcrypt algorithm.`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
pwd, err := users.HashPwd(args[0])
|
||||
checkErr(err)
|
||||
fmt.Println(pwd)
|
||||
},
|
||||
}
|
||||
311
cmd/root.go
Normal file
311
cmd/root.go
Normal file
@@ -0,0 +1,311 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/auth"
|
||||
fbhttp "github.com/filebrowser/filebrowser/v2/http"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/storage"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
homedir "github.com/mitchellh/go-homedir"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
v "github.com/spf13/viper"
|
||||
lumberjack "gopkg.in/natefinch/lumberjack.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
cfgFile string
|
||||
)
|
||||
|
||||
func init() {
|
||||
cobra.OnInitialize(initConfig)
|
||||
|
||||
rootCmd.SetVersionTemplate("File Browser version {{printf \"%s\" .Version}}\n")
|
||||
|
||||
flags := rootCmd.Flags()
|
||||
persistent := rootCmd.PersistentFlags()
|
||||
|
||||
persistent.StringVarP(&cfgFile, "config", "c", "", "config file path")
|
||||
persistent.StringP("database", "d", "./filebrowser.db", "database path")
|
||||
flags.Bool("noauth", false, "use the noauth auther when using quick setup")
|
||||
flags.String("username", "admin", "username for the first user when using quick config")
|
||||
flags.String("password", "", "hashed password for the first user when using quick config (default \"admin\")")
|
||||
|
||||
addServerFlags(flags)
|
||||
}
|
||||
|
||||
func addServerFlags(flags *pflag.FlagSet) {
|
||||
flags.StringP("address", "a", "127.0.0.1", "address to listen on")
|
||||
flags.StringP("log", "l", "stdout", "log output")
|
||||
flags.StringP("port", "p", "8080", "port to listen on")
|
||||
flags.StringP("cert", "t", "", "tls certificate")
|
||||
flags.StringP("key", "k", "", "tls key")
|
||||
flags.StringP("root", "r", ".", "root to prepend to relative paths")
|
||||
flags.StringP("baseurl", "b", "", "base url")
|
||||
}
|
||||
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "filebrowser",
|
||||
Short: "A stylish web-based file browser",
|
||||
Long: `File Browser CLI lets you create the database to use with File Browser,
|
||||
manage your users and all the configurations without acessing the
|
||||
web interface.
|
||||
|
||||
If you've never run File Browser, you'll need to have a database for
|
||||
it. Don't worry: you don't need to setup a separate database server.
|
||||
We're using Bolt DB which is a single file database and all managed
|
||||
by ourselves.
|
||||
|
||||
For this specific command, all the flags you have available (except
|
||||
"config" for the configuration file), can be given either through
|
||||
environment variables or configuration files.
|
||||
|
||||
If you don't set "config", it will look for a configuration file called
|
||||
.filebrowser.{json, toml, yaml, yml} in the following directories:
|
||||
|
||||
- ./
|
||||
- $HOME/
|
||||
- /etc/filebrowser/
|
||||
|
||||
The precedence of the configuration values are as follows:
|
||||
|
||||
- flags
|
||||
- environment variables
|
||||
- configuration file
|
||||
- database values
|
||||
- defaults
|
||||
|
||||
The environment variables are prefixed by "FB_" followed by the option
|
||||
name in caps. So to set "database" via an env variable, you should
|
||||
set FB_DATABASE.
|
||||
|
||||
Also, if the database path doesn't exist, File Browser will enter into
|
||||
the quick setup mode and a new database will be bootstraped and a new
|
||||
user created with the credentials from options "username" and "password".`,
|
||||
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
|
||||
log.Println(cfgFile)
|
||||
|
||||
if !d.hadDB {
|
||||
quickSetup(cmd.Flags(), d)
|
||||
}
|
||||
|
||||
server := getRunParams(cmd.Flags(), d.store)
|
||||
setupLog(server.Log)
|
||||
|
||||
root, err := filepath.Abs(server.Root)
|
||||
checkErr(err)
|
||||
server.Root = root
|
||||
|
||||
adr := server.Address + ":" + server.Port
|
||||
|
||||
var listener net.Listener
|
||||
|
||||
if server.TLSKey != "" && server.TLSCert != "" {
|
||||
cer, err := tls.LoadX509KeyPair(server.TLSCert, server.TLSKey)
|
||||
checkErr(err)
|
||||
listener, err = tls.Listen("tcp", adr, &tls.Config{Certificates: []tls.Certificate{cer}})
|
||||
checkErr(err)
|
||||
} else {
|
||||
listener, err = net.Listen("tcp", adr)
|
||||
checkErr(err)
|
||||
}
|
||||
|
||||
handler, err := fbhttp.NewHandler(d.store, server)
|
||||
checkErr(err)
|
||||
|
||||
log.Println("Listening on", listener.Addr().String())
|
||||
if err := http.Serve(listener, handler); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}, pythonConfig{allowNoDB: true}),
|
||||
}
|
||||
|
||||
func getRunParams(flags *pflag.FlagSet, st *storage.Storage) *settings.Server {
|
||||
server, err := st.Settings.GetServer()
|
||||
checkErr(err)
|
||||
|
||||
if val, set := getParamB(flags, "root"); set {
|
||||
server.Root = val
|
||||
}
|
||||
|
||||
if val, set := getParamB(flags, "baseurl"); set {
|
||||
server.BaseURL = val
|
||||
}
|
||||
|
||||
if val, set := getParamB(flags, "address"); set {
|
||||
server.Address = val
|
||||
}
|
||||
|
||||
if val, set := getParamB(flags, "port"); set {
|
||||
server.Port = val
|
||||
}
|
||||
|
||||
if val, set := getParamB(flags, "log"); set {
|
||||
server.Log = val
|
||||
}
|
||||
|
||||
if val, set := getParamB(flags, "key"); set {
|
||||
server.TLSKey = val
|
||||
}
|
||||
|
||||
if val, set := getParamB(flags, "cert"); set {
|
||||
server.TLSCert = val
|
||||
}
|
||||
|
||||
return server
|
||||
}
|
||||
|
||||
// getParamB returns a parameter as a string and a boolean to tell if it is different from the default
|
||||
//
|
||||
// NOTE: we could simply bind the flags to viper and use IsSet.
|
||||
// Although there is a bug on Viper that always returns true on IsSet
|
||||
// if a flag is binded. Our alternative way is to manually check
|
||||
// the flag and then the value from env/config/gotten by viper.
|
||||
// https://github.com/spf13/viper/pull/331
|
||||
func getParamB(flags *pflag.FlagSet, key string) (string, bool) {
|
||||
value, _ := flags.GetString(key)
|
||||
|
||||
// If set on Flags, use it.
|
||||
if flags.Changed(key) {
|
||||
return value, true
|
||||
}
|
||||
|
||||
// If set through viper (env, config), return it.
|
||||
if v.IsSet(key) {
|
||||
return v.GetString(key), true
|
||||
}
|
||||
|
||||
// Otherwise use default value on flags.
|
||||
return value, false
|
||||
}
|
||||
|
||||
func getParam(flags *pflag.FlagSet, key string) string {
|
||||
val, _ := getParamB(flags, key)
|
||||
return val
|
||||
}
|
||||
|
||||
func setupLog(logMethod string) {
|
||||
switch logMethod {
|
||||
case "stdout":
|
||||
log.SetOutput(os.Stdout)
|
||||
case "stderr":
|
||||
log.SetOutput(os.Stderr)
|
||||
case "":
|
||||
log.SetOutput(ioutil.Discard)
|
||||
default:
|
||||
log.SetOutput(&lumberjack.Logger{
|
||||
Filename: logMethod,
|
||||
MaxSize: 100,
|
||||
MaxAge: 14,
|
||||
MaxBackups: 10,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func quickSetup(flags *pflag.FlagSet, d pythonData) {
|
||||
set := &settings.Settings{
|
||||
Key: generateKey(),
|
||||
Signup: false,
|
||||
CreateUserDir: false,
|
||||
Defaults: settings.UserDefaults{
|
||||
Scope: ".",
|
||||
Locale: "en",
|
||||
Perm: users.Permissions{
|
||||
Admin: false,
|
||||
Execute: true,
|
||||
Create: true,
|
||||
Rename: true,
|
||||
Modify: true,
|
||||
Delete: true,
|
||||
Share: true,
|
||||
Download: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
var err error
|
||||
if _, noauth := getParamB(flags, "noauth"); noauth {
|
||||
set.AuthMethod = auth.MethodNoAuth
|
||||
err = d.store.Auth.Save(&auth.NoAuth{})
|
||||
} else {
|
||||
set.AuthMethod = auth.MethodJSONAuth
|
||||
err = d.store.Auth.Save(&auth.JSONAuth{})
|
||||
}
|
||||
|
||||
checkErr(err)
|
||||
err = d.store.Settings.Save(set)
|
||||
checkErr(err)
|
||||
|
||||
ser := &settings.Server{
|
||||
BaseURL: getParam(flags, "baseurl"),
|
||||
Port: getParam(flags, "port"),
|
||||
Log: getParam(flags, "log"),
|
||||
TLSKey: getParam(flags, "key"),
|
||||
TLSCert: getParam(flags, "cert"),
|
||||
Address: getParam(flags, "address"),
|
||||
Root: getParam(flags, "root"),
|
||||
}
|
||||
|
||||
err = d.store.Settings.SaveServer(ser)
|
||||
checkErr(err)
|
||||
|
||||
username := getParam(flags, "username")
|
||||
password := getParam(flags, "password")
|
||||
|
||||
if password == "" {
|
||||
password, err = users.HashPwd("admin")
|
||||
checkErr(err)
|
||||
}
|
||||
|
||||
if username == "" || password == "" {
|
||||
log.Fatal("username and password cannot be empty during quick setup")
|
||||
}
|
||||
|
||||
user := &users.User{
|
||||
Username: username,
|
||||
Password: password,
|
||||
LockPassword: false,
|
||||
}
|
||||
|
||||
set.Defaults.Apply(user)
|
||||
user.Perm.Admin = true
|
||||
|
||||
err = d.store.Users.Save(user)
|
||||
checkErr(err)
|
||||
}
|
||||
|
||||
func initConfig() {
|
||||
if cfgFile == "" {
|
||||
home, err := homedir.Dir()
|
||||
checkErr(err)
|
||||
v.AddConfigPath(".")
|
||||
v.AddConfigPath(home)
|
||||
v.AddConfigPath("/etc/filebrowser/")
|
||||
v.SetConfigName(".filebrowser")
|
||||
} else {
|
||||
v.SetConfigFile(cfgFile)
|
||||
}
|
||||
|
||||
v.SetEnvPrefix("FB")
|
||||
v.AutomaticEnv()
|
||||
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
||||
|
||||
if err := v.ReadInConfig(); err != nil {
|
||||
if _, ok := err.(v.ConfigParseError); ok {
|
||||
panic(err)
|
||||
}
|
||||
cfgFile = "No config file used"
|
||||
} else {
|
||||
cfgFile = "Using config file: " + v.ConfigFileUsed()
|
||||
}
|
||||
|
||||
}
|
||||
65
cmd/rule_rm.go
Normal file
65
cmd/rule_rm.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rulesCmd.AddCommand(rulesRmCommand)
|
||||
rulesRmCommand.Flags().Uint("index", 0, "index of rule to remove")
|
||||
rulesRmCommand.MarkFlagRequired("index")
|
||||
}
|
||||
|
||||
var rulesRmCommand = &cobra.Command{
|
||||
Use: "rm <index> [index_end]",
|
||||
Short: "Remove a global rule or user rule",
|
||||
Long: `Remove a global rule or user rule. The provided index
|
||||
is the same that's printed when you run 'rules ls'. Note
|
||||
that after each removal/addition, the index of the
|
||||
commands change. So be careful when removing them after each
|
||||
other.
|
||||
|
||||
You can also specify an optional parameter (index_end) so
|
||||
you can remove all commands from 'index' to 'index_end',
|
||||
including 'index_end'.`,
|
||||
Args: func(cmd *cobra.Command, args []string) error {
|
||||
if err := cobra.RangeArgs(1, 2)(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, arg := range args {
|
||||
if _, err := strconv.Atoi(arg); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
|
||||
i, err := strconv.Atoi(args[0])
|
||||
checkErr(err)
|
||||
f := i
|
||||
if len(args) == 2 {
|
||||
f, err = strconv.Atoi(args[1])
|
||||
checkErr(err)
|
||||
}
|
||||
|
||||
user := func(u *users.User) {
|
||||
u.Rules = append(u.Rules[:i], u.Rules[f+1:]...)
|
||||
err := d.store.Users.Save(u)
|
||||
checkErr(err)
|
||||
}
|
||||
|
||||
global := func(s *settings.Settings) {
|
||||
s.Rules = append(s.Rules[:i], s.Rules[f+1:]...)
|
||||
err := d.store.Settings.Save(s)
|
||||
checkErr(err)
|
||||
}
|
||||
|
||||
runRules(d.store, cmd, user, global)
|
||||
}, pythonConfig{}),
|
||||
}
|
||||
91
cmd/rules.go
Normal file
91
cmd/rules.go
Normal file
@@ -0,0 +1,91 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/rules"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/storage"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(rulesCmd)
|
||||
rulesCmd.PersistentFlags().StringP("username", "u", "", "username of user to which the rules apply")
|
||||
rulesCmd.PersistentFlags().UintP("id", "i", 0, "id of user to which the rules apply")
|
||||
}
|
||||
|
||||
var rulesCmd = &cobra.Command{
|
||||
Use: "rules",
|
||||
Short: "Rules management utility",
|
||||
Long: `On each subcommand you'll have available at least two flags:
|
||||
"username" and "id". You must either set only one of them
|
||||
or none. If you set one of them, the command will apply to
|
||||
an user, otherwise it will be applied to the global set or
|
||||
rules.`,
|
||||
Args: cobra.NoArgs,
|
||||
}
|
||||
|
||||
func runRules(st *storage.Storage, cmd *cobra.Command, users func(*users.User), global func(*settings.Settings)) {
|
||||
id := getUserIdentifier(cmd.Flags())
|
||||
if id != nil {
|
||||
user, err := st.Users.Get("", id)
|
||||
checkErr(err)
|
||||
|
||||
if users != nil {
|
||||
users(user)
|
||||
}
|
||||
|
||||
printRules(user.Rules, id)
|
||||
return
|
||||
}
|
||||
|
||||
s, err := st.Settings.Get()
|
||||
checkErr(err)
|
||||
|
||||
if global != nil {
|
||||
global(s)
|
||||
}
|
||||
|
||||
printRules(s.Rules, id)
|
||||
}
|
||||
|
||||
func getUserIdentifier(flags *pflag.FlagSet) interface{} {
|
||||
id := mustGetUint(flags, "id")
|
||||
username := mustGetString(flags, "username")
|
||||
|
||||
if id != 0 {
|
||||
return id
|
||||
} else if username != "" {
|
||||
return username
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func printRules(rules []rules.Rule, id interface{}) {
|
||||
if id == nil {
|
||||
fmt.Printf("Global Rules:\n\n")
|
||||
} else {
|
||||
fmt.Printf("Rules for user %v:\n\n", id)
|
||||
}
|
||||
|
||||
for id, rule := range rules {
|
||||
fmt.Printf("(%d) ", id)
|
||||
if rule.Regex {
|
||||
if rule.Allow {
|
||||
fmt.Printf("Allow Regex: \t%s\n", rule.Regexp.Raw)
|
||||
} else {
|
||||
fmt.Printf("Disallow Regex: \t%s\n", rule.Regexp.Raw)
|
||||
}
|
||||
} else {
|
||||
if rule.Allow {
|
||||
fmt.Printf("Allow Path: \t%s\n", rule.Path)
|
||||
} else {
|
||||
fmt.Printf("Disallow Path: \t%s\n", rule.Path)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
57
cmd/rules_add.go
Normal file
57
cmd/rules_add.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/rules"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rulesCmd.AddCommand(rulesAddCmd)
|
||||
rulesAddCmd.Flags().BoolP("allow", "a", false, "indicates this is an allow rule")
|
||||
rulesAddCmd.Flags().BoolP("regex", "r", false, "indicates this is a regex rule")
|
||||
}
|
||||
|
||||
var rulesAddCmd = &cobra.Command{
|
||||
Use: "add <path|expression>",
|
||||
Short: "Add a global rule or user rule",
|
||||
Long: `Add a global rule or user rule.`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
|
||||
allow := mustGetBool(cmd.Flags(), "allow")
|
||||
regex := mustGetBool(cmd.Flags(), "regex")
|
||||
exp := args[0]
|
||||
|
||||
if regex {
|
||||
regexp.MustCompile(exp)
|
||||
}
|
||||
|
||||
rule := rules.Rule{
|
||||
Allow: allow,
|
||||
Regex: regex,
|
||||
}
|
||||
|
||||
if regex {
|
||||
rule.Regexp = &rules.Regexp{Raw: exp}
|
||||
} else {
|
||||
rule.Path = exp
|
||||
}
|
||||
|
||||
user := func(u *users.User) {
|
||||
u.Rules = append(u.Rules, rule)
|
||||
err := d.store.Users.Save(u)
|
||||
checkErr(err)
|
||||
}
|
||||
|
||||
global := func(s *settings.Settings) {
|
||||
s.Rules = append(s.Rules, rule)
|
||||
err := d.store.Settings.Save(s)
|
||||
checkErr(err)
|
||||
}
|
||||
|
||||
runRules(d.store, cmd, user, global)
|
||||
}, pythonConfig{}),
|
||||
}
|
||||
19
cmd/rules_ls.go
Normal file
19
cmd/rules_ls.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rulesCmd.AddCommand(rulesLsCommand)
|
||||
}
|
||||
|
||||
var rulesLsCommand = &cobra.Command{
|
||||
Use: "ls",
|
||||
Short: "List global rules or user specific rules",
|
||||
Long: `List global rules or user specific rules.`,
|
||||
Args: cobra.NoArgs,
|
||||
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
|
||||
runRules(d.store, cmd, nil, nil)
|
||||
}, pythonConfig{}),
|
||||
}
|
||||
30
cmd/upgrade.go
Normal file
30
cmd/upgrade.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/filebrowser/filebrowser/v2/storage/bolt/importer"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(upgradeCmd)
|
||||
|
||||
upgradeCmd.Flags().String("old.database", "", "")
|
||||
upgradeCmd.Flags().String("old.config", "", "")
|
||||
upgradeCmd.MarkFlagRequired("old.database")
|
||||
}
|
||||
|
||||
var upgradeCmd = &cobra.Command{
|
||||
Use: "upgrade",
|
||||
Short: "Upgrades an old configuration",
|
||||
Long: `Upgrades an old configuration. This command DOES NOT
|
||||
import share links because they are incompatible with
|
||||
this version.`,
|
||||
Args: cobra.NoArgs,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
flags := cmd.Flags()
|
||||
oldDB := mustGetString(flags, "old.database")
|
||||
oldConf := mustGetString(flags, "old.config")
|
||||
err := importer.Import(oldDB, oldConf, getParam(flags, "database"))
|
||||
checkErr(err)
|
||||
},
|
||||
}
|
||||
128
cmd/users.go
Normal file
128
cmd/users.go
Normal file
@@ -0,0 +1,128 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"text/tabwriter"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(usersCmd)
|
||||
}
|
||||
|
||||
var usersCmd = &cobra.Command{
|
||||
Use: "users",
|
||||
Short: "Users management utility",
|
||||
Long: `Users management utility.`,
|
||||
Args: cobra.NoArgs,
|
||||
}
|
||||
|
||||
func printUsers(users []*users.User) {
|
||||
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
|
||||
fmt.Fprintln(w, "ID\tUsername\tScope\tLocale\tV. Mode\tAdmin\tExecute\tCreate\tRename\tModify\tDelete\tShare\tDownload\tPwd Lock")
|
||||
|
||||
for _, user := range users {
|
||||
fmt.Fprintf(w, "%d\t%s\t%s\t%s\t%s\t%t\t%t\t%t\t%t\t%t\t%t\t%t\t%t\t%t\t\n",
|
||||
user.ID,
|
||||
user.Username,
|
||||
user.Scope,
|
||||
user.Locale,
|
||||
user.ViewMode,
|
||||
user.Perm.Admin,
|
||||
user.Perm.Execute,
|
||||
user.Perm.Create,
|
||||
user.Perm.Rename,
|
||||
user.Perm.Modify,
|
||||
user.Perm.Delete,
|
||||
user.Perm.Share,
|
||||
user.Perm.Download,
|
||||
user.LockPassword,
|
||||
)
|
||||
}
|
||||
|
||||
w.Flush()
|
||||
}
|
||||
|
||||
func parseUsernameOrID(arg string) (string, uint) {
|
||||
id, err := strconv.ParseUint(arg, 10, 0)
|
||||
if err != nil {
|
||||
return arg, 0
|
||||
}
|
||||
return "", uint(id)
|
||||
}
|
||||
|
||||
func addUserFlags(flags *pflag.FlagSet) {
|
||||
flags.Bool("perm.admin", false, "admin perm for users")
|
||||
flags.Bool("perm.execute", true, "execute perm for users")
|
||||
flags.Bool("perm.create", true, "create perm for users")
|
||||
flags.Bool("perm.rename", true, "rename perm for users")
|
||||
flags.Bool("perm.modify", true, "modify perm for users")
|
||||
flags.Bool("perm.delete", true, "delete perm for users")
|
||||
flags.Bool("perm.share", true, "share perm for users")
|
||||
flags.Bool("perm.download", true, "download perm for users")
|
||||
flags.String("sorting.by", "name", "sorting mode (name, size or modified)")
|
||||
flags.Bool("sorting.asc", false, "sorting by ascending order")
|
||||
flags.Bool("lockPassword", false, "lock password")
|
||||
flags.StringSlice("commands", nil, "a list of the commands a user can execute")
|
||||
flags.String("scope", ".", "scope for users")
|
||||
flags.String("locale", "en", "locale for users")
|
||||
flags.String("viewMode", string(users.ListViewMode), "view mode for users")
|
||||
}
|
||||
|
||||
func getViewMode(flags *pflag.FlagSet) users.ViewMode {
|
||||
viewMode := users.ViewMode(mustGetString(flags, "viewMode"))
|
||||
if viewMode != users.ListViewMode && viewMode != users.MosaicViewMode {
|
||||
checkErr(errors.New("view mode must be \"" + string(users.ListViewMode) + "\" or \"" + string(users.MosaicViewMode) + "\""))
|
||||
}
|
||||
return viewMode
|
||||
}
|
||||
|
||||
func getUserDefaults(flags *pflag.FlagSet, defaults *settings.UserDefaults, all bool) {
|
||||
visit := func(flag *pflag.Flag) {
|
||||
switch flag.Name {
|
||||
case "scope":
|
||||
defaults.Scope = mustGetString(flags, flag.Name)
|
||||
case "locale":
|
||||
defaults.Locale = mustGetString(flags, flag.Name)
|
||||
case "viewMode":
|
||||
defaults.ViewMode = getViewMode(flags)
|
||||
case "perm.admin":
|
||||
defaults.Perm.Admin = mustGetBool(flags, flag.Name)
|
||||
case "perm.execute":
|
||||
defaults.Perm.Execute = mustGetBool(flags, flag.Name)
|
||||
case "perm.create":
|
||||
defaults.Perm.Create = mustGetBool(flags, flag.Name)
|
||||
case "perm.rename":
|
||||
defaults.Perm.Rename = mustGetBool(flags, flag.Name)
|
||||
case "perm.modify":
|
||||
defaults.Perm.Modify = mustGetBool(flags, flag.Name)
|
||||
case "perm.delete":
|
||||
defaults.Perm.Delete = mustGetBool(flags, flag.Name)
|
||||
case "perm.share":
|
||||
defaults.Perm.Share = mustGetBool(flags, flag.Name)
|
||||
case "perm.download":
|
||||
defaults.Perm.Download = mustGetBool(flags, flag.Name)
|
||||
case "commands":
|
||||
commands, err := flags.GetStringSlice(flag.Name)
|
||||
checkErr(err)
|
||||
defaults.Commands = commands
|
||||
case "sorting.by":
|
||||
defaults.Sorting.By = mustGetString(flags, flag.Name)
|
||||
case "sorting.asc":
|
||||
defaults.Sorting.Asc = mustGetBool(flags, flag.Name)
|
||||
}
|
||||
}
|
||||
|
||||
if all {
|
||||
flags.VisitAll(visit)
|
||||
} else {
|
||||
flags.Visit(visit)
|
||||
}
|
||||
}
|
||||
50
cmd/users_add.go
Normal file
50
cmd/users_add.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
usersCmd.AddCommand(usersAddCmd)
|
||||
addUserFlags(usersAddCmd.Flags())
|
||||
}
|
||||
|
||||
var usersAddCmd = &cobra.Command{
|
||||
Use: "add <username> <password>",
|
||||
Short: "Create a new user",
|
||||
Long: `Create a new user and add it to the database.`,
|
||||
Args: cobra.ExactArgs(2),
|
||||
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
|
||||
s, err := d.store.Settings.Get()
|
||||
checkErr(err)
|
||||
getUserDefaults(cmd.Flags(), &s.Defaults, false)
|
||||
|
||||
password, err := users.HashPwd(args[1])
|
||||
checkErr(err)
|
||||
|
||||
user := &users.User{
|
||||
Username: args[0],
|
||||
Password: password,
|
||||
LockPassword: mustGetBool(cmd.Flags(), "lockPassword"),
|
||||
}
|
||||
|
||||
s.Defaults.Apply(user)
|
||||
|
||||
servSettings, err := d.store.Settings.GetServer()
|
||||
checkErr(err)
|
||||
//since getUserDefaults() polluted s.Defaults.Scope
|
||||
//which makes the Scope not the one saved in the db
|
||||
//we need the right s.Defaults.Scope here
|
||||
s2, err := d.store.Settings.Get()
|
||||
checkErr(err)
|
||||
|
||||
userHome, err := s2.MakeUserDir(user.Username, user.Scope, servSettings.Root)
|
||||
checkErr(err)
|
||||
user.Scope = userHome
|
||||
|
||||
err = d.store.Users.Save(user)
|
||||
checkErr(err)
|
||||
printUsers([]*users.User{user})
|
||||
}, pythonConfig{}),
|
||||
}
|
||||
24
cmd/users_export.go
Normal file
24
cmd/users_export.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
usersCmd.AddCommand(usersExportCmd)
|
||||
}
|
||||
|
||||
var usersExportCmd = &cobra.Command{
|
||||
Use: "export <path>",
|
||||
Short: "Export all users to a file.",
|
||||
Long: `Export all users to a json or yaml file. Please indicate the
|
||||
path to the file where you want to write the users.`,
|
||||
Args: jsonYamlArg,
|
||||
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
|
||||
list, err := d.store.Users.Gets("")
|
||||
checkErr(err)
|
||||
|
||||
err = marshal(args[0], list)
|
||||
checkErr(err)
|
||||
}, pythonConfig{}),
|
||||
}
|
||||
50
cmd/users_find.go
Normal file
50
cmd/users_find.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
usersCmd.AddCommand(usersFindCmd)
|
||||
usersCmd.AddCommand(usersLsCmd)
|
||||
}
|
||||
|
||||
var usersFindCmd = &cobra.Command{
|
||||
Use: "find <id|username>",
|
||||
Short: "Find a user by username or id",
|
||||
Long: `Find a user by username or id. If no flag is set, all users will be printed.`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Run: findUsers,
|
||||
}
|
||||
|
||||
var usersLsCmd = &cobra.Command{
|
||||
Use: "ls",
|
||||
Short: "List all users.",
|
||||
Args: cobra.NoArgs,
|
||||
Run: findUsers,
|
||||
}
|
||||
|
||||
var findUsers = python(func(cmd *cobra.Command, args []string, d pythonData) {
|
||||
var (
|
||||
list []*users.User
|
||||
user *users.User
|
||||
err error
|
||||
)
|
||||
|
||||
if len(args) == 1 {
|
||||
username, id := parseUsernameOrID(args[0])
|
||||
if username != "" {
|
||||
user, err = d.store.Users.Get("", username)
|
||||
} else {
|
||||
user, err = d.store.Users.Get("", id)
|
||||
}
|
||||
|
||||
list = []*users.User{user}
|
||||
} else {
|
||||
list, err = d.store.Users.Gets("")
|
||||
}
|
||||
|
||||
checkErr(err)
|
||||
printUsers(list)
|
||||
}, pythonConfig{})
|
||||
87
cmd/users_import.go
Normal file
87
cmd/users_import.go
Normal file
@@ -0,0 +1,87 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
usersCmd.AddCommand(usersImportCmd)
|
||||
usersImportCmd.Flags().Bool("overwrite", false, "overwrite users with the same id/username combo")
|
||||
usersImportCmd.Flags().Bool("replace", false, "replace the entire user base")
|
||||
}
|
||||
|
||||
var usersImportCmd = &cobra.Command{
|
||||
Use: "import <path>",
|
||||
Short: "Import users from a file",
|
||||
Long: `Import users from a file. The path must be for a json or yaml
|
||||
file. You can use this command to import new users to your
|
||||
installation. For that, just don't place their ID on the files
|
||||
list or set it to 0.`,
|
||||
Args: jsonYamlArg,
|
||||
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
|
||||
fd, err := os.Open(args[0])
|
||||
checkErr(err)
|
||||
defer fd.Close()
|
||||
|
||||
list := []*users.User{}
|
||||
err = unmarshal(args[0], &list)
|
||||
checkErr(err)
|
||||
|
||||
for _, user := range list {
|
||||
err = user.Clean("")
|
||||
checkErr(err)
|
||||
}
|
||||
|
||||
if mustGetBool(cmd.Flags(), "replace") {
|
||||
oldUsers, err := d.store.Users.Gets("")
|
||||
checkErr(err)
|
||||
|
||||
err = marshal("users.backup.json", list)
|
||||
checkErr(err)
|
||||
|
||||
for _, user := range oldUsers {
|
||||
err = d.store.Users.Delete(user.ID)
|
||||
checkErr(err)
|
||||
}
|
||||
}
|
||||
|
||||
overwrite := mustGetBool(cmd.Flags(), "overwrite")
|
||||
|
||||
for _, user := range list {
|
||||
onDB, err := d.store.Users.Get("", user.ID)
|
||||
|
||||
// User exists in DB.
|
||||
if err == nil {
|
||||
if !overwrite {
|
||||
checkErr(errors.New("user " + strconv.Itoa(int(user.ID)) + " is already registred"))
|
||||
}
|
||||
|
||||
// If the usernames mismatch, check if there is another one in the DB
|
||||
// with the new username. If there is, print an error and cancel the
|
||||
// operation
|
||||
if user.Username != onDB.Username {
|
||||
conflictuous, err := d.store.Users.Get("", user.Username)
|
||||
if err == nil {
|
||||
checkErr(usernameConflictError(user.Username, conflictuous.ID, user.ID))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// If it doesn't exist, set the ID to 0 to automatically get a new
|
||||
// one that make sense in this DB.
|
||||
user.ID = 0
|
||||
}
|
||||
|
||||
err = d.store.Users.Save(user)
|
||||
checkErr(err)
|
||||
}
|
||||
}, pythonConfig{}),
|
||||
}
|
||||
|
||||
func usernameConflictError(username string, original, new uint) error {
|
||||
return errors.New("can't import user with ID " + strconv.Itoa(int(new)) + " and username \"" + username + "\" because the username is already registred with the user " + strconv.Itoa(int(original)))
|
||||
}
|
||||
31
cmd/users_rm.go
Normal file
31
cmd/users_rm.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
usersCmd.AddCommand(usersRmCmd)
|
||||
}
|
||||
|
||||
var usersRmCmd = &cobra.Command{
|
||||
Use: "rm <id|username>",
|
||||
Short: "Delete a user by username or id",
|
||||
Long: `Delete a user by username or id`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
|
||||
username, id := parseUsernameOrID(args[0])
|
||||
var err error
|
||||
|
||||
if username != "" {
|
||||
err = d.store.Users.Delete(username)
|
||||
} else {
|
||||
err = d.store.Users.Delete(id)
|
||||
}
|
||||
|
||||
checkErr(err)
|
||||
fmt.Println("user deleted successfully")
|
||||
}, pythonConfig{}),
|
||||
}
|
||||
72
cmd/users_update.go
Normal file
72
cmd/users_update.go
Normal file
@@ -0,0 +1,72 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
usersCmd.AddCommand(usersUpdateCmd)
|
||||
|
||||
usersUpdateCmd.Flags().StringP("password", "p", "", "new password")
|
||||
usersUpdateCmd.Flags().StringP("username", "u", "", "new username")
|
||||
addUserFlags(usersUpdateCmd.Flags())
|
||||
}
|
||||
|
||||
var usersUpdateCmd = &cobra.Command{
|
||||
Use: "update <id|username>",
|
||||
Short: "Updates an existing user",
|
||||
Long: `Updates an existing user. Set the flags for the
|
||||
options you want to change.`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
|
||||
username, id := parseUsernameOrID(args[0])
|
||||
flags := cmd.Flags()
|
||||
password := mustGetString(flags, "password")
|
||||
newUsername := mustGetString(flags, "username")
|
||||
|
||||
var (
|
||||
err error
|
||||
user *users.User
|
||||
)
|
||||
|
||||
if id != 0 {
|
||||
user, err = d.store.Users.Get("", id)
|
||||
} else {
|
||||
user, err = d.store.Users.Get("", username)
|
||||
}
|
||||
|
||||
checkErr(err)
|
||||
|
||||
defaults := settings.UserDefaults{
|
||||
Scope: user.Scope,
|
||||
Locale: user.Locale,
|
||||
ViewMode: user.ViewMode,
|
||||
Perm: user.Perm,
|
||||
Sorting: user.Sorting,
|
||||
Commands: user.Commands,
|
||||
}
|
||||
getUserDefaults(flags, &defaults, false)
|
||||
user.Scope = defaults.Scope
|
||||
user.Locale = defaults.Locale
|
||||
user.ViewMode = defaults.ViewMode
|
||||
user.Perm = defaults.Perm
|
||||
user.Commands = defaults.Commands
|
||||
user.Sorting = defaults.Sorting
|
||||
user.LockPassword = mustGetBool(flags, "lockPassword")
|
||||
|
||||
if newUsername != "" {
|
||||
user.Username = newUsername
|
||||
}
|
||||
|
||||
if password != "" {
|
||||
user.Password, err = users.HashPwd(password)
|
||||
checkErr(err)
|
||||
}
|
||||
|
||||
err = d.store.Users.Update(user)
|
||||
checkErr(err)
|
||||
printUsers([]*users.User{user})
|
||||
}, pythonConfig{}),
|
||||
}
|
||||
177
cmd/utils.go
Normal file
177
cmd/utils.go
Normal file
@@ -0,0 +1,177 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/asdine/storm"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/storage"
|
||||
"github.com/filebrowser/filebrowser/v2/storage/bolt"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
yaml "gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
func checkErr(err error) {
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func mustGetString(flags *pflag.FlagSet, flag string) string {
|
||||
s, err := flags.GetString(flag)
|
||||
checkErr(err)
|
||||
return s
|
||||
}
|
||||
|
||||
func mustGetBool(flags *pflag.FlagSet, flag string) bool {
|
||||
b, err := flags.GetBool(flag)
|
||||
checkErr(err)
|
||||
return b
|
||||
}
|
||||
|
||||
func mustGetUint(flags *pflag.FlagSet, flag string) uint {
|
||||
b, err := flags.GetUint(flag)
|
||||
checkErr(err)
|
||||
return b
|
||||
}
|
||||
|
||||
func generateKey() []byte {
|
||||
k, err := settings.GenerateKey()
|
||||
checkErr(err)
|
||||
return k
|
||||
}
|
||||
|
||||
type cobraFunc func(cmd *cobra.Command, args []string)
|
||||
type pythonFunc func(cmd *cobra.Command, args []string, data pythonData)
|
||||
|
||||
type pythonConfig struct {
|
||||
noDB bool
|
||||
allowNoDB bool
|
||||
}
|
||||
|
||||
type pythonData struct {
|
||||
hadDB bool
|
||||
store *storage.Storage
|
||||
}
|
||||
|
||||
func dbExists(path string) (bool, error) {
|
||||
stat, err := os.Stat(path)
|
||||
if err == nil {
|
||||
return stat.Size() != 0, nil
|
||||
}
|
||||
|
||||
if os.IsNotExist(err) {
|
||||
d := filepath.Dir(path)
|
||||
_, err = os.Stat(d)
|
||||
if os.IsNotExist(err) {
|
||||
os.MkdirAll(d, 0700)
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, err
|
||||
}
|
||||
|
||||
func python(fn pythonFunc, cfg pythonConfig) cobraFunc {
|
||||
return func(cmd *cobra.Command, args []string) {
|
||||
data := pythonData{hadDB: true}
|
||||
|
||||
path := getParam(cmd.Flags(), "database")
|
||||
exists, err := dbExists(path)
|
||||
|
||||
if err != nil {
|
||||
panic(err)
|
||||
} else if exists && cfg.noDB {
|
||||
log.Fatal(path + " already exists")
|
||||
} else if !exists && !cfg.noDB && !cfg.allowNoDB {
|
||||
log.Fatal(path + " does not exist. Please run 'filebrowser config init' first.")
|
||||
}
|
||||
|
||||
data.hadDB = exists
|
||||
db, err := storm.Open(path)
|
||||
checkErr(err)
|
||||
defer db.Close()
|
||||
data.store, err = bolt.NewStorage(db)
|
||||
checkErr(err)
|
||||
fn(cmd, args, data)
|
||||
}
|
||||
}
|
||||
|
||||
func marshal(filename string, data interface{}) error {
|
||||
fd, err := os.Create(filename)
|
||||
checkErr(err)
|
||||
defer fd.Close()
|
||||
|
||||
switch ext := filepath.Ext(filename); ext {
|
||||
case ".json":
|
||||
encoder := json.NewEncoder(fd)
|
||||
encoder.SetIndent("", " ")
|
||||
return encoder.Encode(data)
|
||||
case ".yml", ".yaml":
|
||||
encoder := yaml.NewEncoder(fd)
|
||||
return encoder.Encode(data)
|
||||
default:
|
||||
return errors.New("invalid format: " + ext)
|
||||
}
|
||||
}
|
||||
|
||||
func unmarshal(filename string, data interface{}) error {
|
||||
fd, err := os.Open(filename)
|
||||
checkErr(err)
|
||||
defer fd.Close()
|
||||
|
||||
switch ext := filepath.Ext(filename); ext {
|
||||
case ".json":
|
||||
return json.NewDecoder(fd).Decode(data)
|
||||
case ".yml", ".yaml":
|
||||
return yaml.NewDecoder(fd).Decode(data)
|
||||
default:
|
||||
return errors.New("invalid format: " + ext)
|
||||
}
|
||||
}
|
||||
|
||||
func jsonYamlArg(cmd *cobra.Command, args []string) error {
|
||||
if err := cobra.ExactArgs(1)(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
switch ext := filepath.Ext(args[0]); ext {
|
||||
case ".json", ".yml", ".yaml":
|
||||
return nil
|
||||
default:
|
||||
return errors.New("invalid format: " + ext)
|
||||
}
|
||||
}
|
||||
|
||||
func cleanUpInterfaceMap(in map[interface{}]interface{}) map[string]interface{} {
|
||||
result := make(map[string]interface{})
|
||||
for k, v := range in {
|
||||
result[fmt.Sprintf("%v", k)] = cleanUpMapValue(v)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func cleanUpInterfaceArray(in []interface{}) []interface{} {
|
||||
result := make([]interface{}, len(in))
|
||||
for i, v := range in {
|
||||
result[i] = cleanUpMapValue(v)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func cleanUpMapValue(v interface{}) interface{} {
|
||||
switch v := v.(type) {
|
||||
case []interface{}:
|
||||
return cleanUpInterfaceArray(v)
|
||||
case map[interface{}]interface{}:
|
||||
return cleanUpInterfaceMap(v)
|
||||
default:
|
||||
return v
|
||||
}
|
||||
}
|
||||
20
cmd/version.go
Normal file
20
cmd/version.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/version"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(versionCmd)
|
||||
}
|
||||
|
||||
var versionCmd = &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Print the version number",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("File Browser Version " + version.Version)
|
||||
},
|
||||
}
|
||||
73
doc.go
73
doc.go
@@ -1,73 +0,0 @@
|
||||
/*
|
||||
Package filebrowser provides a web interface to access your files
|
||||
wherever you are. To use this package as a middleware for your app,
|
||||
you'll need to import both File Manager and File Manager HTTP packages.
|
||||
|
||||
import (
|
||||
fm "github.com/filebrowser/filebrowser"
|
||||
h "github.com/filebrowser/filebrowser/http"
|
||||
)
|
||||
|
||||
Then, you should create a new FileBrowser object with your options. In this
|
||||
case, I'm using BoltDB (via Storm package) as a Store. So, you'll also need
|
||||
to import "github.com/filebrowser/filebrowser/bolt".
|
||||
|
||||
db, _ := storm.Open("bolt.db")
|
||||
|
||||
m := &fm.FileBrowser{
|
||||
NoAuth: false,
|
||||
DefaultUser: &fm.User{
|
||||
AllowCommands: true,
|
||||
AllowEdit: true,
|
||||
AllowNew: true,
|
||||
AllowPublish: true,
|
||||
Commands: []string{"git"},
|
||||
Rules: []*fm.Rule{},
|
||||
Locale: "en",
|
||||
CSS: "",
|
||||
Scope: ".",
|
||||
FileSystem: fileutils.Dir("."),
|
||||
},
|
||||
Store: &fm.Store{
|
||||
Config: bolt.ConfigStore{DB: db},
|
||||
Users: bolt.UsersStore{DB: db},
|
||||
Share: bolt.ShareStore{DB: db},
|
||||
},
|
||||
NewFS: func(scope string) fm.FileSystem {
|
||||
return fileutils.Dir(scope)
|
||||
},
|
||||
}
|
||||
|
||||
The credentials for the first user are always 'admin' for both the user and
|
||||
the password, and they can be changed later through the settings. The first
|
||||
user is always an Admin and has all of the permissions set to 'true'.
|
||||
|
||||
Then, you should set the Prefix URL and the Base URL, using the following
|
||||
functions:
|
||||
|
||||
m.SetBaseURL("/")
|
||||
m.SetPrefixURL("/")
|
||||
|
||||
The Prefix URL is a part of the path that is already stripped from the
|
||||
r.URL.Path variable before the request arrives to File Manager's handler.
|
||||
This is a function that will rarely be used. You can see one example on Caddy
|
||||
filemanager plugin.
|
||||
|
||||
The Base URL is the URL path where you want File Manager to be available in. If
|
||||
you want to be available at the root path, you should call:
|
||||
|
||||
m.SetBaseURL("/")
|
||||
|
||||
But if you want to access it at '/admin', you would call:
|
||||
|
||||
m.SetBaseURL("/admin")
|
||||
|
||||
Now, that you already have a File Manager instance created, you just need to
|
||||
add it to your handlers using m.ServeHTTP which is compatible to http.Handler.
|
||||
We also have a m.ServeWithErrorsHTTP that returns the status code and an error.
|
||||
|
||||
One simple implementation for this, at port 80, in the root of the domain, would be:
|
||||
|
||||
http.ListenAndServe(":80", h.Handler(m))
|
||||
*/
|
||||
package filebrowser
|
||||
17
errors/errors.go
Normal file
17
errors/errors.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package errors
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrEmptyKey = errors.New("empty key")
|
||||
ErrExist = errors.New("the resource already exists")
|
||||
ErrNotExist = errors.New("the resource does not exist")
|
||||
ErrEmptyPassword = errors.New("password is empty")
|
||||
ErrEmptyUsername = errors.New("username is empty")
|
||||
ErrEmptyRequest = errors.New("empty request")
|
||||
ErrScopeIsRelative = errors.New("scope is a relative path")
|
||||
ErrInvalidDataType = errors.New("invalid data type")
|
||||
ErrIsDirectory = errors.New("file is directory")
|
||||
ErrInvalidOption = errors.New("invalid option")
|
||||
ErrInvalidAuthMethod = errors.New("invalid auth method")
|
||||
)
|
||||
486
file.go
486
file.go
@@ -1,486 +0,0 @@
|
||||
package filebrowser
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"crypto/sha1"
|
||||
"crypto/sha256"
|
||||
"crypto/sha512"
|
||||
"encoding/hex"
|
||||
"hash"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gohugoio/hugo/parser"
|
||||
)
|
||||
|
||||
// File contains the information about a particular file or directory.
|
||||
type File struct {
|
||||
// Indicates the Kind of view on the front-end (Listing, editor or preview).
|
||||
Kind string `json:"kind"`
|
||||
// The name of the file.
|
||||
Name string `json:"name"`
|
||||
// The Size of the file.
|
||||
Size int64 `json:"size"`
|
||||
// The absolute URL.
|
||||
URL string `json:"url"`
|
||||
// The extension of the file.
|
||||
Extension string `json:"extension"`
|
||||
// The last modified time.
|
||||
ModTime time.Time `json:"modified"`
|
||||
// The File Mode.
|
||||
Mode os.FileMode `json:"mode"`
|
||||
// Indicates if this file is a directory.
|
||||
IsDir bool `json:"isDir"`
|
||||
// Absolute path.
|
||||
Path string `json:"path"`
|
||||
// Relative path to user's virtual File System.
|
||||
VirtualPath string `json:"virtualPath"`
|
||||
// Indicates the file content type: video, text, image, music or blob.
|
||||
Type string `json:"type"`
|
||||
// Stores the content of a text file.
|
||||
Content string `json:"content,omitempty"`
|
||||
|
||||
*Listing `json:",omitempty"`
|
||||
|
||||
Metadata string `json:"metadata,omitempty"`
|
||||
Language string `json:"language,omitempty"`
|
||||
}
|
||||
|
||||
// A Listing is the context used to fill out a template.
|
||||
type Listing struct {
|
||||
// The items (files and folders) in the path.
|
||||
Items []*File `json:"items"`
|
||||
// The number of directories in the Listing.
|
||||
NumDirs int `json:"numDirs"`
|
||||
// The number of files (items that aren't directories) in the Listing.
|
||||
NumFiles int `json:"numFiles"`
|
||||
// Which sorting order is used.
|
||||
Sort string `json:"sort"`
|
||||
// And which order.
|
||||
Order string `json:"order"`
|
||||
}
|
||||
|
||||
// GetInfo gets the file information and, in case of error, returns the
|
||||
// respective HTTP error code
|
||||
func GetInfo(url *url.URL, c *FileBrowser, u *User) (*File, error) {
|
||||
var err error
|
||||
|
||||
i := &File{
|
||||
URL: "/files" + url.String(),
|
||||
VirtualPath: url.Path,
|
||||
Path: filepath.Join(u.Scope, url.Path),
|
||||
}
|
||||
|
||||
info, err := u.FileSystem.Stat(url.Path)
|
||||
if err != nil {
|
||||
return i, err
|
||||
}
|
||||
|
||||
i.Name = info.Name()
|
||||
i.ModTime = info.ModTime()
|
||||
i.Mode = info.Mode()
|
||||
i.IsDir = info.IsDir()
|
||||
i.Size = info.Size()
|
||||
i.Extension = filepath.Ext(i.Name)
|
||||
|
||||
if i.IsDir && !strings.HasSuffix(i.URL, "/") {
|
||||
i.URL += "/"
|
||||
}
|
||||
|
||||
return i, nil
|
||||
}
|
||||
|
||||
// GetListing gets the information about a specific directory and its files.
|
||||
func (i *File) GetListing(u *User, r *http.Request) error {
|
||||
// Gets the directory information using the Virtual File System of
|
||||
// the user configuration.
|
||||
f, err := u.FileSystem.OpenFile(i.VirtualPath, os.O_RDONLY, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// Reads the directory and gets the information about the files.
|
||||
files, err := f.Readdir(-1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var (
|
||||
fileinfos []*File
|
||||
dirCount, fileCount int
|
||||
)
|
||||
|
||||
baseurl, err := url.PathUnescape(i.URL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, f := range files {
|
||||
name := f.Name()
|
||||
allowed := u.Allowed("/" + name)
|
||||
|
||||
if !allowed {
|
||||
continue
|
||||
}
|
||||
|
||||
if strings.HasPrefix(f.Mode().String(), "L") {
|
||||
// It's a symbolic link. We try to follow it. If it doesn't work,
|
||||
// we stay with the link information instead if the target's.
|
||||
info, err := os.Stat(f.Name())
|
||||
if err == nil {
|
||||
f = info
|
||||
}
|
||||
}
|
||||
|
||||
if f.IsDir() {
|
||||
name += "/"
|
||||
dirCount++
|
||||
} else {
|
||||
fileCount++
|
||||
}
|
||||
|
||||
// Absolute URL
|
||||
url := url.URL{Path: baseurl + name}
|
||||
|
||||
i := &File{
|
||||
Name: f.Name(),
|
||||
Size: f.Size(),
|
||||
ModTime: f.ModTime(),
|
||||
Mode: f.Mode(),
|
||||
IsDir: f.IsDir(),
|
||||
URL: url.String(),
|
||||
Extension: filepath.Ext(name),
|
||||
VirtualPath: filepath.Join(i.VirtualPath, name),
|
||||
Path: filepath.Join(i.Path, name),
|
||||
}
|
||||
|
||||
i.GetFileType(false)
|
||||
fileinfos = append(fileinfos, i)
|
||||
}
|
||||
|
||||
i.Listing = &Listing{
|
||||
Items: fileinfos,
|
||||
NumDirs: dirCount,
|
||||
NumFiles: fileCount,
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetEditor gets the editor based on a Info struct
|
||||
func (i *File) GetEditor() error {
|
||||
i.Language = editorLanguage(i.Extension)
|
||||
// If the editor will hold only content, leave now.
|
||||
if editorMode(i.Language) == "content" {
|
||||
return nil
|
||||
}
|
||||
|
||||
// If the file doesn't have any kind of metadata, leave now.
|
||||
if !hasRune(i.Content) {
|
||||
return nil
|
||||
}
|
||||
|
||||
buffer := bytes.NewBuffer([]byte(i.Content))
|
||||
page, err := parser.ReadFrom(buffer)
|
||||
|
||||
// If there is an error, just ignore it and return nil.
|
||||
// This way, the file can be served for editing.
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
i.Content = strings.TrimSpace(string(page.Content()))
|
||||
i.Metadata = strings.TrimSpace(string(page.FrontMatter()))
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetFileType obtains the mimetype and converts it to a simple
|
||||
// type nomenclature.
|
||||
func (i *File) GetFileType(checkContent bool) error {
|
||||
var content []byte
|
||||
var err error
|
||||
|
||||
// Tries to get the file mimetype using its extension.
|
||||
mimetype := mime.TypeByExtension(i.Extension)
|
||||
|
||||
if mimetype == "" && checkContent {
|
||||
file, err := os.Open(i.Path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// Only the first 512 bytes are used to sniff the content type.
|
||||
buffer := make([]byte, 512)
|
||||
_, err = file.Read(buffer)
|
||||
if err != nil && err != io.EOF {
|
||||
return err
|
||||
}
|
||||
|
||||
// Tries to get the file mimetype using its first
|
||||
// 512 bytes.
|
||||
mimetype = http.DetectContentType(buffer)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(mimetype, "video") {
|
||||
i.Type = "video"
|
||||
return nil
|
||||
}
|
||||
|
||||
if strings.HasPrefix(mimetype, "audio") {
|
||||
i.Type = "audio"
|
||||
return nil
|
||||
}
|
||||
|
||||
if strings.HasPrefix(mimetype, "image") {
|
||||
i.Type = "image"
|
||||
return nil
|
||||
}
|
||||
|
||||
if strings.HasPrefix(mimetype, "text") {
|
||||
i.Type = "text"
|
||||
goto End
|
||||
}
|
||||
|
||||
if strings.HasPrefix(mimetype, "application/javascript") {
|
||||
i.Type = "text"
|
||||
goto End
|
||||
}
|
||||
|
||||
// If the type isn't text (and is blob for example), it will check some
|
||||
// common types that are mistaken not to be text.
|
||||
if isInTextExtensions(i.Name) {
|
||||
i.Type = "text"
|
||||
} else {
|
||||
i.Type = "blob"
|
||||
}
|
||||
|
||||
End:
|
||||
// If the file type is text, save its content.
|
||||
if i.Type == "text" {
|
||||
if len(content) == 0 {
|
||||
content, err = ioutil.ReadFile(i.Path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
i.Content = string(content)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Checksum retrieves the checksum of a file.
|
||||
func (i File) Checksum(algo string) (string, error) {
|
||||
file, err := os.Open(i.Path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
defer file.Close()
|
||||
|
||||
var h hash.Hash
|
||||
|
||||
switch algo {
|
||||
case "md5":
|
||||
h = md5.New()
|
||||
case "sha1":
|
||||
h = sha1.New()
|
||||
case "sha256":
|
||||
h = sha256.New()
|
||||
case "sha512":
|
||||
h = sha512.New()
|
||||
default:
|
||||
return "", ErrInvalidOption
|
||||
}
|
||||
|
||||
_, err = io.Copy(h, file)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return hex.EncodeToString(h.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// CanBeEdited checks if the extension of a file is supported by the editor
|
||||
func (i File) CanBeEdited() bool {
|
||||
return i.Type == "text"
|
||||
}
|
||||
|
||||
// ApplySort applies the sort order using .Order and .Sort
|
||||
func (l Listing) ApplySort() {
|
||||
// Check '.Order' to know how to sort
|
||||
if l.Order == "desc" {
|
||||
switch l.Sort {
|
||||
case "name":
|
||||
sort.Sort(sort.Reverse(byName(l)))
|
||||
case "size":
|
||||
sort.Sort(sort.Reverse(bySize(l)))
|
||||
case "modified":
|
||||
sort.Sort(sort.Reverse(byModified(l)))
|
||||
default:
|
||||
// If not one of the above, do nothing
|
||||
return
|
||||
}
|
||||
} else { // If we had more Orderings we could add them here
|
||||
switch l.Sort {
|
||||
case "name":
|
||||
sort.Sort(byName(l))
|
||||
case "size":
|
||||
sort.Sort(bySize(l))
|
||||
case "modified":
|
||||
sort.Sort(byModified(l))
|
||||
default:
|
||||
sort.Sort(byName(l))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Implement sorting for Listing
|
||||
type byName Listing
|
||||
type bySize Listing
|
||||
type byModified Listing
|
||||
|
||||
// By Name
|
||||
func (l byName) Len() int {
|
||||
return len(l.Items)
|
||||
}
|
||||
|
||||
func (l byName) Swap(i, j int) {
|
||||
l.Items[i], l.Items[j] = l.Items[j], l.Items[i]
|
||||
}
|
||||
|
||||
// Treat upper and lower case equally
|
||||
func (l byName) Less(i, j int) bool {
|
||||
if l.Items[i].IsDir && !l.Items[j].IsDir {
|
||||
return true
|
||||
}
|
||||
|
||||
if !l.Items[i].IsDir && l.Items[j].IsDir {
|
||||
return false
|
||||
}
|
||||
|
||||
return strings.ToLower(l.Items[i].Name) < strings.ToLower(l.Items[j].Name)
|
||||
}
|
||||
|
||||
// By Size
|
||||
func (l bySize) Len() int {
|
||||
return len(l.Items)
|
||||
}
|
||||
|
||||
func (l bySize) Swap(i, j int) {
|
||||
l.Items[i], l.Items[j] = l.Items[j], l.Items[i]
|
||||
}
|
||||
|
||||
const directoryOffset = -1 << 31 // = math.MinInt32
|
||||
func (l bySize) Less(i, j int) bool {
|
||||
iSize, jSize := l.Items[i].Size, l.Items[j].Size
|
||||
if l.Items[i].IsDir {
|
||||
iSize = directoryOffset + iSize
|
||||
}
|
||||
if l.Items[j].IsDir {
|
||||
jSize = directoryOffset + jSize
|
||||
}
|
||||
return iSize < jSize
|
||||
}
|
||||
|
||||
// By Modified
|
||||
func (l byModified) Len() int {
|
||||
return len(l.Items)
|
||||
}
|
||||
|
||||
func (l byModified) Swap(i, j int) {
|
||||
l.Items[i], l.Items[j] = l.Items[j], l.Items[i]
|
||||
}
|
||||
|
||||
func (l byModified) Less(i, j int) bool {
|
||||
iModified, jModified := l.Items[i].ModTime, l.Items[j].ModTime
|
||||
return iModified.Sub(jModified) < 0
|
||||
}
|
||||
|
||||
// textExtensions is the sorted list of text extensions which
|
||||
// can be edited.
|
||||
var textExtensions = []string{
|
||||
".ad", ".ada", ".adoc", ".asciidoc",
|
||||
".bas", ".bash", ".bat",
|
||||
".c", ".cc", ".cmd", ".conf", ".cpp", ".cr", ".cs", ".css", ".csv",
|
||||
".d",
|
||||
".f", ".f90",
|
||||
".h", ".hh", ".hpp", ".htaccess", ".html",
|
||||
".ini",
|
||||
".java", ".js", ".json",
|
||||
".markdown", ".md", ".mdown", ".mmark",
|
||||
".nim",
|
||||
".php", ".pl", ".ps1", ".py",
|
||||
".rss", ".rst", ".rtf",
|
||||
".sass", ".scss", ".sh", ".sty",
|
||||
".tex", ".tml", ".toml", ".txt",
|
||||
".vala", ".vapi",
|
||||
".xml",
|
||||
".yaml", ".yml",
|
||||
"Caddyfile",
|
||||
}
|
||||
|
||||
// isInTextExtensions checks if a file can be edited by its extensions.
|
||||
func isInTextExtensions(name string) bool {
|
||||
search := filepath.Ext(name)
|
||||
if search == "" {
|
||||
search = name
|
||||
}
|
||||
|
||||
i := sort.SearchStrings(textExtensions, search)
|
||||
return i < len(textExtensions) && textExtensions[i] == search
|
||||
}
|
||||
|
||||
// hasRune checks if the file has the frontmatter rune
|
||||
func hasRune(file string) bool {
|
||||
return strings.HasPrefix(file, "---") ||
|
||||
strings.HasPrefix(file, "+++") ||
|
||||
strings.HasPrefix(file, "{")
|
||||
}
|
||||
|
||||
func editorMode(language string) string {
|
||||
switch language {
|
||||
case "markdown", "asciidoc", "rst":
|
||||
return "content+metadata"
|
||||
}
|
||||
|
||||
return "content"
|
||||
}
|
||||
|
||||
func editorLanguage(mode string) string {
|
||||
mode = strings.TrimPrefix(mode, ".")
|
||||
|
||||
switch mode {
|
||||
case "md", "markdown", "mdown", "mmark":
|
||||
mode = "markdown"
|
||||
case "yml":
|
||||
mode = "yaml"
|
||||
case "asciidoc", "adoc", "ad":
|
||||
mode = "asciidoc"
|
||||
case "rst":
|
||||
mode = "rst"
|
||||
case "html", "htm", "xml":
|
||||
mode = "htmlmixed"
|
||||
case "js":
|
||||
mode = "javascript"
|
||||
case "go":
|
||||
mode = "golang"
|
||||
case "":
|
||||
mode = "text"
|
||||
}
|
||||
|
||||
return mode
|
||||
}
|
||||
558
filebrowser.go
558
filebrowser.go
@@ -1,558 +0,0 @@
|
||||
package filebrowser
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"github.com/GeertJohan/go.rice"
|
||||
"github.com/hacdias/fileutils"
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/robfig/cron"
|
||||
)
|
||||
|
||||
const (
|
||||
// Version is the current File Manager version.
|
||||
Version = "1.6.0"
|
||||
|
||||
ListViewMode = "list"
|
||||
MosaicViewMode = "mosaic"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrExist = errors.New("the resource already exists")
|
||||
ErrNotExist = errors.New("the resource does not exist")
|
||||
ErrEmptyRequest = errors.New("request body is empty")
|
||||
ErrEmptyPassword = errors.New("password is empty")
|
||||
ErrEmptyUsername = errors.New("username is empty")
|
||||
ErrEmptyScope = errors.New("scope is empty")
|
||||
ErrWrongDataType = errors.New("wrong data type")
|
||||
ErrInvalidUpdateField = errors.New("invalid field to update")
|
||||
ErrInvalidOption = errors.New("invalid option")
|
||||
)
|
||||
|
||||
// FileBrowser is a file manager instance. It should be creating using the
|
||||
// 'New' function and not directly.
|
||||
type FileBrowser struct {
|
||||
// Cron job to manage schedulings.
|
||||
Cron *cron.Cron
|
||||
|
||||
// The key used to sign the JWT tokens.
|
||||
Key []byte
|
||||
|
||||
// The static assets.
|
||||
Assets *rice.Box
|
||||
|
||||
// The Store is used to manage users, shareable links and
|
||||
// other stuff that is saved on the database.
|
||||
Store *Store
|
||||
|
||||
// PrefixURL is a part of the URL that is already trimmed from the request URL before it
|
||||
// arrives to our handlers. It may be useful when using File Manager as a middleware
|
||||
// such as in caddy-filemanager plugin. It is only useful in certain situations.
|
||||
PrefixURL string
|
||||
|
||||
// BaseURL is the path where the GUI will be accessible. It musn't end with
|
||||
// a trailing slash and mustn't contain PrefixURL, if set. It shouldn't be
|
||||
// edited directly. Use SetBaseURL.
|
||||
BaseURL string
|
||||
|
||||
// NoAuth disables the authentication. When the authentication is disabled,
|
||||
// there will only exist one user, called "admin".
|
||||
NoAuth bool
|
||||
|
||||
// ReCaptcha host, key and secret.
|
||||
ReCaptchaHost string
|
||||
ReCaptchaKey string
|
||||
ReCaptchaSecret string
|
||||
|
||||
// StaticGen is the static websit generator handler.
|
||||
StaticGen StaticGen
|
||||
|
||||
// The Default User needed to build the New User page.
|
||||
DefaultUser *User
|
||||
|
||||
// A map of events to a slice of commands.
|
||||
Commands map[string][]string
|
||||
|
||||
// Global stylesheet.
|
||||
CSS string
|
||||
|
||||
// NewFS should build a new file system for a given path.
|
||||
NewFS FSBuilder
|
||||
}
|
||||
|
||||
var commandEvents = []string{
|
||||
"before_save",
|
||||
"after_save",
|
||||
"before_publish",
|
||||
"after_publish",
|
||||
"before_copy",
|
||||
"after_copy",
|
||||
"before_rename",
|
||||
"after_rename",
|
||||
"before_upload",
|
||||
"after_upload",
|
||||
"before_delete",
|
||||
"after_delete",
|
||||
}
|
||||
|
||||
// Command is a command function.
|
||||
type Command func(r *http.Request, m *FileBrowser, u *User) error
|
||||
|
||||
// FSBuilder is the File System Builder.
|
||||
type FSBuilder func(scope string) FileSystem
|
||||
|
||||
// Setup loads the configuration from the database and configures
|
||||
// the Assets and the Cron job. It must always be run after
|
||||
// creating a File Manager object.
|
||||
func (m *FileBrowser) Setup() error {
|
||||
// Creates a new File Manager instance with the Users
|
||||
// map and Assets box.
|
||||
m.Assets = rice.MustFindBox("./node_modules/filebrowser-frontend/dist")
|
||||
m.Cron = cron.New()
|
||||
|
||||
// Tries to get the encryption key from the database.
|
||||
// If it doesn't exist, create a new one of 256 bits.
|
||||
err := m.Store.Config.Get("key", &m.Key)
|
||||
if err != nil && err == ErrNotExist {
|
||||
var bytes []byte
|
||||
bytes, err = GenerateRandomBytes(64)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
m.Key = bytes
|
||||
err = m.Store.Config.Save("key", m.Key)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Get the global CSS.
|
||||
err = m.Store.Config.Get("css", &m.CSS)
|
||||
if err != nil && err == ErrNotExist {
|
||||
err = m.Store.Config.Save("css", "")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Tries to get the event commands from the database.
|
||||
// If they don't exist, initialize them.
|
||||
err = m.Store.Config.Get("commands", &m.Commands)
|
||||
|
||||
if err == nil {
|
||||
// Add hypothetically new command handlers.
|
||||
for _, command := range commandEvents {
|
||||
if _, ok := m.Commands[command]; ok {
|
||||
continue
|
||||
}
|
||||
|
||||
m.Commands[command] = []string{}
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil && err == ErrNotExist {
|
||||
m.Commands = map[string][]string{}
|
||||
|
||||
// Initialize the command handlers.
|
||||
for _, command := range commandEvents {
|
||||
m.Commands[command] = []string{}
|
||||
}
|
||||
|
||||
err = m.Store.Config.Save("commands", m.Commands)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Tries to fetch the users from the database.
|
||||
users, err := m.Store.Users.Gets(m.NewFS)
|
||||
if err != nil && err != ErrNotExist {
|
||||
return err
|
||||
}
|
||||
|
||||
// If there are no users in the database, it creates a new one
|
||||
// based on 'base' User that must be provided by the function caller.
|
||||
if len(users) == 0 {
|
||||
u := *m.DefaultUser
|
||||
u.Username = "admin"
|
||||
|
||||
// Hashes the password.
|
||||
u.Password, err = HashPassword("admin")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// The first user must be an administrator.
|
||||
u.Admin = true
|
||||
u.AllowCommands = true
|
||||
u.AllowNew = true
|
||||
u.AllowEdit = true
|
||||
u.AllowPublish = true
|
||||
|
||||
// Saves the user to the database.
|
||||
if err := m.Store.Users.Save(&u); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
m.DefaultUser.Username = ""
|
||||
m.DefaultUser.Password = ""
|
||||
|
||||
m.Cron.AddFunc("@hourly", m.ShareCleaner)
|
||||
m.Cron.Start()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// RootURL returns the actual URL where
|
||||
// File Manager interface can be accessed.
|
||||
func (m FileBrowser) RootURL() string {
|
||||
return m.PrefixURL + m.BaseURL
|
||||
}
|
||||
|
||||
// SetPrefixURL updates the prefixURL of a File
|
||||
// Manager object.
|
||||
func (m *FileBrowser) SetPrefixURL(url string) {
|
||||
url = strings.TrimPrefix(url, "/")
|
||||
url = strings.TrimSuffix(url, "/")
|
||||
url = "/" + url
|
||||
m.PrefixURL = strings.TrimSuffix(url, "/")
|
||||
}
|
||||
|
||||
// SetBaseURL updates the baseURL of a File Manager
|
||||
// object.
|
||||
func (m *FileBrowser) SetBaseURL(url string) {
|
||||
url = strings.TrimPrefix(url, "/")
|
||||
url = strings.TrimSuffix(url, "/")
|
||||
url = "/" + url
|
||||
m.BaseURL = strings.TrimSuffix(url, "/")
|
||||
}
|
||||
|
||||
// Attach attaches a static generator to the current File Manager.
|
||||
func (m *FileBrowser) Attach(s StaticGen) error {
|
||||
if reflect.TypeOf(s).Kind() != reflect.Ptr {
|
||||
return errors.New("data should be a pointer to interface, not interface")
|
||||
}
|
||||
|
||||
err := s.Setup()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
m.StaticGen = s
|
||||
|
||||
err = m.Store.Config.Get("staticgen_"+s.Name(), s)
|
||||
if err == ErrNotExist {
|
||||
return m.Store.Config.Save("staticgen_"+s.Name(), s)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ShareCleaner removes sharing links that are no longer active.
|
||||
// This function is set to run periodically.
|
||||
func (m FileBrowser) ShareCleaner() {
|
||||
// Get all links.
|
||||
links, err := m.Store.Share.Gets()
|
||||
if err != nil {
|
||||
log.Print(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Find the expired ones.
|
||||
for i := range links {
|
||||
if links[i].Expires && links[i].ExpireDate.Before(time.Now()) {
|
||||
err = m.Store.Share.Delete(links[i].Hash)
|
||||
if err != nil {
|
||||
log.Print(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Runner runs the commands for a certain event type.
|
||||
func (m FileBrowser) Runner(event string, path string, destination string, user *User) error {
|
||||
commands := []string{}
|
||||
|
||||
// Get the commands from the File Manager instance itself.
|
||||
if val, ok := m.Commands[event]; ok {
|
||||
commands = append(commands, val...)
|
||||
}
|
||||
|
||||
// Execute the commands.
|
||||
for _, command := range commands {
|
||||
args := strings.Split(command, " ")
|
||||
nonblock := false
|
||||
|
||||
if len(args) > 1 && args[len(args)-1] == "&" {
|
||||
// Run command in background; non-blocking
|
||||
nonblock = true
|
||||
args = args[:len(args)-1]
|
||||
}
|
||||
|
||||
command, args, err := caddy.SplitCommandAndArgs(strings.Join(args, " "))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cmd := exec.Command(command, args...)
|
||||
cmd.Env = append(os.Environ(), fmt.Sprintf("FILE=%s", path))
|
||||
cmd.Env = append(cmd.Env, fmt.Sprintf("ROOT=%s", user.Scope))
|
||||
cmd.Env = append(cmd.Env, fmt.Sprintf("TRIGGER=%s", event))
|
||||
cmd.Env = append(cmd.Env, fmt.Sprintf("USERNAME=%s", user.Username))
|
||||
|
||||
if destination != "" {
|
||||
cmd.Env = append(cmd.Env, fmt.Sprintf("DESTINATION=%s", destination))
|
||||
}
|
||||
|
||||
cmd.Stdin = os.Stdin
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
|
||||
if nonblock {
|
||||
log.Printf("[INFO] Nonblocking Command:\"%s %s\"", command, strings.Join(args, " "))
|
||||
if err := cmd.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
log.Printf("[INFO] Blocking Command:\"%s %s\"", command, strings.Join(args, " "))
|
||||
if err := cmd.Run(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// DefaultUser is used on New, when no 'base' user is provided.
|
||||
var DefaultUser = User{
|
||||
AllowCommands: true,
|
||||
AllowEdit: true,
|
||||
AllowNew: true,
|
||||
AllowPublish: true,
|
||||
LockPassword: false,
|
||||
Commands: []string{},
|
||||
Rules: []*Rule{},
|
||||
CSS: "",
|
||||
Admin: true,
|
||||
Locale: "",
|
||||
Scope: ".",
|
||||
FileSystem: fileutils.Dir("."),
|
||||
ViewMode: "mosaic",
|
||||
}
|
||||
|
||||
// User contains the configuration for each user.
|
||||
type User struct {
|
||||
// ID is the required primary key with auto increment0
|
||||
ID int `storm:"id,increment"`
|
||||
|
||||
// Tells if this user is an admin.
|
||||
Admin bool `json:"admin"`
|
||||
|
||||
// These indicate if the user can perform certain actions.
|
||||
AllowCommands bool `json:"allowCommands"` // Execute commands
|
||||
AllowEdit bool `json:"allowEdit"` // Edit/rename files
|
||||
AllowNew bool `json:"allowNew"` // Create files and folders
|
||||
AllowPublish bool `json:"allowPublish"` // Publish content (to use with static gen)
|
||||
|
||||
// Prevents the user to change its password.
|
||||
LockPassword bool `json:"lockPassword"`
|
||||
|
||||
// Commands is the list of commands the user can execute.
|
||||
Commands []string `json:"commands"`
|
||||
|
||||
// Custom styles for this user.
|
||||
CSS string `json:"css"`
|
||||
|
||||
// FileSystem is the virtual file system the user has access.
|
||||
FileSystem FileSystem `json:"-"`
|
||||
|
||||
// Locale is the language of the user.
|
||||
Locale string `json:"locale"`
|
||||
|
||||
// The hashed password. This never reaches the front-end because it's temporarily
|
||||
// emptied during JSON marshall.
|
||||
Password string `json:"password"`
|
||||
|
||||
// Rules is an array of access and deny rules.
|
||||
Rules []*Rule `json:"rules"`
|
||||
|
||||
// Scope is the path the user has access to.
|
||||
Scope string `json:"filesystem"`
|
||||
|
||||
// Username is the user username used to login.
|
||||
Username string `json:"username" storm:"index,unique"`
|
||||
|
||||
// User view mode for files and folders.
|
||||
ViewMode string `json:"viewMode"`
|
||||
}
|
||||
|
||||
// Allowed checks if the user has permission to access a directory/file.
|
||||
func (u User) Allowed(url string) bool {
|
||||
var rule *Rule
|
||||
i := len(u.Rules) - 1
|
||||
|
||||
for i >= 0 {
|
||||
rule = u.Rules[i]
|
||||
|
||||
if rule.Regex {
|
||||
if rule.Regexp.MatchString(url) {
|
||||
return rule.Allow
|
||||
}
|
||||
} else if strings.HasPrefix(url, rule.Path) {
|
||||
return rule.Allow
|
||||
}
|
||||
|
||||
i--
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Rule is a dissalow/allow rule.
|
||||
type Rule struct {
|
||||
// Regex indicates if this rule uses Regular Expressions or not.
|
||||
Regex bool `json:"regex"`
|
||||
|
||||
// Allow indicates if this is an allow rule. Set 'false' to be a disallow rule.
|
||||
Allow bool `json:"allow"`
|
||||
|
||||
// Path is the corresponding URL path for this rule.
|
||||
Path string `json:"path"`
|
||||
|
||||
// Regexp is the regular expression. Only use this when 'Regex' was set to true.
|
||||
Regexp *Regexp `json:"regexp"`
|
||||
}
|
||||
|
||||
// Regexp is a regular expression wrapper around native regexp.
|
||||
type Regexp struct {
|
||||
Raw string `json:"raw"`
|
||||
regexp *regexp.Regexp
|
||||
}
|
||||
|
||||
// MatchString checks if this string matches the regular expression.
|
||||
func (r *Regexp) MatchString(s string) bool {
|
||||
if r.regexp == nil {
|
||||
r.regexp = regexp.MustCompile(r.Raw)
|
||||
}
|
||||
|
||||
return r.regexp.MatchString(s)
|
||||
}
|
||||
|
||||
// ShareLink is the information needed to build a shareable link.
|
||||
type ShareLink struct {
|
||||
Hash string `json:"hash" storm:"id,index"`
|
||||
Path string `json:"path" storm:"index"`
|
||||
Expires bool `json:"expires"`
|
||||
ExpireDate time.Time `json:"expireDate"`
|
||||
}
|
||||
|
||||
// Store is a collection of the stores needed to get
|
||||
// and save information.
|
||||
type Store struct {
|
||||
Users UsersStore
|
||||
Config ConfigStore
|
||||
Share ShareStore
|
||||
}
|
||||
|
||||
// UsersStore is the interface to manage users.
|
||||
type UsersStore interface {
|
||||
Get(id int, builder FSBuilder) (*User, error)
|
||||
GetByUsername(username string, builder FSBuilder) (*User, error)
|
||||
Gets(builder FSBuilder) ([]*User, error)
|
||||
Save(u *User) error
|
||||
Update(u *User, fields ...string) error
|
||||
Delete(id int) error
|
||||
}
|
||||
|
||||
// ConfigStore is the interface to manage configuration.
|
||||
type ConfigStore interface {
|
||||
Get(name string, to interface{}) error
|
||||
Save(name string, from interface{}) error
|
||||
}
|
||||
|
||||
// ShareStore is the interface to manage share links.
|
||||
type ShareStore interface {
|
||||
Get(hash string) (*ShareLink, error)
|
||||
GetPermanent(path string) (*ShareLink, error)
|
||||
GetByPath(path string) ([]*ShareLink, error)
|
||||
Gets() ([]*ShareLink, error)
|
||||
Save(s *ShareLink) error
|
||||
Delete(hash string) error
|
||||
}
|
||||
|
||||
// StaticGen is a static website generator.
|
||||
type StaticGen interface {
|
||||
SettingsPath() string
|
||||
Name() string
|
||||
Setup() error
|
||||
|
||||
Hook(c *Context, w http.ResponseWriter, r *http.Request) (int, error)
|
||||
Preview(c *Context, w http.ResponseWriter, r *http.Request) (int, error)
|
||||
Publish(c *Context, w http.ResponseWriter, r *http.Request) (int, error)
|
||||
}
|
||||
|
||||
// FileSystem is the interface to work with the file system.
|
||||
type FileSystem interface {
|
||||
Mkdir(name string, perm os.FileMode) error
|
||||
OpenFile(name string, flag int, perm os.FileMode) (*os.File, error)
|
||||
RemoveAll(name string) error
|
||||
Rename(oldName, newName string) error
|
||||
Stat(name string) (os.FileInfo, error)
|
||||
Copy(src, dst string) error
|
||||
}
|
||||
|
||||
// Context contains the needed information to make handlers work.
|
||||
type Context struct {
|
||||
*FileBrowser
|
||||
User *User
|
||||
File *File
|
||||
// On API handlers, Router is the APi handler we want.
|
||||
Router string
|
||||
}
|
||||
|
||||
// HashPassword generates an hash from a password using bcrypt.
|
||||
func HashPassword(password string) (string, error) {
|
||||
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
return string(bytes), err
|
||||
}
|
||||
|
||||
// CheckPasswordHash compares a password with an hash to check if they match.
|
||||
func CheckPasswordHash(password, hash string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// GenerateRandomBytes returns securely generated random bytes.
|
||||
// It will return an fm.Error if the system's secure random
|
||||
// number generator fails to function correctly, in which
|
||||
// case the caller should not continue.
|
||||
func GenerateRandomBytes(n int) ([]byte, error) {
|
||||
b := make([]byte, n)
|
||||
_, err := rand.Read(b)
|
||||
// Note that err == nil only if we read len(b) bytes.
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return b, nil
|
||||
}
|
||||
264
files/file.go
Normal file
264
files/file.go
Normal file
@@ -0,0 +1,264 @@
|
||||
package files
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"crypto/sha1"
|
||||
"crypto/sha256"
|
||||
"crypto/sha512"
|
||||
"encoding/hex"
|
||||
"hash"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/errors"
|
||||
"github.com/filebrowser/filebrowser/v2/rules"
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
// FileInfo describes a file.
|
||||
type FileInfo struct {
|
||||
*Listing
|
||||
Fs afero.Fs `json:"-"`
|
||||
Path string `json:"path"`
|
||||
Name string `json:"name"`
|
||||
Size int64 `json:"size"`
|
||||
Extension string `json:"extension"`
|
||||
ModTime time.Time `json:"modified"`
|
||||
Mode os.FileMode `json:"mode"`
|
||||
IsDir bool `json:"isDir"`
|
||||
Type string `json:"type"`
|
||||
Subtitles []string `json:"subtitles,omitempty"`
|
||||
Content string `json:"content,omitempty"`
|
||||
Checksums map[string]string `json:"checksums,omitempty"`
|
||||
}
|
||||
|
||||
// FileOptions are the options when getting a file info.
|
||||
type FileOptions struct {
|
||||
Fs afero.Fs
|
||||
Path string
|
||||
Modify bool
|
||||
Expand bool
|
||||
Checker rules.Checker
|
||||
}
|
||||
|
||||
// NewFileInfo creates a File object from a path and a given user. This File
|
||||
// object will be automatically filled depending on if it is a directory
|
||||
// or a file. If it's a video file, it will also detect any subtitles.
|
||||
func NewFileInfo(opts FileOptions) (*FileInfo, error) {
|
||||
if !opts.Checker.Check(opts.Path) {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
|
||||
info, err := opts.Fs.Stat(opts.Path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
file := &FileInfo{
|
||||
Fs: opts.Fs,
|
||||
Path: opts.Path,
|
||||
Name: info.Name(),
|
||||
ModTime: info.ModTime(),
|
||||
Mode: info.Mode(),
|
||||
IsDir: info.IsDir(),
|
||||
Size: info.Size(),
|
||||
Extension: filepath.Ext(info.Name()),
|
||||
}
|
||||
|
||||
if opts.Expand {
|
||||
if file.IsDir {
|
||||
return file, file.readListing(opts.Checker)
|
||||
}
|
||||
|
||||
err = file.detectType(opts.Modify, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return file, err
|
||||
}
|
||||
|
||||
// Checksum checksums a given File for a given User, using a specific
|
||||
// algorithm. The checksums data is saved on File object.
|
||||
func (i *FileInfo) Checksum(algo string) error {
|
||||
if i.IsDir {
|
||||
return errors.ErrIsDirectory
|
||||
}
|
||||
|
||||
if i.Checksums == nil {
|
||||
i.Checksums = map[string]string{}
|
||||
}
|
||||
|
||||
reader, err := i.Fs.Open(i.Path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
var h hash.Hash
|
||||
|
||||
switch algo {
|
||||
case "md5":
|
||||
h = md5.New()
|
||||
case "sha1":
|
||||
h = sha1.New()
|
||||
case "sha256":
|
||||
h = sha256.New()
|
||||
case "sha512":
|
||||
h = sha512.New()
|
||||
default:
|
||||
return errors.ErrInvalidOption
|
||||
}
|
||||
|
||||
_, err = io.Copy(h, reader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
i.Checksums[algo] = hex.EncodeToString(h.Sum(nil))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *FileInfo) detectType(modify, saveContent bool) error {
|
||||
// failing to detect the type should not return error.
|
||||
// imagine the situation where a file in a dir with thousands
|
||||
// of files couldn't be opened: we'd have immediately
|
||||
// a 500 even though it doesn't matter. So we just log it.
|
||||
reader, err := i.Fs.Open(i.Path)
|
||||
if err != nil {
|
||||
log.Print(err)
|
||||
i.Type = "blob"
|
||||
return nil
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
buffer := make([]byte, 512)
|
||||
n, err := reader.Read(buffer)
|
||||
if err != nil && err != io.EOF {
|
||||
log.Print(err)
|
||||
i.Type = "blob"
|
||||
return nil
|
||||
}
|
||||
|
||||
mimetype := mime.TypeByExtension(i.Extension)
|
||||
if mimetype == "" {
|
||||
mimetype = http.DetectContentType(buffer[:n])
|
||||
}
|
||||
|
||||
switch {
|
||||
case strings.HasPrefix(mimetype, "video"):
|
||||
i.Type = "video"
|
||||
i.detectSubtitles()
|
||||
return nil
|
||||
case strings.HasPrefix(mimetype, "audio"):
|
||||
i.Type = "audio"
|
||||
return nil
|
||||
case strings.HasPrefix(mimetype, "image"):
|
||||
i.Type = "image"
|
||||
return nil
|
||||
case isBinary(buffer[:n], n) || i.Size > 10*1024*1024: // 10 MB
|
||||
i.Type = "blob"
|
||||
return nil
|
||||
default:
|
||||
i.Type = "text"
|
||||
|
||||
if !modify {
|
||||
i.Type = "textImmutable"
|
||||
}
|
||||
|
||||
if saveContent {
|
||||
afs := &afero.Afero{Fs: i.Fs}
|
||||
content, err := afs.ReadFile(i.Path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
i.Content = string(content)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *FileInfo) detectSubtitles() {
|
||||
if i.Type != "video" {
|
||||
return
|
||||
}
|
||||
|
||||
i.Subtitles = []string{}
|
||||
ext := filepath.Ext(i.Path)
|
||||
|
||||
// TODO: detect multiple languages. Base.Lang.vtt
|
||||
|
||||
path := strings.TrimSuffix(i.Path, ext) + ".vtt"
|
||||
if _, err := i.Fs.Stat(path); err == nil {
|
||||
i.Subtitles = append(i.Subtitles, path)
|
||||
}
|
||||
}
|
||||
|
||||
func (i *FileInfo) readListing(checker rules.Checker) error {
|
||||
afs := &afero.Afero{Fs: i.Fs}
|
||||
dir, err := afs.ReadDir(i.Path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
listing := &Listing{
|
||||
Items: []*FileInfo{},
|
||||
NumDirs: 0,
|
||||
NumFiles: 0,
|
||||
}
|
||||
|
||||
for _, f := range dir {
|
||||
name := f.Name()
|
||||
path := path.Join(i.Path, name)
|
||||
|
||||
if !checker.Check(path) {
|
||||
continue
|
||||
}
|
||||
|
||||
if strings.HasPrefix(f.Mode().String(), "L") {
|
||||
// It's a symbolic link. We try to follow it. If it doesn't work,
|
||||
// we stay with the link information instead if the target's.
|
||||
info, err := i.Fs.Stat(path)
|
||||
if err == nil {
|
||||
f = info
|
||||
}
|
||||
}
|
||||
|
||||
file := &FileInfo{
|
||||
Fs: i.Fs,
|
||||
Name: name,
|
||||
Size: f.Size(),
|
||||
ModTime: f.ModTime(),
|
||||
Mode: f.Mode(),
|
||||
IsDir: f.IsDir(),
|
||||
Extension: filepath.Ext(name),
|
||||
Path: path,
|
||||
}
|
||||
|
||||
if file.IsDir {
|
||||
listing.NumDirs++
|
||||
} else {
|
||||
listing.NumFiles++
|
||||
|
||||
err := file.detectType(true, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
listing.Items = append(listing.Items, file)
|
||||
}
|
||||
|
||||
i.Listing = listing
|
||||
return nil
|
||||
}
|
||||
108
files/listing.go
Normal file
108
files/listing.go
Normal file
@@ -0,0 +1,108 @@
|
||||
package files
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/maruel/natural"
|
||||
)
|
||||
|
||||
// Listing is a collection of files.
|
||||
type Listing struct {
|
||||
Items []*FileInfo `json:"items"`
|
||||
NumDirs int `json:"numDirs"`
|
||||
NumFiles int `json:"numFiles"`
|
||||
Sorting Sorting `json:"sorting"`
|
||||
}
|
||||
|
||||
// ApplySort applies the sort order using .Order and .Sort
|
||||
func (l Listing) ApplySort() {
|
||||
// Check '.Order' to know how to sort
|
||||
if !l.Sorting.Asc {
|
||||
switch l.Sorting.By {
|
||||
case "name":
|
||||
sort.Sort(sort.Reverse(byName(l)))
|
||||
case "size":
|
||||
sort.Sort(sort.Reverse(bySize(l)))
|
||||
case "modified":
|
||||
sort.Sort(sort.Reverse(byModified(l)))
|
||||
default:
|
||||
// If not one of the above, do nothing
|
||||
return
|
||||
}
|
||||
} else { // If we had more Orderings we could add them here
|
||||
switch l.Sorting.By {
|
||||
case "name":
|
||||
sort.Sort(byName(l))
|
||||
case "size":
|
||||
sort.Sort(bySize(l))
|
||||
case "modified":
|
||||
sort.Sort(byModified(l))
|
||||
default:
|
||||
sort.Sort(byName(l))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Implement sorting for Listing
|
||||
type byName Listing
|
||||
type bySize Listing
|
||||
type byModified Listing
|
||||
|
||||
// By Name
|
||||
func (l byName) Len() int {
|
||||
return len(l.Items)
|
||||
}
|
||||
|
||||
func (l byName) Swap(i, j int) {
|
||||
l.Items[i], l.Items[j] = l.Items[j], l.Items[i]
|
||||
}
|
||||
|
||||
// Treat upper and lower case equally
|
||||
func (l byName) Less(i, j int) bool {
|
||||
if l.Items[i].IsDir && !l.Items[j].IsDir {
|
||||
return true
|
||||
}
|
||||
|
||||
if !l.Items[i].IsDir && l.Items[j].IsDir {
|
||||
return false
|
||||
}
|
||||
|
||||
return natural.Less(strings.ToLower(l.Items[j].Name), strings.ToLower(l.Items[i].Name))
|
||||
}
|
||||
|
||||
// By Size
|
||||
func (l bySize) Len() int {
|
||||
return len(l.Items)
|
||||
}
|
||||
|
||||
func (l bySize) Swap(i, j int) {
|
||||
l.Items[i], l.Items[j] = l.Items[j], l.Items[i]
|
||||
}
|
||||
|
||||
const directoryOffset = -1 << 31 // = math.MinInt32
|
||||
func (l bySize) Less(i, j int) bool {
|
||||
iSize, jSize := l.Items[i].Size, l.Items[j].Size
|
||||
if l.Items[i].IsDir {
|
||||
iSize = directoryOffset + iSize
|
||||
}
|
||||
if l.Items[j].IsDir {
|
||||
jSize = directoryOffset + jSize
|
||||
}
|
||||
return iSize < jSize
|
||||
}
|
||||
|
||||
// By Modified
|
||||
func (l byModified) Len() int {
|
||||
return len(l.Items)
|
||||
}
|
||||
|
||||
func (l byModified) Swap(i, j int) {
|
||||
l.Items[i], l.Items[j] = l.Items[j], l.Items[i]
|
||||
}
|
||||
|
||||
func (l byModified) Less(i, j int) bool {
|
||||
iModified, jModified := l.Items[i].ModTime, l.Items[j].ModTime
|
||||
return iModified.Sub(jModified) < 0
|
||||
}
|
||||
7
files/sorting.go
Normal file
7
files/sorting.go
Normal file
@@ -0,0 +1,7 @@
|
||||
package files
|
||||
|
||||
// Sorting contains a sorting order.
|
||||
type Sorting struct {
|
||||
By string `json:"by"`
|
||||
Asc bool `json:"asc"`
|
||||
}
|
||||
46
files/utils.go
Normal file
46
files/utils.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package files
|
||||
|
||||
import (
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
func isBinary(content []byte, n int) bool {
|
||||
maybeStr := string(content)
|
||||
runeCnt := utf8.RuneCount(content)
|
||||
runeIndex := 0
|
||||
gotRuneErrCnt := 0
|
||||
firstRuneErrIndex := -1
|
||||
|
||||
for _, b := range maybeStr {
|
||||
// 8 and below are control chars (e.g. backspace, null, eof, etc)
|
||||
if b <= 8 {
|
||||
return true
|
||||
}
|
||||
|
||||
// 0xFFFD(65533) is the "error" Rune or "Unicode replacement character"
|
||||
// see https://golang.org/pkg/unicode/utf8/#pkg-constants
|
||||
if b == 0xFFFD {
|
||||
//if it is not the last (utf8.UTFMax - x) rune
|
||||
if runeCnt > utf8.UTFMax && runeIndex < runeCnt-utf8.UTFMax {
|
||||
return true
|
||||
} else {
|
||||
//else it is the last (utf8.UTFMax - x) rune
|
||||
//there maybe Vxxx, VVxx, VVVx, thus, we may got max 3 0xFFFD rune (asume V is the byte we got)
|
||||
//for Chinese, it can only be Vxx, VVx, we may got max 2 0xFFFD rune
|
||||
gotRuneErrCnt++
|
||||
|
||||
//mark the first time
|
||||
if firstRuneErrIndex == -1 {
|
||||
firstRuneErrIndex = runeIndex
|
||||
}
|
||||
}
|
||||
}
|
||||
runeIndex++
|
||||
}
|
||||
|
||||
//if last (utf8.UTFMax - x ) rune has the "error" Rune, but not all
|
||||
if firstRuneErrIndex != -1 && gotRuneErrCnt != runeCnt-firstRuneErrIndex {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
39
fileutils/copy.go
Normal file
39
fileutils/copy.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package fileutils
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
// Copy copies a file or folder from one place to another.
|
||||
func Copy(fs afero.Fs, src, dst string) error {
|
||||
if src = path.Clean("/" + src); src == "" {
|
||||
return os.ErrNotExist
|
||||
}
|
||||
|
||||
if dst = path.Clean("/" + dst); dst == "" {
|
||||
return os.ErrNotExist
|
||||
}
|
||||
|
||||
if src == "/" || dst == "/" {
|
||||
// Prohibit copying from or to the virtual root directory.
|
||||
return os.ErrInvalid
|
||||
}
|
||||
|
||||
if dst == src {
|
||||
return os.ErrInvalid
|
||||
}
|
||||
|
||||
info, err := fs.Stat(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if info.IsDir() {
|
||||
return CopyDir(fs, src, dst)
|
||||
}
|
||||
|
||||
return CopyFile(fs, src, dst)
|
||||
}
|
||||
62
fileutils/dir.go
Normal file
62
fileutils/dir.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package fileutils
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
// CopyDir copies a directory from source to dest and all
|
||||
// of its sub-directories. It doesn't stop if it finds an error
|
||||
// during the copy. Returns an error if any.
|
||||
func CopyDir(fs afero.Fs, source string, dest string) error {
|
||||
// Get properties of source.
|
||||
srcinfo, err := fs.Stat(source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Create the destination directory.
|
||||
err = fs.MkdirAll(dest, srcinfo.Mode())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dir, _ := fs.Open(source)
|
||||
obs, err := dir.Readdir(-1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var errs []error
|
||||
|
||||
for _, obj := range obs {
|
||||
fsource := source + "/" + obj.Name()
|
||||
fdest := dest + "/" + obj.Name()
|
||||
|
||||
if obj.IsDir() {
|
||||
// Create sub-directories, recursively.
|
||||
err = CopyDir(fs, fsource, fdest)
|
||||
if err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
} else {
|
||||
// Perform the file copy.
|
||||
err = CopyFile(fs, fsource, fdest)
|
||||
if err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var errString string
|
||||
for _, err := range errs {
|
||||
errString += err.Error() + "\n"
|
||||
}
|
||||
|
||||
if errString != "" {
|
||||
return errors.New(errString)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
51
fileutils/file.go
Normal file
51
fileutils/file.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package fileutils
|
||||
|
||||
import (
|
||||
"io"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
// CopyFile copies a file from source to dest and returns
|
||||
// an error if any.
|
||||
func CopyFile(fs afero.Fs, source string, dest string) error {
|
||||
// Open the source file.
|
||||
src, err := fs.Open(source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
// Makes the directory needed to create the dst
|
||||
// file.
|
||||
err = fs.MkdirAll(filepath.Dir(dest), 0666)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Create the destination file.
|
||||
dst, err := fs.Create(dest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer dst.Close()
|
||||
|
||||
// Copy the contents of the file.
|
||||
_, err = io.Copy(dst, src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Copy the mode if the user can't
|
||||
// open the file.
|
||||
info, err := fs.Stat(source)
|
||||
if err != nil {
|
||||
err = fs.Chmod(dest, info.Mode())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
1
frontend
Submodule
1
frontend
Submodule
Submodule frontend added at ead7fb4233
42
go.mod
Normal file
42
go.mod
Normal file
@@ -0,0 +1,42 @@
|
||||
module github.com/filebrowser/filebrowser/v2
|
||||
|
||||
require (
|
||||
github.com/DataDog/zstd v1.4.0 // indirect
|
||||
github.com/GeertJohan/go.rice v1.0.0
|
||||
github.com/Sereal/Sereal v0.0.0-20190430203904-6faf9605eb56 // indirect
|
||||
github.com/asdine/storm v2.1.2+incompatible
|
||||
github.com/daaku/go.zipexe v1.0.1 // indirect
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible
|
||||
github.com/dsnet/compress v0.0.1 // indirect
|
||||
github.com/golang/protobuf v1.3.1 // indirect
|
||||
github.com/golang/snappy v0.0.1 // indirect
|
||||
github.com/gorilla/mux v1.7.1
|
||||
github.com/gorilla/websocket v1.4.0
|
||||
github.com/hacdias/fileutils v0.0.0-20181202104838-227b317161a1
|
||||
github.com/inconshreveable/mousetrap v1.0.0 // indirect
|
||||
github.com/kr/pretty v0.1.0 // indirect
|
||||
github.com/magiconair/properties v1.8.1 // indirect
|
||||
github.com/maruel/natural v0.0.0-20180416170133-dbcb3e2e8cf1
|
||||
github.com/mholt/archiver v3.1.1+incompatible
|
||||
github.com/mholt/caddy v1.0.0
|
||||
github.com/mitchellh/go-homedir v1.1.0
|
||||
github.com/nwaples/rardecode v1.0.0 // indirect
|
||||
github.com/pelletier/go-toml v1.4.0
|
||||
github.com/pierrec/lz4 v0.0.0-20190131084431-473cd7ce01a1 // indirect
|
||||
github.com/spf13/afero v1.2.2
|
||||
github.com/spf13/cobra v0.0.3
|
||||
github.com/spf13/jwalterweatherman v1.1.0 // indirect
|
||||
github.com/spf13/pflag v1.0.3
|
||||
github.com/spf13/viper v1.3.2
|
||||
github.com/vmihailenco/msgpack v4.0.4+incompatible // indirect
|
||||
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 // indirect
|
||||
go.etcd.io/bbolt v1.3.2
|
||||
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529
|
||||
golang.org/x/net v0.0.0-20190509222800-a4d6f7feada5 // indirect
|
||||
golang.org/x/sys v0.0.0-20190509141414-a5b02f93d862 // indirect
|
||||
golang.org/x/text v0.3.2 // indirect
|
||||
google.golang.org/appengine v1.5.0 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0
|
||||
gopkg.in/yaml.v2 v2.2.2
|
||||
)
|
||||
196
go.sum
Normal file
196
go.sum
Normal file
@@ -0,0 +1,196 @@
|
||||
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/DataDog/zstd v1.4.0 h1:vhoV+DUHnRZdKW1i5UMjAk2G4JY8wN4ayRfYDNdEhwo=
|
||||
github.com/DataDog/zstd v1.4.0/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo=
|
||||
github.com/GeertJohan/go.incremental v1.0.0 h1:7AH+pY1XUgQE4Y1HcXYaMqAI0m9yrFqo/jt0CW30vsg=
|
||||
github.com/GeertJohan/go.incremental v1.0.0/go.mod h1:6fAjUhbVuX1KcMD3c8TEgVUqmo4seqhv0i0kdATSkM0=
|
||||
github.com/GeertJohan/go.rice v1.0.0 h1:KkI6O9uMaQU3VEKaj01ulavtF7o1fWT7+pk/4voiMLQ=
|
||||
github.com/GeertJohan/go.rice v1.0.0/go.mod h1:eH6gbSOAUv07dQuZVnBmoDP8mgsM1rtixis4Tib9if0=
|
||||
github.com/Sereal/Sereal v0.0.0-20190430203904-6faf9605eb56 h1:3trCIB5GsAOIY8NxlfMztCYIhVsW9V5sZ+brsecjaiI=
|
||||
github.com/Sereal/Sereal v0.0.0-20190430203904-6faf9605eb56/go.mod h1:D0JMgToj/WdxCgd30Kc1UcA9E+WdZoJqeVOuYW7iTBM=
|
||||
github.com/akavel/rsrc v0.8.0 h1:zjWn7ukO9Kc5Q62DOJCcxGpXC18RawVtYAGdz2aLlfw=
|
||||
github.com/akavel/rsrc v0.8.0/go.mod h1:uLoCtb9J+EyAqh+26kdrTgmzRBFPGOolLWKpdxkKq+c=
|
||||
github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
|
||||
github.com/asdine/storm v2.1.2+incompatible h1:dczuIkyqwY2LrtXPz8ixMrU/OFgZp71kbKTHGrXYt/Q=
|
||||
github.com/asdine/storm v2.1.2+incompatible/go.mod h1:RarYDc9hq1UPLImuiXK3BIWPJLdIygvV3PsInK0FbVQ=
|
||||
github.com/bifurcation/mint v0.0.0-20180715133206-93c51c6ce115/go.mod h1:zVt7zX3K/aDCk9Tj+VM7YymsX66ERvzCJzw8rFCX2JU=
|
||||
github.com/cenkalti/backoff v2.1.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM=
|
||||
github.com/cheekybits/genny v0.0.0-20170328200008-9127e812e1e9/go.mod h1:+tQajlRqAUrPI7DOSpB0XAqZYtQakVtB7wXkRAgjxjQ=
|
||||
github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
|
||||
github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk=
|
||||
github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
|
||||
github.com/daaku/go.zipexe v1.0.0/go.mod h1:z8IiR6TsVLEYKwXAoE/I+8ys/sDkgTzSL0CLnGVd57E=
|
||||
github.com/daaku/go.zipexe v1.0.1 h1:wV4zMsDOI2SZ2m7Tdz1Ps96Zrx+TzaK15VbUaGozw0M=
|
||||
github.com/daaku/go.zipexe v1.0.1/go.mod h1:5xWogtqlYnfBXkSB1o9xysukNP9GTvaNkqzUZbt3Bw8=
|
||||
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/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
|
||||
github.com/dsnet/compress v0.0.1 h1:PlZu0n3Tuv04TzpfPbrnI0HW/YwodEXDS+oPKahKF0Q=
|
||||
github.com/dsnet/compress v0.0.1/go.mod h1:Aw8dCMJ7RioblQeTqt88akK31OvO8Dhf5JflhBbQEHo=
|
||||
github.com/dsnet/golib v0.0.0-20171103203638-1ea166775780/go.mod h1:Lj+Z9rebOhdfkVLjJ8T6VcRQv3SXugXy999NBtR9aFY=
|
||||
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
|
||||
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 h1:BHsljHzVlRcyQhjrss6TZTdY2VfCqZPbv5k3iBFa2ZQ=
|
||||
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc=
|
||||
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/go-acme/lego v2.5.0+incompatible/go.mod h1:yzMNe9CasVUhkquNvti5nAtPmG94USbYxYrZfTkIn0M=
|
||||
github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
|
||||
github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg=
|
||||
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
|
||||
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
|
||||
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/mux v1.7.1 h1:Dw4jY2nghMMRsh1ol8dv1axHkDwMQK2DHerMNJsIpJU=
|
||||
github.com/gorilla/mux v1.7.1/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
|
||||
github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q=
|
||||
github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
|
||||
github.com/hacdias/fileutils v0.0.0-20181202104838-227b317161a1 h1:2MkEawJQTmAr6YI7T7j7SKxdTmYJOcaJZfzeVPr56PM=
|
||||
github.com/hacdias/fileutils v0.0.0-20181202104838-227b317161a1/go.mod h1:lwnswzFVSy7B/k81M5rOLUU0fOBKHrDRIkPIBZd7PBo=
|
||||
github.com/hashicorp/go-syslog v1.0.0 h1:KaodqZuhUoZereWVIYmpUgZysurB1kBLX2j0MwMrUAE=
|
||||
github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4=
|
||||
github.com/hashicorp/golang-lru v0.0.0-20180201235237-0fb14efe8c47/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
|
||||
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
|
||||
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
|
||||
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
|
||||
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
|
||||
github.com/jessevdk/go-flags v1.4.0 h1:4IU2WS7AumrZ/40jfhf4QVDMsQwqA7VEHozFRrGARJA=
|
||||
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
|
||||
github.com/jimstudt/http-authentication v0.0.0-20140401203705-3eca13d6893a/go.mod h1:wK6yTYYcgjHE1Z1QtXACPDjcFJyBskHEdagmnq3vsP8=
|
||||
github.com/klauspost/compress v1.4.1/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
|
||||
github.com/klauspost/cpuid v1.2.0/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek=
|
||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k=
|
||||
github.com/lucas-clemente/aes12 v0.0.0-20171027163421-cd47fb39b79f/go.mod h1:JpH9J1c9oX6otFSgdUHwUBUizmKlrMjxWnIAjff4m04=
|
||||
github.com/lucas-clemente/quic-clients v0.1.0/go.mod h1:y5xVIEoObKqULIKivu+gD/LU90pL73bTdtQjPBvtCBk=
|
||||
github.com/lucas-clemente/quic-go v0.10.2/go.mod h1:hvaRS9IHjFLMq76puFJeWNfmn+H70QZ/CXoxqw9bzao=
|
||||
github.com/lucas-clemente/quic-go-certificates v0.0.0-20160823095156-d2f86524cced/go.mod h1:NCcRLrOTZbzhZvixZLlERbJtDtYsmMw8Jc4vS8Z0g58=
|
||||
github.com/magiconair/properties v1.8.0 h1:LLgXmsheXeRoUOBOjtwPQCWIYqM/LU1ayDtDePerRcY=
|
||||
github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
|
||||
github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4=
|
||||
github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
|
||||
github.com/marten-seemann/qtls v0.2.3 h1:0yWJ43C62LsZt08vuQJDK1uC1czUc3FJeCLPoNAI4vA=
|
||||
github.com/marten-seemann/qtls v0.2.3/go.mod h1:xzjG7avBwGGbdZ8dTGxlBnLArsVKLvwmjgmPuiQEcYk=
|
||||
github.com/maruel/natural v0.0.0-20180416170133-dbcb3e2e8cf1 h1:PEhRT94KBTY4E0KdCYmhvDGWjSFBxc68j2M6PMRix8U=
|
||||
github.com/maruel/natural v0.0.0-20180416170133-dbcb3e2e8cf1/go.mod h1:wI697HNhDFM/vBruYM3ckbszQ2+DOIeH9qdBKMdf288=
|
||||
github.com/mholt/archiver v3.1.1+incompatible h1:1dCVxuqs0dJseYEhi5pl7MYPH9zDa1wBi7mF09cbNkU=
|
||||
github.com/mholt/archiver v3.1.1+incompatible/go.mod h1:Dh2dOXnSdiLxRiPoVfIr/fI1TwETms9B8CTWfeh7ROU=
|
||||
github.com/mholt/caddy v1.0.0 h1:KI6RPGih2GFzWRPG8s9clKK28Ns4ZlVMKR/v7mxq6+c=
|
||||
github.com/mholt/caddy v1.0.0/go.mod h1:PzUpQ3yGCTuEuy0KSxEeB4TZOi3zBZ8BR/zY0RBP414=
|
||||
github.com/mholt/certmagic v0.5.0/go.mod h1:g4cOPxcjV0oFq3qwpjSA30LReKD8AoIfwAY9VvG35NY=
|
||||
github.com/miekg/dns v1.1.3/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
|
||||
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
|
||||
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
|
||||
github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
|
||||
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
|
||||
github.com/naoina/go-stringutil v0.1.0/go.mod h1:XJ2SJL9jCtBh+P9q5btrd/Ylo8XwT/h1USek5+NqSA0=
|
||||
github.com/naoina/toml v0.1.1/go.mod h1:NBIhNtsFMo3G2szEBne+bO4gS192HuIYRqfvOWb4i1E=
|
||||
github.com/nkovacs/streamquote v0.0.0-20170412213628-49af9bddb229 h1:E2B8qYyeSgv5MXpmzZXRNp8IAQ4vjxIjhpAf5hv/tAg=
|
||||
github.com/nkovacs/streamquote v0.0.0-20170412213628-49af9bddb229/go.mod h1:0aYXnNPJ8l7uZxf45rWW1a/uME32OF0rhiYGNQ2oF2E=
|
||||
github.com/nwaples/rardecode v1.0.0 h1:r7vGuS5akxOnR4JQSkko62RJ1ReCMXxQRPtxsiFMBOs=
|
||||
github.com/nwaples/rardecode v1.0.0/go.mod h1:5DzqNKiOdpKKBH87u8VlvAnPZMXcGRhxWkRpHbbfGS0=
|
||||
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/ginkgo v1.8.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
|
||||
github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc=
|
||||
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
|
||||
github.com/pelletier/go-toml v1.4.0 h1:u3Z1r+oOXJIkxqw34zVhyPgjBsm6X2wn21NWs/HfSeg=
|
||||
github.com/pelletier/go-toml v1.4.0/go.mod h1:PN7xzY2wHTK0K9p34ErDQMlFxa51Fk0OUruD3k1mMwo=
|
||||
github.com/pierrec/lz4 v0.0.0-20190131084431-473cd7ce01a1 h1:0utzB5Mn6QyMzIeOn+oD7pjKQLjJwfM9bz6TkPPdxcw=
|
||||
github.com/pierrec/lz4 v0.0.0-20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc=
|
||||
github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/russross/blackfriday v0.0.0-20170610170232-067529f716f4/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
|
||||
github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI=
|
||||
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
|
||||
github.com/spf13/afero v1.2.2 h1:5jhuqJyZCZf2JRofRvN/nIFgIWNzPa3/Vz8mYylgbWc=
|
||||
github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk=
|
||||
github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8=
|
||||
github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
|
||||
github.com/spf13/cobra v0.0.3 h1:ZlrZ4XsMRm04Fr5pSFxBgfND2EBVa1nLpiy1stUsX/8=
|
||||
github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
|
||||
github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk=
|
||||
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
|
||||
github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk=
|
||||
github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo=
|
||||
github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
|
||||
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
|
||||
github.com/spf13/viper v1.3.2 h1:VUFqw5KcqRf7i70GOzW7N+Q7+gxVBkSSqiXB12+JQ4M=
|
||||
github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0=
|
||||
github.com/ulikunitz/xz v0.5.6 h1:jGHAfXawEGZQ3blwU5wnWKQJvAraT7Ftq9EXjnXYgt8=
|
||||
github.com/ulikunitz/xz v0.5.6/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasttemplate v1.0.1 h1:tY9CJiPnMXf1ERmG2EyK7gNUd+c6RKGD0IfU8WdUSz8=
|
||||
github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8=
|
||||
github.com/vmihailenco/msgpack v4.0.4+incompatible h1:dSLoQfGFAo3F6OoNhwUmLwVgaUXK79GlxNBwueZn0xI=
|
||||
github.com/vmihailenco/msgpack v4.0.4+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk=
|
||||
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 h1:nIPpBwaJSVYIxUFsDv3M8ofmx9yWTog9BfvIu0q41lo=
|
||||
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8/go.mod h1:HUYIGzjTL3rfEspMxjDjgmT5uz5wzYJKVo23qUhYTos=
|
||||
github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=
|
||||
go.etcd.io/bbolt v1.3.2 h1:Z/90sZLPOeCy2PwprqkFa25PdkusRzaj9P8zm/KNyvk=
|
||||
go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
|
||||
golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9 h1:mKdxBk7AujPs8kU4m80U72y/zjbZ3UcXC7dClwKbUI0=
|
||||
golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/crypto v0.0.0-20190123085648-057139ce5d2b/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/crypto v0.0.0-20190228161510-8dd112bcdc25 h1:jsG6UpNLt9iAsb0S2AGW28DveNzzgmbXR+ENoPjUeIU=
|
||||
golang.org/x/crypto v0.0.0-20190228161510-8dd112bcdc25/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529 h1:iMGN4xG0cnqj3t+zOM8wUB0BiPKHEwSxEZCvzcbZuvk=
|
||||
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/net v0.0.0-20180724234803-3673e40ba225 h1:kNX+jCowfMYzvlSvJu5pQWEmyWFrBXJ3PBy10xKMXK8=
|
||||
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd h1:nTDtHvHSdCn1m6ITfMRqtOd/9+7a3s8RBNOZ3eYZzJA=
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190328230028-74de082e2cca/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190509222800-a4d6f7feada5 h1:6M3SDHlHHDCx2PcQw3S4KsR170vGqDhJDOmpVd4Hjak=
|
||||
golang.org/x/net v0.0.0-20190509222800-a4d6f7feada5/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a h1:1n5lsVfiQW3yfsRGu98756EH1YthsFqr/5mxHduZW2A=
|
||||
golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190124100055-b90733256f2e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190228124157-a34e9553db1e h1:ZytStCyV048ZqDsWHiYDdoI2Vd4msMcrDECFxS+tL9c=
|
||||
golang.org/x/sys v0.0.0-20190228124157-a34e9553db1e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190509141414-a5b02f93d862 h1:rM0ROo5vb9AdYJi1110yjWGMej9ITfKddS89P3Fkhug=
|
||||
golang.org/x/sys v0.0.0-20190509141414-a5b02f93d862/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
google.golang.org/appengine v1.5.0 h1:KxkO13IPW4Lslp2bz+KHP2E3gtFlrIGNThxkZQ3g+4c=
|
||||
google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||
gopkg.in/mcuadros/go-syslog.v2 v2.2.1/go.mod h1:l5LPIyOOyIdQquNg+oU6Z3524YwrcqEm0aKH+5zpt2U=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k=
|
||||
gopkg.in/square/go-jose.v2 v2.2.2/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
296
http/auth.go
296
http/auth.go
@@ -3,150 +3,34 @@ package http
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
jwt "github.com/dgrijalva/jwt-go"
|
||||
"github.com/dgrijalva/jwt-go/request"
|
||||
fm "github.com/filebrowser/filebrowser"
|
||||
"github.com/filebrowser/filebrowser/v2/errors"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
const reCaptchaAPI = "/recaptcha/api/siteverify"
|
||||
|
||||
type cred struct {
|
||||
Password string `json:"password"`
|
||||
Username string `json:"username"`
|
||||
ReCaptcha string `json:"recaptcha"`
|
||||
type userInfo struct {
|
||||
ID uint `json:"id"`
|
||||
Locale string `json:"locale"`
|
||||
ViewMode users.ViewMode `json:"viewMode"`
|
||||
Perm users.Permissions `json:"perm"`
|
||||
Commands []string `json:"commands"`
|
||||
LockPassword bool `json:"lockPassword"`
|
||||
}
|
||||
|
||||
// reCaptcha checks the reCaptcha code.
|
||||
func reCaptcha(host, secret, response string) (bool, error) {
|
||||
body := url.Values{}
|
||||
body.Set("secret", secret)
|
||||
body.Add("response", response)
|
||||
|
||||
client := &http.Client{}
|
||||
|
||||
resp, err := client.Post(host+reCaptchaAPI, "application/x-www-form-urlencoded", strings.NewReader(body.Encode()))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
var data struct {
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
err = json.NewDecoder(resp.Body).Decode(&data)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return data.Success, nil
|
||||
}
|
||||
|
||||
// authHandler processes the authentication for the user.
|
||||
func authHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
// NoAuth instances shouldn't call this method.
|
||||
if c.NoAuth {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// Receive the credentials from the request and unmarshal them.
|
||||
var cred cred
|
||||
if r.Body == nil {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
err := json.NewDecoder(r.Body).Decode(&cred)
|
||||
if err != nil {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
// If ReCaptcha is enabled, check the code.
|
||||
if len(c.ReCaptchaSecret) > 0 {
|
||||
ok, err := reCaptcha(c.ReCaptchaHost, c.ReCaptchaSecret, cred.ReCaptcha)
|
||||
if err != nil {
|
||||
return http.StatusForbidden, err
|
||||
}
|
||||
|
||||
if !ok {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Checks if the user exists.
|
||||
u, err := c.Store.Users.GetByUsername(cred.Username, c.NewFS)
|
||||
if err != nil {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
// Checks if the password is correct.
|
||||
if !fm.CheckPasswordHash(cred.Password, u.Password) {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
c.User = u
|
||||
return printToken(c, w)
|
||||
}
|
||||
|
||||
// renewAuthHandler is used when the front-end already has a JWT token
|
||||
// and is checking if it is up to date. If so, updates its info.
|
||||
func renewAuthHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
ok, u := validateAuth(c, r)
|
||||
if !ok {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
c.User = u
|
||||
return printToken(c, w)
|
||||
}
|
||||
|
||||
// claims is the JWT claims.
|
||||
type claims struct {
|
||||
fm.User
|
||||
type authToken struct {
|
||||
User userInfo `json:"user"`
|
||||
jwt.StandardClaims
|
||||
}
|
||||
|
||||
// printToken prints the final JWT token to the user.
|
||||
func printToken(c *fm.Context, w http.ResponseWriter) (int, error) {
|
||||
// Creates a copy of the user and removes it password
|
||||
// hash so it never arrives to the user.
|
||||
u := fm.User{}
|
||||
u = *c.User
|
||||
u.Password = ""
|
||||
|
||||
// Builds the claims.
|
||||
claims := claims{
|
||||
u,
|
||||
jwt.StandardClaims{
|
||||
ExpiresAt: time.Now().Add(time.Hour * 24).Unix(),
|
||||
Issuer: "File Manager",
|
||||
},
|
||||
}
|
||||
|
||||
// Creates the token and signs it.
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
signed, err := token.SignedString(c.Key)
|
||||
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
// Writes the token.
|
||||
w.Header().Set("Content-Type", "cty")
|
||||
w.Write([]byte(signed))
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
type extractor []string
|
||||
|
||||
func (e extractor) ExtractToken(r *http.Request) (string, error) {
|
||||
token, _ := request.AuthorizationHeaderExtractor.ExtractToken(r)
|
||||
token, _ := request.HeaderExtractor{"X-Auth"}.ExtractToken(r)
|
||||
|
||||
// Checks if the token isn't empty and if it contains two dots.
|
||||
// The former prevents incompatibility with URLs that previously
|
||||
@@ -155,42 +39,142 @@ func (e extractor) ExtractToken(r *http.Request) (string, error) {
|
||||
return token, nil
|
||||
}
|
||||
|
||||
cookie, err := r.Cookie("auth")
|
||||
if err != nil {
|
||||
auth := r.URL.Query().Get("auth")
|
||||
if auth == "" {
|
||||
return "", request.ErrNoTokenInRequest
|
||||
}
|
||||
|
||||
return cookie.Value, nil
|
||||
return auth, nil
|
||||
}
|
||||
|
||||
// validateAuth is used to validate the authentication and returns the
|
||||
// User if it is valid.
|
||||
func validateAuth(c *fm.Context, r *http.Request) (bool, *fm.User) {
|
||||
if c.NoAuth {
|
||||
c.User = c.DefaultUser
|
||||
return true, c.User
|
||||
func withUser(fn handleFunc) handleFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
keyFunc := func(token *jwt.Token) (interface{}, error) {
|
||||
return d.settings.Key, nil
|
||||
}
|
||||
|
||||
var tk authToken
|
||||
token, err := request.ParseFromRequestWithClaims(r, &extractor{}, &tk, keyFunc)
|
||||
|
||||
if err != nil || !token.Valid {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
expired := !tk.VerifyExpiresAt(time.Now().Add(time.Hour).Unix(), true)
|
||||
updated := d.store.Users.LastUpdate(tk.User.ID) > tk.IssuedAt
|
||||
|
||||
if expired || updated {
|
||||
w.Header().Add("X-Renew-Token", "true")
|
||||
}
|
||||
|
||||
d.user, err = d.store.Users.Get(d.server.Root, tk.User.ID)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
return fn(w, r, d)
|
||||
}
|
||||
}
|
||||
|
||||
keyFunc := func(token *jwt.Token) (interface{}, error) {
|
||||
return c.Key, nil
|
||||
}
|
||||
func withAdmin(fn handleFunc) handleFunc {
|
||||
return withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
if !d.user.Perm.Admin {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
var claims claims
|
||||
token, err := request.ParseFromRequestWithClaims(r,
|
||||
extractor{},
|
||||
&claims,
|
||||
keyFunc,
|
||||
)
|
||||
return fn(w, r, d)
|
||||
})
|
||||
}
|
||||
|
||||
if err != nil || !token.Valid {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
u, err := c.Store.Users.Get(claims.User.ID, c.NewFS)
|
||||
var loginHandler = func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
auther, err := d.store.Auth.Get(d.settings.AuthMethod)
|
||||
if err != nil {
|
||||
return false, nil
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
c.User = u
|
||||
return true, u
|
||||
user, err := auther.Auth(r, d.store.Users, d.server.Root)
|
||||
if err == os.ErrPermission {
|
||||
return http.StatusForbidden, nil
|
||||
} else if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
} else {
|
||||
return printToken(w, r, d, user)
|
||||
}
|
||||
}
|
||||
|
||||
type signupBody struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
var signupHandler = func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
if !d.settings.Signup {
|
||||
return http.StatusMethodNotAllowed, nil
|
||||
}
|
||||
|
||||
if r.Body == nil {
|
||||
return http.StatusBadRequest, nil
|
||||
}
|
||||
|
||||
info := &signupBody{}
|
||||
err := json.NewDecoder(r.Body).Decode(info)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, err
|
||||
}
|
||||
|
||||
if info.Password == "" || info.Username == "" {
|
||||
return http.StatusBadRequest, nil
|
||||
}
|
||||
|
||||
user := &users.User{
|
||||
Username: info.Username,
|
||||
}
|
||||
|
||||
d.settings.Defaults.Apply(user)
|
||||
|
||||
pwd, err := users.HashPwd(info.Password)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
user.Password = pwd
|
||||
err = d.store.Users.Save(user)
|
||||
if err == errors.ErrExist {
|
||||
return http.StatusConflict, err
|
||||
} else if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
return http.StatusOK, nil
|
||||
}
|
||||
|
||||
var renewHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
return printToken(w, r, d, d.user)
|
||||
})
|
||||
|
||||
func printToken(w http.ResponseWriter, r *http.Request, d *data, user *users.User) (int, error) {
|
||||
claims := &authToken{
|
||||
User: userInfo{
|
||||
ID: user.ID,
|
||||
Locale: user.Locale,
|
||||
ViewMode: user.ViewMode,
|
||||
Perm: user.Perm,
|
||||
LockPassword: user.LockPassword,
|
||||
Commands: user.Commands,
|
||||
},
|
||||
StandardClaims: jwt.StandardClaims{
|
||||
IssuedAt: time.Now().Unix(),
|
||||
ExpiresAt: time.Now().Add(time.Hour * 2).Unix(),
|
||||
Issuer: "File Browser",
|
||||
},
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
signed, err := token.SignedString(d.settings.Key)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "cty")
|
||||
w.Write([]byte(signed))
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
104
http/commands.go
Normal file
104
http/commands.go
Normal file
@@ -0,0 +1,104 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/runner"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
}
|
||||
|
||||
var (
|
||||
cmdNotAllowed = []byte("Command not allowed.")
|
||||
)
|
||||
|
||||
func wsErr(ws *websocket.Conn, r *http.Request, status int, err error) {
|
||||
txt := http.StatusText(status)
|
||||
if err != nil || status >= 400 {
|
||||
log.Printf("%s: %v %s %v", r.URL.Path, status, r.RemoteAddr, err)
|
||||
}
|
||||
ws.WriteControl(websocket.CloseInternalServerErr, []byte(txt), time.Now().Add(10*time.Second))
|
||||
}
|
||||
|
||||
var commandsHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
var raw string
|
||||
|
||||
for {
|
||||
_, msg, err := conn.ReadMessage()
|
||||
if err != nil {
|
||||
wsErr(conn, r, http.StatusInternalServerError, err)
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
raw = strings.TrimSpace(string(msg))
|
||||
if raw != "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !d.user.CanExecute(strings.Split(raw, " ")[0]) {
|
||||
err := conn.WriteMessage(websocket.TextMessage, cmdNotAllowed)
|
||||
if err != nil {
|
||||
wsErr(conn, r, http.StatusInternalServerError, err)
|
||||
}
|
||||
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
command, err := runner.ParseCommand(d.settings, raw)
|
||||
if err != nil {
|
||||
err := conn.WriteMessage(websocket.TextMessage, []byte(err.Error()))
|
||||
if err != nil {
|
||||
wsErr(conn, r, http.StatusInternalServerError, err)
|
||||
}
|
||||
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
cmd := exec.Command(command[0], command[1:]...)
|
||||
cmd.Dir = d.user.FullPath(r.URL.Path)
|
||||
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
wsErr(conn, r, http.StatusInternalServerError, err)
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
stderr, err := cmd.StderrPipe()
|
||||
if err != nil {
|
||||
wsErr(conn, r, http.StatusInternalServerError, err)
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
wsErr(conn, r, http.StatusInternalServerError, err)
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
s := bufio.NewScanner(io.MultiReader(stdout, stderr))
|
||||
for s.Scan() {
|
||||
conn.WriteMessage(websocket.TextMessage, s.Bytes())
|
||||
}
|
||||
|
||||
if err := cmd.Wait(); err != nil {
|
||||
wsErr(conn, r, http.StatusInternalServerError, err)
|
||||
}
|
||||
|
||||
return 0, nil
|
||||
})
|
||||
68
http/data.go
Normal file
68
http/data.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/runner"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/storage"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
type handleFunc func(w http.ResponseWriter, r *http.Request, d *data) (int, error)
|
||||
|
||||
type data struct {
|
||||
*runner.Runner
|
||||
settings *settings.Settings
|
||||
server *settings.Server
|
||||
store *storage.Storage
|
||||
user *users.User
|
||||
raw interface{}
|
||||
}
|
||||
|
||||
// Check implements rules.Checker.
|
||||
func (d *data) Check(path string) bool {
|
||||
for _, rule := range d.user.Rules {
|
||||
if rule.Matches(path) {
|
||||
return rule.Allow
|
||||
}
|
||||
}
|
||||
|
||||
for _, rule := range d.settings.Rules {
|
||||
if rule.Matches(path) {
|
||||
return rule.Allow
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func handle(fn handleFunc, prefix string, storage *storage.Storage, server *settings.Server) http.Handler {
|
||||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
settings, err := storage.Settings.Get()
|
||||
if err != nil {
|
||||
log.Fatalln("ERROR: couldn't get settings")
|
||||
return
|
||||
}
|
||||
|
||||
status, err := fn(w, r, &data{
|
||||
Runner: &runner.Runner{Settings: settings},
|
||||
store: storage,
|
||||
settings: settings,
|
||||
server: server,
|
||||
})
|
||||
|
||||
if status != 0 {
|
||||
txt := http.StatusText(status)
|
||||
http.Error(w, strconv.Itoa(status)+" "+txt, status)
|
||||
}
|
||||
|
||||
if status >= 400 || err != nil {
|
||||
log.Printf("%s: %v %s %v", r.URL.Path, status, r.RemoteAddr, err)
|
||||
}
|
||||
})
|
||||
|
||||
return http.StripPrefix(prefix, handler)
|
||||
}
|
||||
103
http/download.go
103
http/download.go
@@ -1,103 +0,0 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
fm "github.com/filebrowser/filebrowser"
|
||||
"github.com/hacdias/fileutils"
|
||||
"github.com/mholt/archiver"
|
||||
)
|
||||
|
||||
// downloadHandler creates an archive in one of the supported formats (zip, tar,
|
||||
// tar.gz or tar.bz2) and sends it to be downloaded.
|
||||
func downloadHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
// If the file isn't a directory, serve it using http.ServeFile. We display it
|
||||
// inline if it is requested.
|
||||
if !c.File.IsDir {
|
||||
return downloadFileHandler(c, w, r)
|
||||
}
|
||||
|
||||
query := r.URL.Query().Get("format")
|
||||
files := []string{}
|
||||
names := strings.Split(r.URL.Query().Get("files"), ",")
|
||||
|
||||
// If there are files in the query, sanitize their names.
|
||||
// Otherwise, just append the current path.
|
||||
if len(names) != 0 {
|
||||
for _, name := range names {
|
||||
// Unescape the name.
|
||||
name, err := url.QueryUnescape(name)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
// Clean the slashes.
|
||||
name = fileutils.SlashClean(name)
|
||||
files = append(files, filepath.Join(c.File.Path, name))
|
||||
}
|
||||
} else {
|
||||
files = append(files, c.File.Path)
|
||||
}
|
||||
|
||||
var (
|
||||
extension string
|
||||
ar archiver.Archiver
|
||||
)
|
||||
|
||||
switch query {
|
||||
// If the format is true, just set it to "zip".
|
||||
case "zip", "true", "":
|
||||
extension, ar = ".zip", archiver.Zip
|
||||
case "tar":
|
||||
extension, ar = ".tar", archiver.Tar
|
||||
case "targz":
|
||||
extension, ar = ".tar.gz", archiver.TarGz
|
||||
case "tarbz2":
|
||||
extension, ar = ".tar.bz2", archiver.TarBz2
|
||||
case "tarxz":
|
||||
extension, ar = ".tar.xz", archiver.TarXZ
|
||||
default:
|
||||
return http.StatusNotImplemented, nil
|
||||
}
|
||||
|
||||
// Defines the file name.
|
||||
name := c.File.Name
|
||||
if name == "." || name == "" {
|
||||
name = "archive"
|
||||
}
|
||||
name += extension
|
||||
|
||||
w.Header().Set("Content-Disposition", "attachment; filename*=utf-8''"+url.PathEscape(name))
|
||||
err := ar.Write(w, files)
|
||||
|
||||
return 0, err
|
||||
}
|
||||
|
||||
func downloadFileHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
file, err := os.Open(c.File.Path)
|
||||
defer file.Close()
|
||||
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
stat, err := file.Stat()
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
if r.URL.Query().Get("inline") == "true" {
|
||||
w.Header().Set("Content-Disposition", "inline")
|
||||
} else {
|
||||
// As per RFC6266 section 4.3
|
||||
w.Header().Set("Content-Disposition", "attachment; filename*=utf-8''"+url.PathEscape(c.File.Name))
|
||||
}
|
||||
|
||||
http.ServeContent(w, r, stat.Name(), stat.ModTime(), file)
|
||||
|
||||
return 0, nil
|
||||
}
|
||||
371
http/http.go
371
http/http.go
@@ -1,344 +1,69 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"html/template"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
fm "github.com/filebrowser/filebrowser"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/storage"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
// Handler returns a function compatible with http.HandleFunc.
|
||||
func Handler(m *fm.FileBrowser) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
code, err := serve(&fm.Context{
|
||||
FileBrowser: m,
|
||||
User: nil,
|
||||
File: nil,
|
||||
}, w, r)
|
||||
|
||||
if code >= 400 {
|
||||
w.WriteHeader(code)
|
||||
|
||||
txt := http.StatusText(code)
|
||||
log.Printf("%v: %v %v\n", r.URL.Path, code, txt)
|
||||
w.Write([]byte(txt + "\n"))
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
log.Print(err)
|
||||
}
|
||||
})
|
||||
type modifyRequest struct {
|
||||
What string `json:"what"` // Answer to: what data type?
|
||||
Which []string `json:"which"` // Answer to: which fields?
|
||||
}
|
||||
|
||||
// serve is the main entry point of this HTML application.
|
||||
func serve(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
// Checks if the URL contains the baseURL and strips it. Otherwise, it just
|
||||
// returns a 404 fm.Error because we're not supposed to be here!
|
||||
p := strings.TrimPrefix(r.URL.Path, c.BaseURL)
|
||||
func NewHandler(storage *storage.Storage, server *settings.Server) (http.Handler, error) {
|
||||
server.Clean()
|
||||
|
||||
if len(p) >= len(r.URL.Path) && c.BaseURL != "" {
|
||||
return http.StatusNotFound, nil
|
||||
r := mux.NewRouter()
|
||||
index, static := getStaticHandlers(storage, server)
|
||||
|
||||
// NOTE: This fixes the issue where it would redirect if people did not put a
|
||||
// trailing slash in the end. I hate this decision since this allows some awful
|
||||
// URLs https://www.gorillatoolkit.org/pkg/mux#Router.SkipClean
|
||||
r = r.SkipClean(true)
|
||||
|
||||
monkey := func(fn handleFunc, prefix string) http.Handler {
|
||||
return handle(fn, prefix, storage, server)
|
||||
}
|
||||
|
||||
r.URL.Path = p
|
||||
r.PathPrefix("/static").Handler(static)
|
||||
r.NotFoundHandler = index
|
||||
|
||||
// Check if this request is made to the service worker. If so,
|
||||
// pass it through a template to add the needed variables.
|
||||
if r.URL.Path == "/sw.js" {
|
||||
return renderFile(c, w, "sw.js")
|
||||
}
|
||||
api := r.PathPrefix("/api").Subrouter()
|
||||
|
||||
// Checks if this request is made to the static assets folder. If so, and
|
||||
// if it is a GET request, returns with the asset. Otherwise, returns
|
||||
// a status not implemented.
|
||||
if matchURL(r.URL.Path, "/static") {
|
||||
if r.Method != http.MethodGet {
|
||||
return http.StatusNotImplemented, nil
|
||||
}
|
||||
api.Handle("/login", monkey(loginHandler, ""))
|
||||
api.Handle("/signup", monkey(signupHandler, ""))
|
||||
api.Handle("/renew", monkey(renewHandler, ""))
|
||||
|
||||
return staticHandler(c, w, r)
|
||||
}
|
||||
users := api.PathPrefix("/users").Subrouter()
|
||||
users.Handle("", monkey(usersGetHandler, "")).Methods("GET")
|
||||
users.Handle("", monkey(userPostHandler, "")).Methods("POST")
|
||||
users.Handle("/{id:[0-9]+}", monkey(userPutHandler, "")).Methods("PUT")
|
||||
users.Handle("/{id:[0-9]+}", monkey(userGetHandler, "")).Methods("GET")
|
||||
users.Handle("/{id:[0-9]+}", monkey(userDeleteHandler, "")).Methods("DELETE")
|
||||
|
||||
// Checks if this request is made to the API and directs to the
|
||||
// API handler if so.
|
||||
if matchURL(r.URL.Path, "/api") {
|
||||
r.URL.Path = strings.TrimPrefix(r.URL.Path, "/api")
|
||||
return apiHandler(c, w, r)
|
||||
}
|
||||
api.PathPrefix("/resources").Handler(monkey(resourceGetHandler, "/api/resources")).Methods("GET")
|
||||
api.PathPrefix("/resources").Handler(monkey(resourceDeleteHandler, "/api/resources")).Methods("DELETE")
|
||||
api.PathPrefix("/resources").Handler(monkey(resourcePostPutHandler, "/api/resources")).Methods("POST")
|
||||
api.PathPrefix("/resources").Handler(monkey(resourcePostPutHandler, "/api/resources")).Methods("PUT")
|
||||
api.PathPrefix("/resources").Handler(monkey(resourcePatchHandler, "/api/resources")).Methods("PATCH")
|
||||
|
||||
// If it is a request to the preview and a static website generator is
|
||||
// active, build the preview.
|
||||
if strings.HasPrefix(r.URL.Path, "/preview") && c.StaticGen != nil {
|
||||
r.URL.Path = strings.TrimPrefix(r.URL.Path, "/preview")
|
||||
return c.StaticGen.Preview(c, w, r)
|
||||
}
|
||||
api.PathPrefix("/share").Handler(monkey(shareGetsHandler, "/api/share")).Methods("GET")
|
||||
api.PathPrefix("/share").Handler(monkey(sharePostHandler, "/api/share")).Methods("POST")
|
||||
api.PathPrefix("/share").Handler(monkey(shareDeleteHandler, "/api/share")).Methods("DELETE")
|
||||
|
||||
if strings.HasPrefix(r.URL.Path, "/share/") {
|
||||
r.URL.Path = strings.TrimPrefix(r.URL.Path, "/share/")
|
||||
return sharePage(c, w, r)
|
||||
}
|
||||
api.Handle("/settings", monkey(settingsGetHandler, "")).Methods("GET")
|
||||
api.Handle("/settings", monkey(settingsPutHandler, "")).Methods("PUT")
|
||||
|
||||
// Any other request should show the index.html file.
|
||||
w.Header().Set("x-frame-options", "SAMEORIGIN")
|
||||
w.Header().Set("x-content-type-options", "nosniff")
|
||||
w.Header().Set("x-xss-protection", "1; mode=block")
|
||||
api.PathPrefix("/raw").Handler(monkey(rawHandler, "/api/raw")).Methods("GET")
|
||||
api.PathPrefix("/command").Handler(monkey(commandsHandler, "/api/command")).Methods("GET")
|
||||
api.PathPrefix("/search").Handler(monkey(searchHandler, "/api/search")).Methods("GET")
|
||||
|
||||
return renderFile(c, w, "index.html")
|
||||
}
|
||||
|
||||
// staticHandler handles the static assets path.
|
||||
func staticHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
if r.URL.Path != "/static/manifest.json" {
|
||||
http.FileServer(c.Assets.HTTPBox()).ServeHTTP(w, r)
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
return renderFile(c, w, "static/manifest.json")
|
||||
}
|
||||
|
||||
// apiHandler is the main entry point for the /api endpoint.
|
||||
func apiHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
if r.URL.Path == "/auth/get" {
|
||||
return authHandler(c, w, r)
|
||||
}
|
||||
|
||||
if r.URL.Path == "/auth/renew" {
|
||||
return renewAuthHandler(c, w, r)
|
||||
}
|
||||
|
||||
valid, _ := validateAuth(c, r)
|
||||
if !valid {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
c.Router, r.URL.Path = splitURL(r.URL.Path)
|
||||
|
||||
if !c.User.Allowed(r.URL.Path) {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
if c.StaticGen != nil {
|
||||
// If we are using the 'magic url' for the settings,
|
||||
// we should redirect the request for the acutual path.
|
||||
if r.URL.Path == "/settings" {
|
||||
r.URL.Path = c.StaticGen.SettingsPath()
|
||||
}
|
||||
|
||||
// Executes the Static website generator hook.
|
||||
code, err := c.StaticGen.Hook(c, w, r)
|
||||
if code != 0 || err != nil {
|
||||
return code, err
|
||||
}
|
||||
}
|
||||
|
||||
if c.Router == "checksum" || c.Router == "download" {
|
||||
var err error
|
||||
c.File, err = fm.GetInfo(r.URL, c.FileBrowser, c.User)
|
||||
if err != nil {
|
||||
return ErrorToHTTP(err, false), err
|
||||
}
|
||||
}
|
||||
|
||||
var code int
|
||||
var err error
|
||||
|
||||
switch c.Router {
|
||||
case "download":
|
||||
code, err = downloadHandler(c, w, r)
|
||||
case "checksum":
|
||||
code, err = checksumHandler(c, w, r)
|
||||
case "command":
|
||||
code, err = command(c, w, r)
|
||||
case "search":
|
||||
code, err = search(c, w, r)
|
||||
case "resource":
|
||||
code, err = resourceHandler(c, w, r)
|
||||
case "users":
|
||||
code, err = usersHandler(c, w, r)
|
||||
case "settings":
|
||||
code, err = settingsHandler(c, w, r)
|
||||
case "share":
|
||||
code, err = shareHandler(c, w, r)
|
||||
default:
|
||||
code = http.StatusNotFound
|
||||
}
|
||||
|
||||
return code, err
|
||||
}
|
||||
|
||||
// serveChecksum calculates the hash of a file. Supports MD5, SHA1, SHA256 and SHA512.
|
||||
func checksumHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
query := r.URL.Query().Get("algo")
|
||||
|
||||
val, err := c.File.Checksum(query)
|
||||
if err == fm.ErrInvalidOption {
|
||||
return http.StatusBadRequest, err
|
||||
} else if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
w.Write([]byte(val))
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// splitURL splits the path and returns everything that stands
|
||||
// before the first slash and everything that goes after.
|
||||
func splitURL(path string) (string, string) {
|
||||
if path == "" {
|
||||
return "", ""
|
||||
}
|
||||
|
||||
path = strings.TrimPrefix(path, "/")
|
||||
|
||||
i := strings.Index(path, "/")
|
||||
if i == -1 {
|
||||
return "", path
|
||||
}
|
||||
|
||||
return path[0:i], path[i:]
|
||||
}
|
||||
|
||||
// renderFile renders a file using a template with some needed variables.
|
||||
func renderFile(c *fm.Context, w http.ResponseWriter, file string) (int, error) {
|
||||
tpl := template.Must(template.New("file").Parse(c.Assets.MustString(file)))
|
||||
|
||||
var contentType string
|
||||
switch filepath.Ext(file) {
|
||||
case ".html":
|
||||
contentType = "text/html"
|
||||
case ".js":
|
||||
contentType = "application/javascript"
|
||||
case ".json":
|
||||
contentType = "application/json"
|
||||
default:
|
||||
contentType = "text"
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", contentType+"; charset=utf-8")
|
||||
|
||||
data := map[string]interface{}{
|
||||
"BaseURL": c.RootURL(),
|
||||
"NoAuth": c.NoAuth,
|
||||
"Version": fm.Version,
|
||||
"CSS": template.CSS(c.CSS),
|
||||
"ReCaptcha": c.ReCaptchaKey != "" && c.ReCaptchaSecret != "",
|
||||
"ReCaptchaHost": c.ReCaptchaHost,
|
||||
"ReCaptchaKey": c.ReCaptchaKey,
|
||||
}
|
||||
|
||||
if c.StaticGen != nil {
|
||||
data["StaticGen"] = c.StaticGen.Name()
|
||||
}
|
||||
|
||||
err := tpl.Execute(w, data)
|
||||
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// sharePage build the share page.
|
||||
func sharePage(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
s, err := c.Store.Share.Get(r.URL.Path)
|
||||
if err == fm.ErrNotExist {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return renderFile(c, w, "static/share/404.html")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
if s.Expires && s.ExpireDate.Before(time.Now()) {
|
||||
c.Store.Share.Delete(s.Hash)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return renderFile(c, w, "static/share/404.html")
|
||||
}
|
||||
|
||||
r.URL.Path = s.Path
|
||||
|
||||
info, err := os.Stat(s.Path)
|
||||
if err != nil {
|
||||
c.Store.Share.Delete(s.Hash)
|
||||
return ErrorToHTTP(err, false), err
|
||||
}
|
||||
|
||||
c.File = &fm.File{
|
||||
Path: s.Path,
|
||||
Name: info.Name(),
|
||||
ModTime: info.ModTime(),
|
||||
Mode: info.Mode(),
|
||||
IsDir: info.IsDir(),
|
||||
Size: info.Size(),
|
||||
}
|
||||
|
||||
dl := r.URL.Query().Get("dl")
|
||||
|
||||
if dl == "" || dl == "0" {
|
||||
tpl := template.Must(template.New("file").Parse(c.Assets.MustString("static/share/index.html")))
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
|
||||
err := tpl.Execute(w, map[string]interface{}{
|
||||
"BaseURL": c.RootURL(),
|
||||
"File": c.File,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
return downloadHandler(c, w, r)
|
||||
}
|
||||
|
||||
// renderJSON prints the JSON version of data to the browser.
|
||||
func renderJSON(w http.ResponseWriter, data interface{}) (int, error) {
|
||||
marsh, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
if _, err := w.Write(marsh); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// matchURL checks if the first URL matches the second.
|
||||
func matchURL(first, second string) bool {
|
||||
first = strings.ToLower(first)
|
||||
second = strings.ToLower(second)
|
||||
|
||||
return strings.HasPrefix(first, second)
|
||||
}
|
||||
|
||||
// ErrorToHTTP converts errors to HTTP Status Code.
|
||||
func ErrorToHTTP(err error, gone bool) int {
|
||||
switch {
|
||||
case err == nil:
|
||||
return http.StatusOK
|
||||
case os.IsPermission(err):
|
||||
return http.StatusForbidden
|
||||
case os.IsNotExist(err):
|
||||
if !gone {
|
||||
return http.StatusNotFound
|
||||
}
|
||||
|
||||
return http.StatusGone
|
||||
case os.IsExist(err):
|
||||
return http.StatusConflict
|
||||
default:
|
||||
return http.StatusInternalServerError
|
||||
}
|
||||
public := api.PathPrefix("/public").Subrouter()
|
||||
public.PathPrefix("/dl").Handler(monkey(publicDlHandler, "/api/public/dl/")).Methods("GET")
|
||||
public.PathPrefix("/share").Handler(monkey(publicShareHandler, "/api/public/share/")).Methods("GET")
|
||||
|
||||
return stripPrefix(server.BaseURL, r), nil
|
||||
}
|
||||
|
||||
50
http/public.go
Normal file
50
http/public.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
)
|
||||
|
||||
var withHashFile = func(fn handleFunc) handleFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
link, err := d.store.Share.GetByHash(r.URL.Path)
|
||||
if err != nil {
|
||||
return errToStatus(err), err
|
||||
}
|
||||
|
||||
user, err := d.store.Users.Get(d.server.Root, link.UserID)
|
||||
if err != nil {
|
||||
return errToStatus(err), err
|
||||
}
|
||||
|
||||
d.user = user
|
||||
|
||||
file, err := files.NewFileInfo(files.FileOptions{
|
||||
Fs: d.user.Fs,
|
||||
Path: link.Path,
|
||||
Modify: d.user.Perm.Modify,
|
||||
Expand: false,
|
||||
Checker: d,
|
||||
})
|
||||
if err != nil {
|
||||
return errToStatus(err), err
|
||||
}
|
||||
|
||||
d.raw = file
|
||||
return fn(w, r, d)
|
||||
}
|
||||
}
|
||||
|
||||
var publicShareHandler = withHashFile(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
return renderJSON(w, r, d.raw)
|
||||
})
|
||||
|
||||
var publicDlHandler = withHashFile(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
file := d.raw.(*files.FileInfo)
|
||||
if !file.IsDir {
|
||||
return rawFileHandler(w, r, file)
|
||||
}
|
||||
|
||||
return rawDirHandler(w, r, d, file)
|
||||
})
|
||||
177
http/raw.go
Normal file
177
http/raw.go
Normal file
@@ -0,0 +1,177 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"github.com/hacdias/fileutils"
|
||||
"github.com/mholt/archiver"
|
||||
)
|
||||
|
||||
func parseQueryFiles(r *http.Request, f *files.FileInfo, u *users.User) ([]string, error) {
|
||||
files := []string{}
|
||||
names := strings.Split(r.URL.Query().Get("files"), ",")
|
||||
|
||||
if len(names) == 0 {
|
||||
files = append(files, f.Path)
|
||||
} else {
|
||||
for _, name := range names {
|
||||
name, err := url.QueryUnescape(strings.Replace(name, "+", "%2B", -1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
name = fileutils.SlashClean(name)
|
||||
files = append(files, filepath.Join(f.Path, name))
|
||||
}
|
||||
}
|
||||
|
||||
return files, nil
|
||||
}
|
||||
|
||||
func parseQueryAlgorithm(r *http.Request) (string, archiver.Writer, error) {
|
||||
switch r.URL.Query().Get("algo") {
|
||||
case "zip", "true", "":
|
||||
return ".zip", archiver.NewZip(), nil
|
||||
case "tar":
|
||||
return ".tar", archiver.NewTar(), nil
|
||||
case "targz":
|
||||
return ".tar.gz", archiver.NewTarGz(), nil
|
||||
case "tarbz2":
|
||||
return ".tar.bz2", archiver.NewTarBz2(), nil
|
||||
case "tarxz":
|
||||
return ".tar.xz", archiver.NewTarXz(), nil
|
||||
case "tarlz4":
|
||||
return ".tar.lz4", archiver.NewTarLz4(), nil
|
||||
case "tarsz":
|
||||
return ".tar.sz", archiver.NewTarSz(), nil
|
||||
default:
|
||||
return "", nil, errors.New("format not implemented")
|
||||
}
|
||||
}
|
||||
|
||||
var rawHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
if !d.user.Perm.Download {
|
||||
return http.StatusAccepted, nil
|
||||
}
|
||||
|
||||
file, err := files.NewFileInfo(files.FileOptions{
|
||||
Fs: d.user.Fs,
|
||||
Path: r.URL.Path,
|
||||
Modify: d.user.Perm.Modify,
|
||||
Expand: false,
|
||||
Checker: d,
|
||||
})
|
||||
if err != nil {
|
||||
return errToStatus(err), err
|
||||
}
|
||||
|
||||
if !file.IsDir {
|
||||
return rawFileHandler(w, r, file)
|
||||
}
|
||||
|
||||
return rawDirHandler(w, r, d, file)
|
||||
})
|
||||
|
||||
func addFile(ar archiver.Writer, d *data, path string) error {
|
||||
// Checks are always done with paths with "/" as path separator.
|
||||
path = strings.Replace(path, "\\", "/", -1)
|
||||
if !d.Check(path) {
|
||||
return nil
|
||||
}
|
||||
|
||||
info, err := d.user.Fs.Stat(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
file, err := d.user.Fs.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
err = ar.Write(archiver.File{
|
||||
FileInfo: archiver.FileInfo{
|
||||
FileInfo: info,
|
||||
CustomName: strings.TrimPrefix(path, "/"),
|
||||
},
|
||||
ReadCloser: file,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if info.IsDir() {
|
||||
names, err := file.Readdirnames(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, name := range names {
|
||||
err = addFile(ar, d, filepath.Join(path, name))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func rawDirHandler(w http.ResponseWriter, r *http.Request, d *data, file *files.FileInfo) (int, error) {
|
||||
filenames, err := parseQueryFiles(r, file, d.user)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
extension, ar, err := parseQueryAlgorithm(r)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
name := file.Name
|
||||
if name == "." || name == "" {
|
||||
name = "archive"
|
||||
}
|
||||
name += extension
|
||||
w.Header().Set("Content-Disposition", "attachment; filename*=utf-8''"+url.PathEscape(name))
|
||||
|
||||
err = ar.Create(w)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
defer ar.Close()
|
||||
|
||||
for _, fname := range filenames {
|
||||
err = addFile(ar, d, fname)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
}
|
||||
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func rawFileHandler(w http.ResponseWriter, r *http.Request, file *files.FileInfo) (int, error) {
|
||||
fd, err := file.Fs.Open(file.Path)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
defer fd.Close()
|
||||
|
||||
if r.URL.Query().Get("inline") == "true" {
|
||||
w.Header().Set("Content-Disposition", "inline")
|
||||
} else {
|
||||
// As per RFC6266 section 4.3
|
||||
w.Header().Set("Content-Disposition", "attachment; filename*=utf-8''"+url.PathEscape(file.Name))
|
||||
}
|
||||
|
||||
http.ServeContent(w, r, file.Name, file.ModTime, fd)
|
||||
return 0, nil
|
||||
}
|
||||
404
http/resource.go
404
http/resource.go
@@ -1,386 +1,158 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
fm "github.com/filebrowser/filebrowser"
|
||||
"github.com/hacdias/fileutils"
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/errors"
|
||||
"github.com/filebrowser/filebrowser/v2/fileutils"
|
||||
)
|
||||
|
||||
// sanitizeURL sanitizes the URL to prevent path transversal
|
||||
// using fileutils.SlashClean and adds the trailing slash bar.
|
||||
func sanitizeURL(url string) string {
|
||||
path := fileutils.SlashClean(url)
|
||||
if strings.HasSuffix(url, "/") && path != "/" {
|
||||
return path + "/"
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func resourceHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
r.URL.Path = sanitizeURL(r.URL.Path)
|
||||
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
return resourceGetHandler(c, w, r)
|
||||
case http.MethodDelete:
|
||||
return resourceDeleteHandler(c, w, r)
|
||||
case http.MethodPut:
|
||||
// Before save command handler.
|
||||
path := filepath.Join(c.User.Scope, r.URL.Path)
|
||||
if err := c.Runner("before_save", path, "", c.User); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
code, err := resourcePostPutHandler(c, w, r)
|
||||
if code != http.StatusOK {
|
||||
return code, err
|
||||
}
|
||||
|
||||
// After save command handler.
|
||||
if err := c.Runner("after_save", path, "", c.User); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
return code, err
|
||||
case http.MethodPatch:
|
||||
return resourcePatchHandler(c, w, r)
|
||||
case http.MethodPost:
|
||||
return resourcePostPutHandler(c, w, r)
|
||||
}
|
||||
|
||||
return http.StatusNotImplemented, nil
|
||||
}
|
||||
|
||||
func resourceGetHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
// Gets the information of the directory/file.
|
||||
f, err := fm.GetInfo(r.URL, c.FileBrowser, c.User)
|
||||
var resourceGetHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
file, err := files.NewFileInfo(files.FileOptions{
|
||||
Fs: d.user.Fs,
|
||||
Path: r.URL.Path,
|
||||
Modify: d.user.Perm.Modify,
|
||||
Expand: true,
|
||||
Checker: d,
|
||||
})
|
||||
if err != nil {
|
||||
return ErrorToHTTP(err, false), err
|
||||
return errToStatus(err), err
|
||||
}
|
||||
|
||||
// If it's a dir and the path doesn't end with a trailing slash,
|
||||
// add a trailing slash to the path.
|
||||
if f.IsDir && !strings.HasSuffix(r.URL.Path, "/") {
|
||||
r.URL.Path = r.URL.Path + "/"
|
||||
if file.IsDir {
|
||||
file.Listing.Sorting = d.user.Sorting
|
||||
file.Listing.ApplySort()
|
||||
return renderJSON(w, r, file)
|
||||
}
|
||||
|
||||
// If it is a dir, go and serve the listing.
|
||||
if f.IsDir {
|
||||
c.File = f
|
||||
return listingHandler(c, w, r)
|
||||
if checksum := r.URL.Query().Get("checksum"); checksum != "" {
|
||||
err := file.Checksum(checksum)
|
||||
if err == errors.ErrInvalidOption {
|
||||
return http.StatusBadRequest, nil
|
||||
} else if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
// do not waste bandwidth if we just want the checksum
|
||||
file.Content = ""
|
||||
}
|
||||
|
||||
// Tries to get the file type.
|
||||
if err = f.GetFileType(true); err != nil {
|
||||
return ErrorToHTTP(err, true), err
|
||||
}
|
||||
return renderJSON(w, r, file)
|
||||
})
|
||||
|
||||
// Serve a preview if the file can't be edited or the
|
||||
// user has no permission to edit this file. Otherwise,
|
||||
// just serve the editor.
|
||||
if !f.CanBeEdited() || !c.User.AllowEdit {
|
||||
f.Kind = "preview"
|
||||
return renderJSON(w, f)
|
||||
}
|
||||
|
||||
f.Kind = "editor"
|
||||
|
||||
// Tries to get the editor data.
|
||||
if err = f.GetEditor(); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
return renderJSON(w, f)
|
||||
}
|
||||
|
||||
func listingHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
f := c.File
|
||||
f.Kind = "listing"
|
||||
|
||||
// Tries to get the listing data.
|
||||
if err := f.GetListing(c.User, r); err != nil {
|
||||
return ErrorToHTTP(err, true), err
|
||||
}
|
||||
|
||||
listing := f.Listing
|
||||
|
||||
// Defines the cookie scope.
|
||||
cookieScope := c.RootURL()
|
||||
if cookieScope == "" {
|
||||
cookieScope = "/"
|
||||
}
|
||||
|
||||
// Copy the query values into the Listing struct
|
||||
if sort, order, err := handleSortOrder(w, r, cookieScope); err == nil {
|
||||
listing.Sort = sort
|
||||
listing.Order = order
|
||||
} else {
|
||||
return http.StatusBadRequest, err
|
||||
}
|
||||
|
||||
listing.ApplySort()
|
||||
return renderJSON(w, f)
|
||||
}
|
||||
|
||||
func resourceDeleteHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
// Prevent the removal of the root directory.
|
||||
if r.URL.Path == "/" || !c.User.AllowEdit {
|
||||
var resourceDeleteHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
if r.URL.Path == "/" || !d.user.Perm.Delete {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
// Fire the before trigger.
|
||||
if err := c.Runner("before_delete", r.URL.Path, "", c.User); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
err := d.RunHook(func() error {
|
||||
return d.user.Fs.RemoveAll(r.URL.Path)
|
||||
}, "delete", r.URL.Path, "", d.user)
|
||||
|
||||
// Remove the file or folder.
|
||||
err := c.User.FileSystem.RemoveAll(r.URL.Path)
|
||||
if err != nil {
|
||||
return ErrorToHTTP(err, true), err
|
||||
}
|
||||
|
||||
// Fire the after trigger.
|
||||
if err := c.Runner("after_delete", r.URL.Path, "", c.User); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
return errToStatus(err), err
|
||||
}
|
||||
|
||||
return http.StatusOK, nil
|
||||
}
|
||||
})
|
||||
|
||||
func resourcePostPutHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
if !c.User.AllowNew && r.Method == http.MethodPost {
|
||||
var resourcePostPutHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
if !d.user.Perm.Create && r.Method == http.MethodPost {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
if !c.User.AllowEdit && r.Method == http.MethodPut {
|
||||
if !d.user.Perm.Modify && r.Method == http.MethodPut {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
// Discard any invalid upload before returning to avoid connection
|
||||
// reset error.
|
||||
defer func() {
|
||||
io.Copy(ioutil.Discard, r.Body)
|
||||
}()
|
||||
|
||||
// Checks if the current request is for a directory and not a file.
|
||||
// For directories, only allow POST for creation.
|
||||
if strings.HasSuffix(r.URL.Path, "/") {
|
||||
// If the method is PUT, we return 405 Method not Allowed, because
|
||||
// POST should be used instead.
|
||||
if r.Method == http.MethodPut {
|
||||
return http.StatusMethodNotAllowed, nil
|
||||
}
|
||||
|
||||
// Otherwise we try to create the directory.
|
||||
err := c.User.FileSystem.Mkdir(r.URL.Path, 0776)
|
||||
return ErrorToHTTP(err, false), err
|
||||
err := d.user.Fs.MkdirAll(r.URL.Path, 0775)
|
||||
return errToStatus(err), err
|
||||
}
|
||||
|
||||
// If using POST method, we are trying to create a new file so it is not
|
||||
// desirable to override an already existent file. Thus, we check
|
||||
// if the file already exists. If so, we just return a 409 Conflict.
|
||||
if r.Method == http.MethodPost && r.Header.Get("Action") != "override" {
|
||||
if _, err := c.User.FileSystem.Stat(r.URL.Path); err == nil {
|
||||
return http.StatusConflict, errors.New("There is already a file on that path")
|
||||
if r.Method == http.MethodPost && r.URL.Query().Get("override") != "true" {
|
||||
if _, err := d.user.Fs.Stat(r.URL.Path); err == nil {
|
||||
return http.StatusConflict, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Fire the before trigger.
|
||||
if err := c.Runner("before_upload", r.URL.Path, "", c.User); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
// Create/Open the file.
|
||||
f, err := c.User.FileSystem.OpenFile(r.URL.Path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0776)
|
||||
if err != nil {
|
||||
return ErrorToHTTP(err, false), err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// Copies the new content for the file.
|
||||
_, err = io.Copy(f, r.Body)
|
||||
if err != nil {
|
||||
return ErrorToHTTP(err, false), err
|
||||
}
|
||||
|
||||
// Gets the info about the file.
|
||||
fi, err := f.Stat()
|
||||
if err != nil {
|
||||
return ErrorToHTTP(err, false), err
|
||||
}
|
||||
|
||||
// Check if this instance has a Static Generator and handles publishing
|
||||
// or scheduling if it's the case.
|
||||
if c.StaticGen != nil {
|
||||
code, err := resourcePublishSchedule(c, w, r)
|
||||
if code != 0 {
|
||||
return code, err
|
||||
}
|
||||
}
|
||||
|
||||
// Writes the ETag Header.
|
||||
etag := fmt.Sprintf(`"%x%x"`, fi.ModTime().UnixNano(), fi.Size())
|
||||
w.Header().Set("ETag", etag)
|
||||
|
||||
// Fire the after trigger.
|
||||
if err := c.Runner("after_upload", r.URL.Path, "", c.User); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
return http.StatusOK, nil
|
||||
}
|
||||
|
||||
func resourcePublishSchedule(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
publish := r.Header.Get("Publish")
|
||||
schedule := r.Header.Get("Schedule")
|
||||
|
||||
if publish != "true" && schedule == "" {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
if !c.User.AllowPublish {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
if publish == "true" {
|
||||
return resourcePublish(c, w, r)
|
||||
}
|
||||
|
||||
t, err := time.Parse("2006-01-02T15:04", schedule)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
c.Cron.AddFunc(t.Format("05 04 15 02 01 *"), func() {
|
||||
_, err := resourcePublish(c, w, r)
|
||||
err := d.RunHook(func() error {
|
||||
file, err := d.user.Fs.OpenFile(r.URL.Path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0775)
|
||||
if err != nil {
|
||||
log.Print(err)
|
||||
return err
|
||||
}
|
||||
})
|
||||
defer file.Close()
|
||||
|
||||
return http.StatusOK, nil
|
||||
}
|
||||
_, err = io.Copy(file, r.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
func resourcePublish(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
path := filepath.Join(c.User.Scope, r.URL.Path)
|
||||
// Gets the info about the file.
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Before save command handler.
|
||||
if err := c.Runner("before_publish", path, "", c.User); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
etag := fmt.Sprintf(`"%x%x"`, info.ModTime().UnixNano(), info.Size())
|
||||
w.Header().Set("ETag", etag)
|
||||
return nil
|
||||
}, "upload", r.URL.Path, "", d.user)
|
||||
|
||||
code, err := c.StaticGen.Publish(c, w, r)
|
||||
if err != nil {
|
||||
return code, err
|
||||
}
|
||||
|
||||
// Executed the before publish command.
|
||||
if err := c.Runner("before_publish", path, "", c.User); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
return code, nil
|
||||
}
|
||||
|
||||
// resourcePatchHandler is the entry point for resource handler.
|
||||
func resourcePatchHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
if !c.User.AllowEdit {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
dst := r.Header.Get("Destination")
|
||||
action := r.Header.Get("Action")
|
||||
dst, err := url.QueryUnescape(dst)
|
||||
if err != nil {
|
||||
return ErrorToHTTP(err, true), err
|
||||
}
|
||||
return errToStatus(err), err
|
||||
})
|
||||
|
||||
var resourcePatchHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
src := r.URL.Path
|
||||
dst := r.URL.Query().Get("destination")
|
||||
action := r.URL.Query().Get("action")
|
||||
dst, err := url.QueryUnescape(dst)
|
||||
|
||||
if err != nil {
|
||||
return errToStatus(err), err
|
||||
}
|
||||
|
||||
if dst == "/" || src == "/" {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
if action == "copy" {
|
||||
// Fire the after trigger.
|
||||
if err := c.Runner("before_copy", src, dst, c.User); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
switch action {
|
||||
case "copy":
|
||||
if !d.user.Perm.Create {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
// Copy the file.
|
||||
err = c.User.FileSystem.Copy(src, dst)
|
||||
|
||||
// Fire the after trigger.
|
||||
if err := c.Runner("after_copy", src, dst, c.User); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
} else {
|
||||
// Fire the after trigger.
|
||||
if err := c.Runner("before_rename", src, dst, c.User); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
// Rename the file.
|
||||
err = c.User.FileSystem.Rename(src, dst)
|
||||
|
||||
// Fire the after trigger.
|
||||
if err := c.Runner("after_rename", src, dst, c.User); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
case "rename":
|
||||
default:
|
||||
action = "rename"
|
||||
if !d.user.Perm.Rename {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
}
|
||||
|
||||
return ErrorToHTTP(err, true), err
|
||||
}
|
||||
|
||||
// handleSortOrder gets and stores for a Listing the 'sort' and 'order',
|
||||
// and reads 'limit' if given. The latter is 0 if not given. Sets cookies.
|
||||
func handleSortOrder(w http.ResponseWriter, r *http.Request, scope string) (sort string, order string, err error) {
|
||||
sort = r.URL.Query().Get("sort")
|
||||
order = r.URL.Query().Get("order")
|
||||
|
||||
// If the query 'sort' or 'order' is empty, use defaults or any values
|
||||
// previously saved in Cookies.
|
||||
switch sort {
|
||||
case "":
|
||||
sort = "name"
|
||||
if sortCookie, sortErr := r.Cookie("sort"); sortErr == nil {
|
||||
sort = sortCookie.Value
|
||||
err = d.RunHook(func() error {
|
||||
if action == "copy" {
|
||||
return fileutils.Copy(d.user.Fs, src, dst)
|
||||
}
|
||||
case "name", "size":
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "sort",
|
||||
Value: sort,
|
||||
MaxAge: 31536000,
|
||||
Path: scope,
|
||||
Secure: r.TLS != nil,
|
||||
})
|
||||
}
|
||||
|
||||
switch order {
|
||||
case "":
|
||||
order = "asc"
|
||||
if orderCookie, orderErr := r.Cookie("order"); orderErr == nil {
|
||||
order = orderCookie.Value
|
||||
}
|
||||
case "asc", "desc":
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "order",
|
||||
Value: order,
|
||||
MaxAge: 31536000,
|
||||
Path: scope,
|
||||
Secure: r.TLS != nil,
|
||||
})
|
||||
}
|
||||
return d.user.Fs.Rename(src, dst)
|
||||
}, action, src, dst, d.user)
|
||||
|
||||
return
|
||||
}
|
||||
return errToStatus(err), err
|
||||
})
|
||||
|
||||
28
http/search.go
Normal file
28
http/search.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/search"
|
||||
)
|
||||
|
||||
var searchHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
response := []map[string]interface{}{}
|
||||
query := r.URL.Query().Get("query")
|
||||
|
||||
err := search.Search(d.user.Fs, r.URL.Path, query, d, func(path string, f os.FileInfo) error {
|
||||
response = append(response, map[string]interface{}{
|
||||
"dir": f.IsDir(),
|
||||
"path": path,
|
||||
})
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
return renderJSON(w, r, response)
|
||||
})
|
||||
162
http/settings.go
162
http/settings.go
@@ -1,146 +1,52 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"reflect"
|
||||
|
||||
fm "github.com/filebrowser/filebrowser"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"github.com/filebrowser/filebrowser/v2/rules"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
)
|
||||
|
||||
type modifySettingsRequest struct {
|
||||
modifyRequest
|
||||
Data struct {
|
||||
CSS string `json:"css"`
|
||||
Commands map[string][]string `json:"commands"`
|
||||
StaticGen map[string]interface{} `json:"staticGen"`
|
||||
} `json:"data"`
|
||||
type settingsData struct {
|
||||
Signup bool `json:"signup"`
|
||||
CreateUserDir bool `json:"createUserDir"`
|
||||
Defaults settings.UserDefaults `json:"defaults"`
|
||||
Rules []rules.Rule `json:"rules"`
|
||||
Branding settings.Branding `json:"branding"`
|
||||
Shell []string `json:"shell"`
|
||||
Commands map[string][]string `json:"commands"`
|
||||
}
|
||||
|
||||
type option struct {
|
||||
Variable string `json:"variable"`
|
||||
Name string `json:"name"`
|
||||
Value interface{} `json:"value"`
|
||||
}
|
||||
|
||||
func parsePutSettingsRequest(r *http.Request) (*modifySettingsRequest, error) {
|
||||
// Checks if the request body is empty.
|
||||
if r.Body == nil {
|
||||
return nil, fm.ErrEmptyRequest
|
||||
var settingsGetHandler = withAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
data := &settingsData{
|
||||
Signup: d.settings.Signup,
|
||||
CreateUserDir: d.settings.CreateUserDir,
|
||||
Defaults: d.settings.Defaults,
|
||||
Rules: d.settings.Rules,
|
||||
Branding: d.settings.Branding,
|
||||
Shell: d.settings.Shell,
|
||||
Commands: d.settings.Commands,
|
||||
}
|
||||
|
||||
// Parses the request body and checks if it's well formed.
|
||||
mod := &modifySettingsRequest{}
|
||||
err := json.NewDecoder(r.Body).Decode(mod)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return renderJSON(w, r, data)
|
||||
})
|
||||
|
||||
// Checks if the request type is right.
|
||||
if mod.What != "settings" {
|
||||
return nil, fm.ErrWrongDataType
|
||||
}
|
||||
|
||||
return mod, nil
|
||||
}
|
||||
|
||||
func settingsHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
if r.URL.Path != "" && r.URL.Path != "/" {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
return settingsGetHandler(c, w, r)
|
||||
case http.MethodPut:
|
||||
return settingsPutHandler(c, w, r)
|
||||
}
|
||||
|
||||
return http.StatusMethodNotAllowed, nil
|
||||
}
|
||||
|
||||
type settingsGetRequest struct {
|
||||
CSS string `json:"css"`
|
||||
Commands map[string][]string `json:"commands"`
|
||||
StaticGen []option `json:"staticGen"`
|
||||
}
|
||||
|
||||
func settingsGetHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
if !c.User.Admin {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
result := &settingsGetRequest{
|
||||
Commands: c.Commands,
|
||||
StaticGen: []option{},
|
||||
CSS: c.CSS,
|
||||
}
|
||||
|
||||
if c.StaticGen != nil {
|
||||
t := reflect.TypeOf(c.StaticGen).Elem()
|
||||
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
if t.Field(i).Name[0] == bytes.ToLower([]byte{t.Field(i).Name[0]})[0] {
|
||||
continue
|
||||
}
|
||||
|
||||
result.StaticGen = append(result.StaticGen, option{
|
||||
Variable: t.Field(i).Name,
|
||||
Name: t.Field(i).Tag.Get("name"),
|
||||
Value: reflect.ValueOf(c.StaticGen).Elem().FieldByName(t.Field(i).Name).Interface(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return renderJSON(w, result)
|
||||
}
|
||||
|
||||
func settingsPutHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
if !c.User.Admin {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
mod, err := parsePutSettingsRequest(r)
|
||||
var settingsPutHandler = withAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
req := &settingsData{}
|
||||
err := json.NewDecoder(r.Body).Decode(req)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, err
|
||||
}
|
||||
|
||||
// Update the commands.
|
||||
if mod.Which == "commands" {
|
||||
if err := c.Store.Config.Save("commands", mod.Data.Commands); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
d.settings.Signup = req.Signup
|
||||
d.settings.CreateUserDir = req.CreateUserDir
|
||||
d.settings.Defaults = req.Defaults
|
||||
d.settings.Rules = req.Rules
|
||||
d.settings.Branding = req.Branding
|
||||
d.settings.Shell = req.Shell
|
||||
d.settings.Commands = req.Commands
|
||||
|
||||
c.Commands = mod.Data.Commands
|
||||
return http.StatusOK, nil
|
||||
}
|
||||
|
||||
// Update the global CSS.
|
||||
if mod.Which == "css" {
|
||||
if err := c.Store.Config.Save("css", mod.Data.CSS); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
c.CSS = mod.Data.CSS
|
||||
return http.StatusOK, nil
|
||||
}
|
||||
|
||||
// Update the static generator options.
|
||||
if mod.Which == "staticGen" {
|
||||
err = mapstructure.Decode(mod.Data.StaticGen, c.StaticGen)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
err = c.Store.Config.Save("staticgen_"+c.StaticGen.Name(), c.StaticGen)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
return http.StatusOK, nil
|
||||
}
|
||||
|
||||
return http.StatusMethodNotAllowed, nil
|
||||
}
|
||||
err = d.store.Settings.Save(d.settings)
|
||||
return errToStatus(err), err
|
||||
})
|
||||
|
||||
116
http/share.go
116
http/share.go
@@ -1,87 +1,78 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
fm "github.com/filebrowser/filebrowser"
|
||||
"github.com/filebrowser/filebrowser/v2/errors"
|
||||
"github.com/filebrowser/filebrowser/v2/share"
|
||||
)
|
||||
|
||||
func shareHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
r.URL.Path = sanitizeURL(r.URL.Path)
|
||||
func withPermShare(fn handleFunc) handleFunc {
|
||||
return withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
if !d.user.Perm.Share {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
return shareGetHandler(c, w, r)
|
||||
case http.MethodDelete:
|
||||
return shareDeleteHandler(c, w, r)
|
||||
case http.MethodPost:
|
||||
return sharePostHandler(c, w, r)
|
||||
}
|
||||
|
||||
return http.StatusNotImplemented, nil
|
||||
return fn(w, r, d)
|
||||
})
|
||||
}
|
||||
|
||||
func shareGetHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
path := filepath.Join(c.User.Scope, r.URL.Path)
|
||||
s, err := c.Store.Share.GetByPath(path)
|
||||
if err == fm.ErrNotExist {
|
||||
return http.StatusNotFound, nil
|
||||
var shareGetsHandler = withPermShare(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
s, err := d.store.Share.Gets(r.URL.Path, d.user.ID)
|
||||
if err == errors.ErrNotExist {
|
||||
return renderJSON(w, r, []*share.Link{})
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
for i, link := range s {
|
||||
if link.Expires && link.ExpireDate.Before(time.Now()) {
|
||||
c.Store.Share.Delete(link.Hash)
|
||||
s = append(s[:i], s[i+1:]...)
|
||||
}
|
||||
return renderJSON(w, r, s)
|
||||
})
|
||||
|
||||
var shareDeleteHandler = withPermShare(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
hash := strings.TrimSuffix(r.URL.Path, "/")
|
||||
hash = strings.TrimPrefix(hash, "/")
|
||||
|
||||
if hash == "" {
|
||||
return http.StatusBadRequest, nil
|
||||
}
|
||||
|
||||
if len(s) == 0 {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
err := d.store.Share.Delete(hash)
|
||||
return errToStatus(err), err
|
||||
})
|
||||
|
||||
return renderJSON(w, s)
|
||||
}
|
||||
|
||||
func sharePostHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
path := filepath.Join(c.User.Scope, r.URL.Path)
|
||||
|
||||
var s *fm.ShareLink
|
||||
expire := r.URL.Query().Get("expires")
|
||||
var sharePostHandler = withPermShare(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
var s *share.Link
|
||||
rawExpire := r.URL.Query().Get("expires")
|
||||
unit := r.URL.Query().Get("unit")
|
||||
|
||||
if expire == "" {
|
||||
if rawExpire == "" {
|
||||
var err error
|
||||
s, err = c.Store.Share.GetPermanent(path)
|
||||
s, err = d.store.Share.GetPermanent(r.URL.Path, d.user.ID)
|
||||
if err == nil {
|
||||
w.Write([]byte(c.RootURL() + "/share/" + s.Hash))
|
||||
w.Write([]byte(d.server.BaseURL + "/share/" + s.Hash))
|
||||
return 0, nil
|
||||
}
|
||||
}
|
||||
|
||||
bytes, err := fm.GenerateRandomBytes(6)
|
||||
bytes := make([]byte, 6)
|
||||
_, err := rand.Read(bytes)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
str := base64.URLEncoding.EncodeToString(bytes)
|
||||
|
||||
s = &fm.ShareLink{
|
||||
Path: path,
|
||||
Hash: str,
|
||||
Expires: expire != "",
|
||||
}
|
||||
var expire int64 = 0
|
||||
|
||||
if expire != "" {
|
||||
num, err := strconv.Atoi(expire)
|
||||
if rawExpire != "" {
|
||||
num, err := strconv.Atoi(rawExpire)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
@@ -98,30 +89,19 @@ func sharePostHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (in
|
||||
add = time.Hour * time.Duration(num)
|
||||
}
|
||||
|
||||
s.ExpireDate = time.Now().Add(add)
|
||||
expire = time.Now().Add(add).Unix()
|
||||
}
|
||||
|
||||
if err := c.Store.Share.Save(s); err != nil {
|
||||
s = &share.Link{
|
||||
Path: r.URL.Path,
|
||||
Hash: str,
|
||||
Expire: expire,
|
||||
UserID: d.user.ID,
|
||||
}
|
||||
|
||||
if err := d.store.Share.Save(s); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
return renderJSON(w, s)
|
||||
}
|
||||
|
||||
func shareDeleteHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
s, err := c.Store.Share.Get(strings.TrimPrefix(r.URL.Path, "/"))
|
||||
if err == fm.ErrNotExist {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
err = c.Store.Share.Delete(s.Hash)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
return http.StatusOK, nil
|
||||
}
|
||||
return renderJSON(w, r, s)
|
||||
})
|
||||
|
||||
126
http/static.go
Normal file
126
http/static.go
Normal file
@@ -0,0 +1,126 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
rice "github.com/GeertJohan/go.rice"
|
||||
"github.com/filebrowser/filebrowser/v2/auth"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/storage"
|
||||
"github.com/filebrowser/filebrowser/v2/version"
|
||||
)
|
||||
|
||||
func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *data, box *rice.Box, file, contentType string) (int, error) {
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
|
||||
staticURL := strings.TrimPrefix(d.server.BaseURL+"/static", "/")
|
||||
|
||||
auther, err := d.store.Auth.Get(d.settings.AuthMethod)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
data := map[string]interface{}{
|
||||
"Name": d.settings.Branding.Name,
|
||||
"DisableExternal": d.settings.Branding.DisableExternal,
|
||||
"BaseURL": d.server.BaseURL,
|
||||
"Version": version.Version,
|
||||
"StaticURL": staticURL,
|
||||
"Signup": d.settings.Signup,
|
||||
"NoAuth": d.settings.AuthMethod == auth.MethodNoAuth,
|
||||
"LoginPage": auther.LoginPage(),
|
||||
"CSS": false,
|
||||
"ReCaptcha": false,
|
||||
}
|
||||
|
||||
if d.settings.Branding.Files != "" {
|
||||
path := filepath.Join(d.settings.Branding.Files, "custom.css")
|
||||
_, err := os.Stat(path)
|
||||
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
log.Printf("couldn't load custom styles: %v", err)
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
data["CSS"] = true
|
||||
}
|
||||
}
|
||||
|
||||
if d.settings.AuthMethod == auth.MethodJSONAuth {
|
||||
raw, err := d.store.Auth.Get(d.settings.AuthMethod)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
auther := raw.(*auth.JSONAuth)
|
||||
|
||||
if auther.ReCaptcha != nil {
|
||||
data["ReCaptcha"] = auther.ReCaptcha.Key != "" && auther.ReCaptcha.Secret != ""
|
||||
data["ReCaptchaHost"] = auther.ReCaptcha.Host
|
||||
data["ReCaptchaKey"] = auther.ReCaptcha.Key
|
||||
}
|
||||
}
|
||||
|
||||
b, err := json.MarshalIndent(data, "", " ")
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
data["Json"] = string(b)
|
||||
|
||||
index := template.Must(template.New("index").Delims("[{[", "]}]").Parse(box.MustString(file)))
|
||||
err = index.Execute(w, data)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func getStaticHandlers(storage *storage.Storage, server *settings.Server) (http.Handler, http.Handler) {
|
||||
box := rice.MustFindBox("../frontend/dist")
|
||||
handler := http.FileServer(box.HTTPBox())
|
||||
|
||||
index := handle(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
if r.Method != http.MethodGet {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
|
||||
w.Header().Set("x-xss-protection", "1; mode=block")
|
||||
return handleWithStaticData(w, r, d, box, "index.html", "text/html; charset=utf-8")
|
||||
}, "", storage, server)
|
||||
|
||||
static := handle(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
if r.Method != http.MethodGet {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
|
||||
if d.settings.Branding.Files != "" {
|
||||
if strings.HasPrefix(r.URL.Path, "img/") {
|
||||
path := filepath.Join(d.settings.Branding.Files, r.URL.Path)
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
http.ServeFile(w, r, path)
|
||||
return 0, nil
|
||||
}
|
||||
} else if r.URL.Path == "custom.css" && d.settings.Branding.Files != "" {
|
||||
http.ServeFile(w, r, filepath.Join(d.settings.Branding.Files, "custom.css"))
|
||||
return 0, nil
|
||||
}
|
||||
}
|
||||
|
||||
if !strings.HasSuffix(r.URL.Path, ".js") {
|
||||
handler.ServeHTTP(w, r)
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
return handleWithStaticData(w, r, d, box, r.URL.Path, "application/javascript; charset=utf-8")
|
||||
}, "/static/", storage, server)
|
||||
|
||||
return index, static
|
||||
}
|
||||
422
http/users.go
422
http/users.go
@@ -2,123 +2,85 @@ package http
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
fm "github.com/filebrowser/filebrowser"
|
||||
"github.com/filebrowser/filebrowser/v2/errors"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
type modifyRequest struct {
|
||||
What string `json:"what"` // Answer to: what data type?
|
||||
Which string `json:"which"` // Answer to: which field?
|
||||
}
|
||||
|
||||
type modifyUserRequest struct {
|
||||
modifyRequest
|
||||
Data *fm.User `json:"data"`
|
||||
Data *users.User `json:"data"`
|
||||
}
|
||||
|
||||
// usersHandler is the entry point of the users API. It's just a router
|
||||
// to send the request to its
|
||||
func usersHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
// If the user isn't admin and isn't making a PUT
|
||||
// request, then return forbidden.
|
||||
if !c.User.Admin && r.Method != http.MethodPut {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
return usersGetHandler(c, w, r)
|
||||
case http.MethodPost:
|
||||
return usersPostHandler(c, w, r)
|
||||
case http.MethodDelete:
|
||||
return usersDeleteHandler(c, w, r)
|
||||
case http.MethodPut:
|
||||
return usersPutHandler(c, w, r)
|
||||
}
|
||||
|
||||
return http.StatusNotImplemented, nil
|
||||
}
|
||||
|
||||
// getUserID returns the id from the user which is present
|
||||
// in the request url. If the url is invalid and doesn't
|
||||
// contain a valid ID, it returns an fm.Error.
|
||||
func getUserID(r *http.Request) (int, error) {
|
||||
// Obtains the ID in string from the URL and converts
|
||||
// it into an integer.
|
||||
sid := strings.TrimPrefix(r.URL.Path, "/")
|
||||
sid = strings.TrimSuffix(sid, "/")
|
||||
id, err := strconv.Atoi(sid)
|
||||
func getUserID(r *http.Request) (uint, error) {
|
||||
vars := mux.Vars(r)
|
||||
i, err := strconv.ParseUint(vars["id"], 10, 0)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, err
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return id, nil
|
||||
return uint(i), err
|
||||
}
|
||||
|
||||
// getUser returns the user which is present in the request
|
||||
// body. If the body is empty or the JSON is invalid, it
|
||||
// returns an fm.Error.
|
||||
func getUser(c *fm.Context, r *http.Request) (*fm.User, string, error) {
|
||||
// Checks if the request body is empty.
|
||||
func getUser(w http.ResponseWriter, r *http.Request) (*modifyUserRequest, error) {
|
||||
if r.Body == nil {
|
||||
return nil, "", fm.ErrEmptyRequest
|
||||
return nil, errors.ErrEmptyRequest
|
||||
}
|
||||
|
||||
// Parses the request body and checks if it's well formed.
|
||||
mod := &modifyUserRequest{}
|
||||
err := json.NewDecoder(r.Body).Decode(mod)
|
||||
req := &modifyUserRequest{}
|
||||
err := json.NewDecoder(r.Body).Decode(req)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Checks if the request type is right.
|
||||
if mod.What != "user" {
|
||||
return nil, "", fm.ErrWrongDataType
|
||||
if req.What != "user" {
|
||||
return nil, errors.ErrInvalidDataType
|
||||
}
|
||||
|
||||
mod.Data.FileSystem = c.NewFS(mod.Data.Scope)
|
||||
return mod.Data, mod.Which, nil
|
||||
return req, nil
|
||||
}
|
||||
|
||||
func usersGetHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
// Request for the default user data.
|
||||
if r.URL.Path == "/base" {
|
||||
return renderJSON(w, c.DefaultUser)
|
||||
}
|
||||
|
||||
// Request for the listing of users.
|
||||
if r.URL.Path == "/" {
|
||||
users, err := c.Store.Users.Gets(c.NewFS)
|
||||
func withSelfOrAdmin(fn handleFunc) handleFunc {
|
||||
return withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
id, err := getUserID(r)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
for _, u := range users {
|
||||
// Removes the user password so it won't
|
||||
// be sent to the front-end.
|
||||
u.Password = ""
|
||||
if d.user.ID != id && !d.user.Perm.Admin {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
sort.Slice(users, func(i, j int) bool {
|
||||
return users[i].ID < users[j].ID
|
||||
})
|
||||
d.raw = id
|
||||
return fn(w, r, d)
|
||||
})
|
||||
}
|
||||
|
||||
return renderJSON(w, users)
|
||||
}
|
||||
|
||||
id, err := getUserID(r)
|
||||
var usersGetHandler = withAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
users, err := d.store.Users.Gets(d.server.Root)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
u, err := c.Store.Users.Get(id, c.NewFS)
|
||||
if err == fm.ErrExist {
|
||||
for _, u := range users {
|
||||
u.Password = ""
|
||||
}
|
||||
|
||||
sort.Slice(users, func(i, j int) bool {
|
||||
return users[i].ID < users[j].ID
|
||||
})
|
||||
|
||||
return renderJSON(w, r, users)
|
||||
})
|
||||
|
||||
var userGetHandler = withSelfOrAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
u, err := d.store.Users.Get(d.server.Root, d.raw.(uint))
|
||||
if err == errors.ErrNotExist {
|
||||
return http.StatusNotFound, err
|
||||
}
|
||||
|
||||
@@ -127,257 +89,107 @@ func usersGetHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int
|
||||
}
|
||||
|
||||
u.Password = ""
|
||||
return renderJSON(w, u)
|
||||
}
|
||||
return renderJSON(w, r, u)
|
||||
})
|
||||
|
||||
func usersPostHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
if r.URL.Path != "/" {
|
||||
return http.StatusMethodNotAllowed, nil
|
||||
}
|
||||
|
||||
u, _, err := getUser(c, r)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, err
|
||||
}
|
||||
|
||||
// Checks if username isn't empty.
|
||||
if u.Username == "" {
|
||||
return http.StatusBadRequest, fm.ErrEmptyUsername
|
||||
}
|
||||
|
||||
// Checks if scope isn't empty.
|
||||
if u.Scope == "" {
|
||||
return http.StatusBadRequest, fm.ErrEmptyScope
|
||||
}
|
||||
|
||||
// Checks if password isn't empty.
|
||||
if u.Password == "" {
|
||||
return http.StatusBadRequest, fm.ErrEmptyPassword
|
||||
}
|
||||
|
||||
// Initialize rules if they're not initialized.
|
||||
if u.Rules == nil {
|
||||
u.Rules = []*fm.Rule{}
|
||||
}
|
||||
|
||||
// If the view mode is empty, initialize with the default one.
|
||||
if u.ViewMode == "" {
|
||||
u.ViewMode = c.DefaultUser.ViewMode
|
||||
}
|
||||
|
||||
// Initialize commands if not initialized.
|
||||
if u.Commands == nil {
|
||||
u.Commands = []string{}
|
||||
}
|
||||
|
||||
// It's a new user so the ID will be auto created.
|
||||
if u.ID != 0 {
|
||||
u.ID = 0
|
||||
}
|
||||
|
||||
// Checks if the scope exists.
|
||||
if code, err := checkFS(u.Scope); err != nil {
|
||||
return code, err
|
||||
}
|
||||
|
||||
// Hashes the password.
|
||||
pw, err := fm.HashPassword(u.Password)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
u.Password = pw
|
||||
u.ViewMode = fm.MosaicViewMode
|
||||
|
||||
// Saves the user to the database.
|
||||
err = c.Store.Users.Save(u)
|
||||
if err == fm.ErrExist {
|
||||
return http.StatusConflict, err
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
// Set the Location header and return.
|
||||
w.Header().Set("Location", "/settings/users/"+strconv.Itoa(u.ID))
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func checkFS(path string) (int, error) {
|
||||
info, err := os.Stat(path)
|
||||
|
||||
if err != nil {
|
||||
if !os.IsNotExist(err) {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
err = os.MkdirAll(path, 0666)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
if !info.IsDir() {
|
||||
return http.StatusBadRequest, errors.New("Scope is not a dir")
|
||||
}
|
||||
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func usersDeleteHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
if r.URL.Path == "/" {
|
||||
return http.StatusMethodNotAllowed, nil
|
||||
}
|
||||
|
||||
id, err := getUserID(r)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
// Deletes the user from the database.
|
||||
err = c.Store.Users.Delete(id)
|
||||
if err == fm.ErrNotExist {
|
||||
return http.StatusNotFound, fm.ErrNotExist
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
var userDeleteHandler = withSelfOrAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
err := d.store.Users.Delete(d.raw.(uint))
|
||||
if err == errors.ErrNotExist {
|
||||
return http.StatusNotFound, err
|
||||
}
|
||||
|
||||
return http.StatusOK, nil
|
||||
}
|
||||
})
|
||||
|
||||
func usersPutHandler(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
// New users should be created on /api/users.
|
||||
if r.URL.Path == "/" {
|
||||
return http.StatusMethodNotAllowed, nil
|
||||
}
|
||||
|
||||
// Gets the user ID from the URL and checks if it's valid.
|
||||
id, err := getUserID(r)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
// Checks if the user has permission to access this page.
|
||||
if !c.User.Admin && id != c.User.ID {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
// Gets the user from the request body.
|
||||
u, which, err := getUser(c, r)
|
||||
var userPostHandler = withAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
req, err := getUser(w, r)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, err
|
||||
}
|
||||
|
||||
// If we're updating the default user. Only for NoAuth
|
||||
// implementations. Used to change the viewMode.
|
||||
if id == 0 && c.NoAuth {
|
||||
c.DefaultUser.ViewMode = u.ViewMode
|
||||
return http.StatusOK, nil
|
||||
if len(req.Which) != 0 {
|
||||
return http.StatusBadRequest, nil
|
||||
}
|
||||
|
||||
// Updates the CSS and locale.
|
||||
if which == "partial" {
|
||||
c.User.CSS = u.CSS
|
||||
c.User.Locale = u.Locale
|
||||
c.User.ViewMode = u.ViewMode
|
||||
if req.Data.Password == "" {
|
||||
return http.StatusBadRequest, errors.ErrEmptyPassword
|
||||
}
|
||||
|
||||
req.Data.Password, err = users.HashPwd(req.Data.Password)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
userHome, err := d.settings.MakeUserDir(req.Data.Username, req.Data.Scope, d.server.Root)
|
||||
if err != nil {
|
||||
log.Printf("create user: failed to mkdir user home dir: [%s]", userHome)
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
req.Data.Scope = userHome
|
||||
log.Printf("user: %s, home dir: [%s].", req.Data.Username, userHome)
|
||||
|
||||
err = d.store.Users.Save(req.Data)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
w.Header().Set("Location", "/settings/users/"+strconv.FormatUint(uint64(req.Data.ID), 10))
|
||||
return http.StatusCreated, nil
|
||||
})
|
||||
|
||||
var userPutHandler = withSelfOrAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
req, err := getUser(w, r)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, err
|
||||
}
|
||||
|
||||
if req.Data.ID != d.raw.(uint) {
|
||||
return http.StatusBadRequest, nil
|
||||
}
|
||||
|
||||
if len(req.Which) == 1 && req.Which[0] == "all" {
|
||||
if !d.user.Perm.Admin {
|
||||
return http.StatusForbidden, err
|
||||
}
|
||||
|
||||
if req.Data.Password != "" {
|
||||
req.Data.Password, err = users.HashPwd(req.Data.Password)
|
||||
} else {
|
||||
var suser *users.User
|
||||
suser, err = d.store.Users.Get(d.server.Root, d.raw.(uint))
|
||||
req.Data.Password = suser.Password
|
||||
}
|
||||
|
||||
err = c.Store.Users.Update(c.User, "CSS", "Locale", "ViewMode")
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
return http.StatusOK, nil
|
||||
req.Which = []string{}
|
||||
}
|
||||
|
||||
// Updates the Password.
|
||||
if which == "password" {
|
||||
if u.Password == "" {
|
||||
return http.StatusBadRequest, fm.ErrEmptyPassword
|
||||
for k, v := range req.Which {
|
||||
if v == "password" {
|
||||
if !d.user.Perm.Admin && d.user.LockPassword {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
req.Data.Password, err = users.HashPwd(req.Data.Password)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
}
|
||||
|
||||
if id == c.User.ID && c.User.LockPassword {
|
||||
if !d.user.Perm.Admin && (v == "scope" || v == "perm" || v == "username") {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
c.User.Password, err = fm.HashPassword(u.Password)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
err = c.Store.Users.Update(c.User, "Password")
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
return http.StatusOK, nil
|
||||
req.Which[k] = strings.Title(v)
|
||||
}
|
||||
|
||||
// If can only be all.
|
||||
if which != "all" {
|
||||
return http.StatusBadRequest, fm.ErrInvalidUpdateField
|
||||
}
|
||||
|
||||
// Checks if username isn't empty.
|
||||
if u.Username == "" {
|
||||
return http.StatusBadRequest, fm.ErrEmptyUsername
|
||||
}
|
||||
|
||||
// Checks if filesystem isn't empty.
|
||||
if u.Scope == "" {
|
||||
return http.StatusBadRequest, fm.ErrEmptyScope
|
||||
}
|
||||
|
||||
// Checks if the scope exists.
|
||||
if code, err := checkFS(u.Scope); err != nil {
|
||||
return code, err
|
||||
}
|
||||
|
||||
// Initialize rules if they're not initialized.
|
||||
if u.Rules == nil {
|
||||
u.Rules = []*fm.Rule{}
|
||||
}
|
||||
|
||||
// Initialize commands if not initialized.
|
||||
if u.Commands == nil {
|
||||
u.Commands = []string{}
|
||||
}
|
||||
|
||||
// Gets the current saved user from the in-memory map.
|
||||
suser, err := c.Store.Users.Get(id, c.NewFS)
|
||||
if err == fm.ErrNotExist {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
u.ID = id
|
||||
|
||||
// Changes the password if the request wants it.
|
||||
if u.Password != "" {
|
||||
pw, err := fm.HashPassword(u.Password)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
u.Password = pw
|
||||
} else {
|
||||
u.Password = suser.Password
|
||||
}
|
||||
|
||||
// Updates the whole User struct because we always are supposed
|
||||
// to send a new entire object.
|
||||
err = c.Store.Users.Update(u)
|
||||
err = d.store.Users.Update(req.Data, req.Which...)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
return http.StatusOK, nil
|
||||
}
|
||||
})
|
||||
|
||||
59
http/utils.go
Normal file
59
http/utils.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/errors"
|
||||
)
|
||||
|
||||
func renderJSON(w http.ResponseWriter, r *http.Request, data interface{}) (int, error) {
|
||||
marsh, err := json.Marshal(data)
|
||||
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
if _, err := w.Write(marsh); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func errToStatus(err error) int {
|
||||
switch {
|
||||
case err == nil:
|
||||
return http.StatusOK
|
||||
case os.IsPermission(err):
|
||||
return http.StatusForbidden
|
||||
case os.IsNotExist(err), err == errors.ErrNotExist:
|
||||
return http.StatusNotFound
|
||||
case os.IsExist(err), err == errors.ErrExist:
|
||||
return http.StatusConflict
|
||||
default:
|
||||
return http.StatusInternalServerError
|
||||
}
|
||||
}
|
||||
|
||||
// This is an addaptation if http.StripPrefix in which we don't
|
||||
// return 404 if the page doesn't have the needed prefix.
|
||||
func stripPrefix(prefix string, h http.Handler) http.Handler {
|
||||
if prefix == "" {
|
||||
return h
|
||||
}
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := strings.TrimPrefix(r.URL.Path, prefix)
|
||||
r2 := new(http.Request)
|
||||
*r2 = *r
|
||||
r2.URL = new(url.URL)
|
||||
*r2.URL = *r.URL
|
||||
r2.URL.Path = p
|
||||
h.ServeHTTP(w, r2)
|
||||
})
|
||||
}
|
||||
@@ -1,339 +0,0 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"mime"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
fm "github.com/filebrowser/filebrowser"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
}
|
||||
|
||||
var (
|
||||
cmdNotImplemented = []byte("Command not implemented.")
|
||||
cmdNotAllowed = []byte("Command not allowed.")
|
||||
)
|
||||
|
||||
// command handles the requests for VCS related commands: git, svn and mercurial
|
||||
func command(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
// Upgrades the connection to a websocket and checks for fm.Errors.
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
var (
|
||||
message []byte
|
||||
command []string
|
||||
)
|
||||
|
||||
// Starts an infinite loop until a valid command is captured.
|
||||
for {
|
||||
_, message, err = conn.ReadMessage()
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
command = strings.Split(string(message), " ")
|
||||
if len(command) != 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Check if the command is allowed
|
||||
allowed := false
|
||||
|
||||
for _, cmd := range c.User.Commands {
|
||||
if cmd == command[0] {
|
||||
allowed = true
|
||||
}
|
||||
}
|
||||
|
||||
if !allowed {
|
||||
err = conn.WriteMessage(websocket.BinaryMessage, cmdNotAllowed)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// Check if the program is talled is installed on the computer.
|
||||
if _, err = exec.LookPath(command[0]); err != nil {
|
||||
err = conn.WriteMessage(websocket.BinaryMessage, cmdNotImplemented)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
return http.StatusNotImplemented, nil
|
||||
}
|
||||
|
||||
// Gets the path and initializes a buffer.
|
||||
path := c.User.Scope + "/" + r.URL.Path
|
||||
path = filepath.Clean(path)
|
||||
buff := new(bytes.Buffer)
|
||||
|
||||
// Sets up the command executation.
|
||||
cmd := exec.Command(command[0], command[1:]...)
|
||||
cmd.Dir = path
|
||||
cmd.Stderr = buff
|
||||
cmd.Stdout = buff
|
||||
|
||||
// Starts the command and checks for fm.Errors.
|
||||
err = cmd.Start()
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
// Set a 'done' variable to check whetever the command has already finished
|
||||
// running or not. This verification is done using a goroutine that uses the
|
||||
// method .Wait() from the command.
|
||||
done := false
|
||||
go func() {
|
||||
err = cmd.Wait()
|
||||
done = true
|
||||
}()
|
||||
|
||||
// Function to print the current information on the buffer to the connection.
|
||||
print := func() error {
|
||||
by := buff.Bytes()
|
||||
if len(by) > 0 {
|
||||
err = conn.WriteMessage(websocket.TextMessage, by)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// While the command hasn't finished running, continue sending the output
|
||||
// to the client in intervals of 100 milliseconds.
|
||||
for !done {
|
||||
if err = print(); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
|
||||
// After the command is done executing, send the output one more time to the
|
||||
// browser to make sure it gets the latest information.
|
||||
if err = print(); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
var (
|
||||
typeRegexp = regexp.MustCompile(`type:(\w+)`)
|
||||
)
|
||||
|
||||
type condition func(path string) bool
|
||||
|
||||
type searchOptions struct {
|
||||
CaseInsensitive bool
|
||||
Conditions []condition
|
||||
Terms []string
|
||||
}
|
||||
|
||||
func extensionCondition(extension string) condition {
|
||||
return func(path string) bool {
|
||||
return filepath.Ext(path) == "."+extension
|
||||
}
|
||||
}
|
||||
|
||||
func imageCondition(path string) bool {
|
||||
extension := filepath.Ext(path)
|
||||
mimetype := mime.TypeByExtension(extension)
|
||||
|
||||
return strings.HasPrefix(mimetype, "image")
|
||||
}
|
||||
|
||||
func audioCondition(path string) bool {
|
||||
extension := filepath.Ext(path)
|
||||
mimetype := mime.TypeByExtension(extension)
|
||||
|
||||
return strings.HasPrefix(mimetype, "audio")
|
||||
}
|
||||
|
||||
func videoCondition(path string) bool {
|
||||
extension := filepath.Ext(path)
|
||||
mimetype := mime.TypeByExtension(extension)
|
||||
|
||||
return strings.HasPrefix(mimetype, "video")
|
||||
}
|
||||
|
||||
func parseSearch(value string) *searchOptions {
|
||||
opts := &searchOptions{
|
||||
CaseInsensitive: strings.Contains(value, "case:insensitive"),
|
||||
Conditions: []condition{},
|
||||
Terms: []string{},
|
||||
}
|
||||
|
||||
// removes the options from the value
|
||||
value = strings.Replace(value, "case:insensitive", "", -1)
|
||||
value = strings.Replace(value, "case:sensitive", "", -1)
|
||||
value = strings.TrimSpace(value)
|
||||
|
||||
types := typeRegexp.FindAllStringSubmatch(value, -1)
|
||||
for _, t := range types {
|
||||
if len(t) == 1 {
|
||||
continue
|
||||
}
|
||||
|
||||
switch t[1] {
|
||||
case "image":
|
||||
opts.Conditions = append(opts.Conditions, imageCondition)
|
||||
case "audio", "music":
|
||||
opts.Conditions = append(opts.Conditions, audioCondition)
|
||||
case "video":
|
||||
opts.Conditions = append(opts.Conditions, videoCondition)
|
||||
default:
|
||||
opts.Conditions = append(opts.Conditions, extensionCondition(t[1]))
|
||||
}
|
||||
}
|
||||
|
||||
if len(types) > 0 {
|
||||
// Remove the fields from the search value.
|
||||
value = typeRegexp.ReplaceAllString(value, "")
|
||||
}
|
||||
|
||||
// If it's canse insensitive, put everything in lowercase.
|
||||
if opts.CaseInsensitive {
|
||||
value = strings.ToLower(value)
|
||||
}
|
||||
|
||||
// Remove the spaces from the search value.
|
||||
value = strings.TrimSpace(value)
|
||||
|
||||
if value == "" {
|
||||
return opts
|
||||
}
|
||||
|
||||
// if the value starts with " and finishes what that character, we will
|
||||
// only search for that term
|
||||
if value[0] == '"' && value[len(value)-1] == '"' {
|
||||
unique := strings.TrimPrefix(value, "\"")
|
||||
unique = strings.TrimSuffix(unique, "\"")
|
||||
|
||||
opts.Terms = []string{unique}
|
||||
return opts
|
||||
}
|
||||
|
||||
opts.Terms = strings.Split(value, " ")
|
||||
return opts
|
||||
}
|
||||
|
||||
// search searches for a file or directory.
|
||||
func search(c *fm.Context, w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
// Upgrades the connection to a websocket and checks for fm.Errors.
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
var (
|
||||
value string
|
||||
search *searchOptions
|
||||
message []byte
|
||||
)
|
||||
|
||||
// Starts an infinite loop until a valid command is captured.
|
||||
for {
|
||||
_, message, err = conn.ReadMessage()
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
if len(message) != 0 {
|
||||
value = string(message)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
search = parseSearch(value)
|
||||
scope := strings.TrimPrefix(r.URL.Path, "/")
|
||||
scope = "/" + scope
|
||||
scope = c.User.Scope + scope
|
||||
scope = strings.Replace(scope, "\\", "/", -1)
|
||||
scope = filepath.Clean(scope)
|
||||
|
||||
err = filepath.Walk(scope, func(path string, f os.FileInfo, err error) error {
|
||||
if search.CaseInsensitive {
|
||||
path = strings.ToLower(path)
|
||||
}
|
||||
|
||||
path = strings.TrimPrefix(path, scope)
|
||||
path = strings.TrimPrefix(path, "/")
|
||||
path = strings.Replace(path, "\\", "/", -1)
|
||||
|
||||
// Only execute if there are conditions to meet.
|
||||
if len(search.Conditions) > 0 {
|
||||
match := false
|
||||
|
||||
for _, t := range search.Conditions {
|
||||
if t(path) {
|
||||
match = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// If doesn't meet the condition, go to the next.
|
||||
if !match {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
if len(search.Terms) > 0 {
|
||||
is := false
|
||||
|
||||
// Checks if matches the terms and if it is allowed.
|
||||
for _, term := range search.Terms {
|
||||
if is {
|
||||
break
|
||||
}
|
||||
|
||||
if strings.Contains(path, term) {
|
||||
if !c.User.Allowed(path) {
|
||||
return nil
|
||||
}
|
||||
|
||||
is = true
|
||||
}
|
||||
}
|
||||
|
||||
if !is {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
response, _ := json.Marshal(map[string]interface{}{
|
||||
"dir": f.IsDir(),
|
||||
"path": path,
|
||||
})
|
||||
|
||||
return conn.WriteMessage(websocket.TextMessage, response)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
return 0, nil
|
||||
}
|
||||
12
main.go
Normal file
12
main.go
Normal file
@@ -0,0 +1,12 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/cmd"
|
||||
)
|
||||
|
||||
func main() {
|
||||
runtime.GOMAXPROCS(runtime.NumCPU())
|
||||
cmd.Execute()
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"name": "filebrowser",
|
||||
"author": "File Browser contributors",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"filebrowser-frontend": "1.0.4"
|
||||
}
|
||||
}
|
||||
21
publish.sh
21
publish.sh
@@ -1,21 +0,0 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
echo "Building assets"
|
||||
./build.sh
|
||||
|
||||
echo "Updating version number to $1..."
|
||||
sed -i "s|(untracked)|$1|g" filebrowser.go
|
||||
git add -A
|
||||
git commit -m "chore: version $1"
|
||||
git tag "v$1"
|
||||
git push
|
||||
git push --tags
|
||||
|
||||
echo "Commiting untracked version notice..."
|
||||
sed -i "s|$1|(untracked)|g" filebrowser.go
|
||||
git add -A
|
||||
git commit -m "chore: setting untracked version [ci skip]"
|
||||
git push
|
||||
|
||||
echo "Done!"
|
||||
@@ -1 +0,0 @@
|
||||
ee6a18b32d66a98bab93e7c2dadc6b60b0d53495
|
||||
44
rules/rules.go
Normal file
44
rules/rules.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Checker is a Rules checker.
|
||||
type Checker interface {
|
||||
Check(path string) bool
|
||||
}
|
||||
|
||||
// Rule is a allow/disallow rule.
|
||||
type Rule struct {
|
||||
Regex bool `json:"regex"`
|
||||
Allow bool `json:"allow"`
|
||||
Path string `json:"path"`
|
||||
Regexp *Regexp `json:"regexp"`
|
||||
}
|
||||
|
||||
// Matches matches a path against a rule.
|
||||
func (r *Rule) Matches(path string) bool {
|
||||
if r.Regex {
|
||||
return r.Regexp.MatchString(path)
|
||||
}
|
||||
|
||||
return strings.HasPrefix(path, r.Path)
|
||||
}
|
||||
|
||||
// Regexp is a wrapper to the native regexp type where we
|
||||
// save the raw expression.
|
||||
type Regexp struct {
|
||||
Raw string `json:"raw"`
|
||||
regexp *regexp.Regexp
|
||||
}
|
||||
|
||||
// MatchString checks if a string matches the regexp.
|
||||
func (r *Regexp) MatchString(s string) bool {
|
||||
if r.regexp == nil {
|
||||
r.regexp = regexp.MustCompile(r.Raw)
|
||||
}
|
||||
|
||||
return r.regexp.MatchString(s)
|
||||
}
|
||||
34
runner/parser.go
Normal file
34
runner/parser.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package runner
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/mholt/caddy"
|
||||
)
|
||||
|
||||
// ParseCommand parses the command taking in account if the current
|
||||
// instance uses a shell to run the commands or just calls the binary
|
||||
// directyly.
|
||||
func ParseCommand(s *settings.Settings, raw string) ([]string, error) {
|
||||
command := []string{}
|
||||
|
||||
if len(s.Shell) == 0 {
|
||||
cmd, args, err := caddy.SplitCommandAndArgs(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, err = exec.LookPath(cmd)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
command = append(command, cmd)
|
||||
command = append(command, args...)
|
||||
} else {
|
||||
command = append(s.Shell, raw)
|
||||
}
|
||||
|
||||
return command, nil
|
||||
}
|
||||
81
runner/runner.go
Normal file
81
runner/runner.go
Normal file
@@ -0,0 +1,81 @@
|
||||
package runner
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
// Runner is a commands runner.
|
||||
type Runner struct {
|
||||
*settings.Settings
|
||||
}
|
||||
|
||||
// RunHook runs the hooks for the before and after event.
|
||||
func (r *Runner) RunHook(fn func() error, evt, path, dst string, user *users.User) error {
|
||||
path = user.FullPath(path)
|
||||
dst = user.FullPath(dst)
|
||||
|
||||
if val, ok := r.Commands["before_"+evt]; ok {
|
||||
for _, command := range val {
|
||||
err := r.exec(command, "before_"+evt, path, dst, user)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
err := fn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if val, ok := r.Commands["after_"+evt]; ok {
|
||||
for _, command := range val {
|
||||
err := r.exec(command, "after_"+evt, path, dst, user)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Runner) exec(raw, evt, path, dst string, user *users.User) error {
|
||||
blocking := true
|
||||
|
||||
if strings.HasSuffix(raw, "&") {
|
||||
blocking = false
|
||||
raw = strings.TrimSpace(strings.TrimSuffix(raw, "&"))
|
||||
}
|
||||
|
||||
command, err := ParseCommand(r.Settings, raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cmd := exec.Command(command[0], command[1:]...)
|
||||
cmd.Env = append(os.Environ(), fmt.Sprintf("FILE=%s", path))
|
||||
cmd.Env = append(cmd.Env, fmt.Sprintf("SCOPE=%s", user.Scope))
|
||||
cmd.Env = append(cmd.Env, fmt.Sprintf("TRIGGER=%s", evt))
|
||||
cmd.Env = append(cmd.Env, fmt.Sprintf("USERNAME=%s", user.Username))
|
||||
cmd.Env = append(cmd.Env, fmt.Sprintf("DESTINATION=%s", dst))
|
||||
|
||||
cmd.Stdin = os.Stdin
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
|
||||
if !blocking {
|
||||
log.Printf("[INFO] Nonblocking Command: \"%s\"", strings.Join(command, " "))
|
||||
return cmd.Start()
|
||||
}
|
||||
|
||||
log.Printf("[INFO] Blocking Command: \"%s\"", strings.Join(command, " "))
|
||||
return cmd.Run()
|
||||
}
|
||||
102
search/conditions.go
Normal file
102
search/conditions.go
Normal file
@@ -0,0 +1,102 @@
|
||||
package search
|
||||
|
||||
import (
|
||||
"mime"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
typeRegexp = regexp.MustCompile(`type:(\w+)`)
|
||||
)
|
||||
|
||||
type condition func(path string) bool
|
||||
|
||||
func extensionCondition(extension string) condition {
|
||||
return func(path string) bool {
|
||||
return filepath.Ext(path) == "."+extension
|
||||
}
|
||||
}
|
||||
|
||||
func imageCondition(path string) bool {
|
||||
extension := filepath.Ext(path)
|
||||
mimetype := mime.TypeByExtension(extension)
|
||||
|
||||
return strings.HasPrefix(mimetype, "image")
|
||||
}
|
||||
|
||||
func audioCondition(path string) bool {
|
||||
extension := filepath.Ext(path)
|
||||
mimetype := mime.TypeByExtension(extension)
|
||||
|
||||
return strings.HasPrefix(mimetype, "audio")
|
||||
}
|
||||
|
||||
func videoCondition(path string) bool {
|
||||
extension := filepath.Ext(path)
|
||||
mimetype := mime.TypeByExtension(extension)
|
||||
|
||||
return strings.HasPrefix(mimetype, "video")
|
||||
}
|
||||
|
||||
func parseSearch(value string) *searchOptions {
|
||||
opts := &searchOptions{
|
||||
CaseSensitive: strings.Contains(value, "case:sensitive"),
|
||||
Conditions: []condition{},
|
||||
Terms: []string{},
|
||||
}
|
||||
|
||||
// removes the options from the value
|
||||
value = strings.Replace(value, "case:insensitive", "", -1)
|
||||
value = strings.Replace(value, "case:sensitive", "", -1)
|
||||
value = strings.TrimSpace(value)
|
||||
|
||||
types := typeRegexp.FindAllStringSubmatch(value, -1)
|
||||
for _, t := range types {
|
||||
if len(t) == 1 {
|
||||
continue
|
||||
}
|
||||
|
||||
switch t[1] {
|
||||
case "image":
|
||||
opts.Conditions = append(opts.Conditions, imageCondition)
|
||||
case "audio", "music":
|
||||
opts.Conditions = append(opts.Conditions, audioCondition)
|
||||
case "video":
|
||||
opts.Conditions = append(opts.Conditions, videoCondition)
|
||||
default:
|
||||
opts.Conditions = append(opts.Conditions, extensionCondition(t[1]))
|
||||
}
|
||||
}
|
||||
|
||||
if len(types) > 0 {
|
||||
// Remove the fields from the search value.
|
||||
value = typeRegexp.ReplaceAllString(value, "")
|
||||
}
|
||||
|
||||
// If it's canse insensitive, put everything in lowercase.
|
||||
if !opts.CaseSensitive {
|
||||
value = strings.ToLower(value)
|
||||
}
|
||||
|
||||
// Remove the spaces from the search value.
|
||||
value = strings.TrimSpace(value)
|
||||
|
||||
if value == "" {
|
||||
return opts
|
||||
}
|
||||
|
||||
// if the value starts with " and finishes what that character, we will
|
||||
// only search for that term
|
||||
if value[0] == '"' && value[len(value)-1] == '"' {
|
||||
unique := strings.TrimPrefix(value, "\"")
|
||||
unique = strings.TrimSuffix(unique, "\"")
|
||||
|
||||
opts.Terms = []string{unique}
|
||||
return opts
|
||||
}
|
||||
|
||||
opts.Terms = strings.Split(value, " ")
|
||||
return opts
|
||||
}
|
||||
69
search/search.go
Normal file
69
search/search.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package search
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/rules"
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
type searchOptions struct {
|
||||
CaseSensitive bool
|
||||
Conditions []condition
|
||||
Terms []string
|
||||
}
|
||||
|
||||
// Search searches for a query in a fs.
|
||||
func Search(fs afero.Fs, scope, query string, checker rules.Checker, found func(path string, f os.FileInfo) error) error {
|
||||
search := parseSearch(query)
|
||||
|
||||
scope = strings.Replace(scope, "\\", "/", -1)
|
||||
scope = strings.TrimPrefix(scope, "/")
|
||||
scope = strings.TrimSuffix(scope, "/")
|
||||
scope = "/" + scope + "/"
|
||||
|
||||
return afero.Walk(fs, scope, func(originalPath string, f os.FileInfo, err error) error {
|
||||
originalPath = strings.Replace(originalPath, "\\", "/", -1)
|
||||
originalPath = strings.TrimPrefix(originalPath, "/")
|
||||
originalPath = "/" + originalPath
|
||||
path := originalPath
|
||||
|
||||
if path == scope {
|
||||
return nil
|
||||
}
|
||||
|
||||
if !checker.Check(path) {
|
||||
return nil
|
||||
}
|
||||
|
||||
if !search.CaseSensitive {
|
||||
path = strings.ToLower(path)
|
||||
}
|
||||
|
||||
if len(search.Conditions) > 0 {
|
||||
match := false
|
||||
|
||||
for _, t := range search.Conditions {
|
||||
if t(path) {
|
||||
match = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !match {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
if len(search.Terms) > 0 {
|
||||
for _, term := range search.Terms {
|
||||
if strings.Contains(path, term) {
|
||||
return found(strings.TrimPrefix(originalPath, scope), f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
8
settings/branding.go
Normal file
8
settings/branding.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package settings
|
||||
|
||||
// Branding contains the branding settings of the app.
|
||||
type Branding struct {
|
||||
Name string `json:"name"`
|
||||
DisableExternal bool `json:"disableExternal"`
|
||||
Files string `json:"files"`
|
||||
}
|
||||
27
settings/defaults.go
Normal file
27
settings/defaults.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package settings
|
||||
|
||||
import (
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
// UserDefaults is a type that holds the default values
|
||||
// for some fields on User.
|
||||
type UserDefaults struct {
|
||||
Scope string `json:"scope"`
|
||||
Locale string `json:"locale"`
|
||||
ViewMode users.ViewMode `json:"viewMode"`
|
||||
Sorting files.Sorting `json:"sorting"`
|
||||
Perm users.Permissions `json:"perm"`
|
||||
Commands []string `json:"commands"`
|
||||
}
|
||||
|
||||
// Apply applies the default options to a user.
|
||||
func (d *UserDefaults) Apply(u *users.User) {
|
||||
u.Scope = d.Scope
|
||||
u.Locale = d.Locale
|
||||
u.ViewMode = d.ViewMode
|
||||
u.Perm = d.Perm
|
||||
u.Sorting = d.Sorting
|
||||
u.Commands = d.Commands
|
||||
}
|
||||
75
settings/dir.go
Normal file
75
settings/dir.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package settings
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
var (
|
||||
invalidFilenameChars = regexp.MustCompile(`[^0-9A-Za-z@_\-.]`)
|
||||
|
||||
dashes = regexp.MustCompile(`[\-]+`)
|
||||
)
|
||||
|
||||
// MakeUserDir makes the user directory according to settings.
|
||||
func (settings *Settings) MakeUserDir(username, userScope, serverRoot string) (string, error) {
|
||||
var err error
|
||||
userScope = strings.TrimSpace(userScope)
|
||||
if userScope == "" || userScope == "./" {
|
||||
userScope = "."
|
||||
}
|
||||
|
||||
if !settings.CreateUserDir {
|
||||
return userScope, nil
|
||||
}
|
||||
|
||||
fs := afero.NewBasePathFs(afero.NewOsFs(), serverRoot)
|
||||
|
||||
// Use the default auto create logic only if specific scope is not the default scope
|
||||
if userScope != settings.Defaults.Scope {
|
||||
// Try create the dir, for example: settings.Defaults.Scope == "." and userScope == "./foo"
|
||||
if userScope != "." {
|
||||
err = fs.MkdirAll(userScope, os.ModePerm)
|
||||
if err != nil {
|
||||
log.Printf("create user: failed to mkdir user home dir: [%s]", userScope)
|
||||
}
|
||||
}
|
||||
return userScope, err
|
||||
}
|
||||
|
||||
// Clean username first
|
||||
username = cleanUsername(username)
|
||||
if username == "" || username == "-" || username == "." {
|
||||
log.Printf("create user: invalid user for home dir creation: [%s]", username)
|
||||
return "", errors.New("invalid user for home dir creation")
|
||||
}
|
||||
|
||||
// Create default user dir
|
||||
userHomeBase := settings.Defaults.Scope + string(os.PathSeparator) + "users"
|
||||
userHome := userHomeBase + string(os.PathSeparator) + username
|
||||
err = fs.MkdirAll(userHome, os.ModePerm)
|
||||
if err != nil {
|
||||
log.Printf("create user: failed to mkdir user home dir: [%s]", userHome)
|
||||
} else {
|
||||
log.Printf("create user: mkdir user home dir: [%s] successfully.", userHome)
|
||||
}
|
||||
return userHome, err
|
||||
}
|
||||
|
||||
func cleanUsername(s string) string {
|
||||
// Remove any trailing space to avoid ending on -
|
||||
s = strings.Trim(s, " ")
|
||||
s = strings.Replace(s, "..", "", -1)
|
||||
|
||||
// Replace all characters which not in the list `0-9A-Za-z@_\-.` with a dash
|
||||
s = invalidFilenameChars.ReplaceAllString(s, "-")
|
||||
|
||||
// Remove any multiple dashes caused by replacements above
|
||||
s = dashes.ReplaceAllString(s, "-")
|
||||
return s
|
||||
}
|
||||
57
settings/settings.go
Normal file
57
settings/settings.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package settings
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"strings"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/rules"
|
||||
)
|
||||
|
||||
// AuthMethod describes an authentication method.
|
||||
type AuthMethod string
|
||||
|
||||
// Settings contain the main settings of the application.
|
||||
type Settings struct {
|
||||
Key []byte `json:"key"`
|
||||
Signup bool `json:"signup"`
|
||||
CreateUserDir bool `json:"createUserDir"`
|
||||
Defaults UserDefaults `json:"defaults"`
|
||||
AuthMethod AuthMethod `json:"authMethod"`
|
||||
Branding Branding `json:"branding"`
|
||||
Commands map[string][]string `json:"commands"`
|
||||
Shell []string `json:"shell"`
|
||||
Rules []rules.Rule `json:"rules"`
|
||||
}
|
||||
|
||||
// GetRules implements rules.Provider.
|
||||
func (s *Settings) GetRules() []rules.Rule {
|
||||
return s.Rules
|
||||
}
|
||||
|
||||
// Server specific settings.
|
||||
type Server struct {
|
||||
Root string `json:"root"`
|
||||
BaseURL string `json:"baseURL"`
|
||||
TLSKey string `json:"tlsKey"`
|
||||
TLSCert string `json:"tlsCert"`
|
||||
Port string `json:"port"`
|
||||
Address string `json:"address"`
|
||||
Log string `json:"log"`
|
||||
}
|
||||
|
||||
// Clean cleans any variables that might need cleaning.
|
||||
func (s *Server) Clean() {
|
||||
s.BaseURL = strings.TrimSuffix(s.BaseURL, "/")
|
||||
}
|
||||
|
||||
// GenerateKey generates a key of 256 bits.
|
||||
func GenerateKey() ([]byte, error) {
|
||||
b := make([]byte, 64)
|
||||
_, err := rand.Read(b)
|
||||
// Note that err == nil only if we read len(b) bytes.
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return b, nil
|
||||
}
|
||||
97
settings/storage.go
Normal file
97
settings/storage.go
Normal file
@@ -0,0 +1,97 @@
|
||||
package settings
|
||||
|
||||
import (
|
||||
"github.com/filebrowser/filebrowser/v2/errors"
|
||||
"github.com/filebrowser/filebrowser/v2/rules"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
// StorageBackend is a settings storage backend.
|
||||
type StorageBackend interface {
|
||||
Get() (*Settings, error)
|
||||
Save(*Settings) error
|
||||
GetServer() (*Server, error)
|
||||
SaveServer(*Server) error
|
||||
}
|
||||
|
||||
// Storage is a settings storage.
|
||||
type Storage struct {
|
||||
back StorageBackend
|
||||
}
|
||||
|
||||
// NewStorage creates a settings storage from a backend.
|
||||
func NewStorage(back StorageBackend) *Storage {
|
||||
return &Storage{back: back}
|
||||
}
|
||||
|
||||
// Get returns the settings for the current instance.
|
||||
func (s *Storage) Get() (*Settings, error) {
|
||||
return s.back.Get()
|
||||
}
|
||||
|
||||
var defaultEvents = []string{
|
||||
"save",
|
||||
"copy",
|
||||
"rename",
|
||||
"upload",
|
||||
"delete",
|
||||
}
|
||||
|
||||
// Save saves the settings for the current instance.
|
||||
func (s *Storage) Save(set *Settings) error {
|
||||
if len(set.Key) == 0 {
|
||||
return errors.ErrEmptyKey
|
||||
}
|
||||
|
||||
if set.Defaults.Locale == "" {
|
||||
set.Defaults.Locale = "en"
|
||||
}
|
||||
|
||||
if set.Defaults.Commands == nil {
|
||||
set.Defaults.Commands = []string{}
|
||||
}
|
||||
|
||||
if set.Defaults.ViewMode == "" {
|
||||
set.Defaults.ViewMode = users.MosaicViewMode
|
||||
}
|
||||
|
||||
if set.Rules == nil {
|
||||
set.Rules = []rules.Rule{}
|
||||
}
|
||||
|
||||
if set.Shell == nil {
|
||||
set.Shell = []string{}
|
||||
}
|
||||
|
||||
if set.Commands == nil {
|
||||
set.Commands = map[string][]string{}
|
||||
}
|
||||
|
||||
for _, event := range defaultEvents {
|
||||
if _, ok := set.Commands["before_"+event]; !ok {
|
||||
set.Commands["before_"+event] = []string{}
|
||||
}
|
||||
|
||||
if _, ok := set.Commands["after_"+event]; !ok {
|
||||
set.Commands["after_"+event] = []string{}
|
||||
}
|
||||
}
|
||||
|
||||
err := s.back.Save(set)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetServer wraps StorageBackend.GetServer.
|
||||
func (s *Storage) GetServer() (*Server, error) {
|
||||
return s.back.GetServer()
|
||||
}
|
||||
|
||||
// SaveServer wraps StorageBackend.SaveServer and adds some verification.
|
||||
func (s *Storage) SaveServer(ser *Server) error {
|
||||
ser.Clean()
|
||||
return s.back.SaveServer(ser)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user