Compare commits
69 Commits
f4e6eb56c8
...
feature/fr
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc7b70e039 | ||
|
|
873b4a9d3a | ||
|
|
596eb8faea | ||
|
|
0cd6e837fc | ||
|
|
be63fcbc37 | ||
|
|
3f252a8abd | ||
|
|
0740072a60 | ||
|
|
ff752985c6 | ||
|
|
feb5122843 | ||
|
|
0260a03e1b | ||
|
|
a88e4d7274 | ||
|
|
7d99a4852b | ||
|
|
e59e7ca4c8 | ||
|
|
b0b765b8fa | ||
|
|
d861e0cd7d | ||
|
|
b2b1fbaf65 | ||
|
|
d1491b8d19 | ||
|
|
85e8668e34 | ||
|
|
a0a9584a4d | ||
|
|
737797f6dd | ||
|
|
1d1a469fe0 | ||
|
|
227256e0e0 | ||
|
|
5060c84f28 | ||
|
|
903b7e6e5a | ||
| c8b7d6e09c | |||
|
|
507b5f0e49 | ||
|
|
ec81d3228b | ||
|
|
8111aaf672 | ||
|
|
66b29b96ee | ||
|
|
86fb222d18 | ||
|
|
08b1a055a4 | ||
|
|
8f2193bed2 | ||
|
|
ed4a091d6e | ||
|
|
ccd8bc7aa1 | ||
|
|
b0c11c7c67 | ||
|
|
3354154b87 | ||
|
|
1233f3b736 | ||
|
|
b17d111c5d | ||
|
|
9447b64a76 | ||
|
|
6cd37d6758 | ||
|
|
6a88e401f6 | ||
|
|
30e500ec44 | ||
|
|
e758452509 | ||
|
|
9c139d6007 | ||
| ce404670d6 | |||
|
|
5668f465bb | ||
| f9c1cac50f | |||
|
|
5e0ab960f9 | ||
|
|
75a3777cb0 | ||
|
|
d33f4f103f | ||
|
|
a7524ab076 | ||
|
|
1c051f9502 | ||
|
|
81fbf8281f | ||
|
|
8875122e1b | ||
|
|
65d40c1e83 | ||
|
|
d2b842d933 | ||
|
|
34ebfaddbc | ||
| efdb47a117 | |||
|
|
5210c64c5d | ||
|
|
23c6bc4fd0 | ||
|
|
bbc6977e73 | ||
| 968911e489 | |||
|
|
c79ef265db | ||
|
|
0374d63efe | ||
|
|
06cabb0e18 | ||
|
|
051951dc44 | ||
|
|
edbcdaeff4 | ||
|
|
27173c01da | ||
| 6b73b64a3a |
140
.github/workflows/test.yml
vendored
140
.github/workflows/test.yml
vendored
@@ -16,34 +16,8 @@ jobs:
|
||||
# the workflow DRY. The composite action performs checkout, cache restore and
|
||||
# toolchain setup.
|
||||
|
||||
verify-generated-code:
|
||||
# no need to depend on a separate setup job; the composite action runs in
|
||||
# this job and restores caches/toolchain here.
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Rust, checkout and restore caches
|
||||
uses: ./.github/actions/setup-rust
|
||||
|
||||
- name: generate entities from migration files
|
||||
run: |
|
||||
cd apps/cli
|
||||
cargo run -- db:migrate_and_generate --output-path ../../public/database/src/generated/entities
|
||||
- name: Check for uncommitted changes in /generated/
|
||||
run: |
|
||||
if [[ -n $(git status --porcelain | grep '^ M .*\/generated\/') ]]; then
|
||||
echo "Generated code is not up to date. Please run the code generation locally and commit the changes."
|
||||
git status --porcelain | grep '^ M .*\/generated\/'
|
||||
exit 1
|
||||
else
|
||||
echo "Generated code is up to date."
|
||||
fi
|
||||
|
||||
test:
|
||||
needs: frontend-build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
@@ -54,10 +28,19 @@ jobs:
|
||||
- name: Setup Rust, checkout and restore caches
|
||||
uses: ./.github/actions/setup-rust
|
||||
|
||||
- name: Restore frontend build cache
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: apps/frontend/build
|
||||
key: frontend-build-${{ runner.os }}-run-${{ github.run_id }}
|
||||
restore-keys: |
|
||||
frontend-build-${{ runner.os }}-
|
||||
|
||||
- name: Run tests
|
||||
run: cargo test --all-features
|
||||
|
||||
lint:
|
||||
needs: frontend-build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
@@ -70,8 +53,111 @@ jobs:
|
||||
with:
|
||||
components: clippy, rustfmt
|
||||
|
||||
- name: Restore frontend build cache
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: apps/frontend/build
|
||||
key: frontend-build-${{ runner.os }}-run-${{ github.run_id }}
|
||||
restore-keys: |
|
||||
frontend-build-${{ runner.os }}-
|
||||
|
||||
- name: Run clippy
|
||||
run: cargo clippy --all-features -- -D warnings
|
||||
|
||||
- name: Check code formatting
|
||||
run: cargo fmt --all -- --check
|
||||
|
||||
lint-frontend:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: 'pnpm'
|
||||
cache-dependency-path: apps/frontend/pnpm-lock.yaml
|
||||
|
||||
- name: Install frontend dependencies
|
||||
run: |
|
||||
cd apps/frontend
|
||||
pnpm install
|
||||
|
||||
- name: Run frontend linter
|
||||
run: |
|
||||
cd apps/frontend
|
||||
pnpm lint
|
||||
|
||||
test-frontend:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
name: Install pnpm
|
||||
with:
|
||||
version: 10
|
||||
run_install: false
|
||||
|
||||
- name: Install Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: 'pnpm'
|
||||
cache-dependency-path: apps/frontend/pnpm-lock.yaml
|
||||
|
||||
- name: Install frontend dependencies
|
||||
run: |
|
||||
cd apps/frontend
|
||||
pnpm install
|
||||
|
||||
- name: Run frontend tests
|
||||
run: |
|
||||
cd apps/frontend
|
||||
pnpm test
|
||||
|
||||
frontend-build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: 'pnpm'
|
||||
cache-dependency-path: apps/frontend/pnpm-lock.yaml
|
||||
|
||||
- name: Install frontend dependencies
|
||||
run: |
|
||||
cd apps/frontend
|
||||
pnpm install
|
||||
|
||||
- name: Build frontend
|
||||
run: |
|
||||
cd apps/frontend
|
||||
pnpm build
|
||||
|
||||
- name: Cache frontend build
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: apps/frontend/build
|
||||
key: frontend-build-${{ runner.os }}-run-${{ github.run_id }}
|
||||
restore-keys: |
|
||||
frontend-build-${{ runner.os }}-
|
||||
|
||||
195
.github/workflows/verify.yml
vendored
Normal file
195
.github/workflows/verify.yml
vendored
Normal file
@@ -0,0 +1,195 @@
|
||||
# this workflow verifies the generated code is up to date and valid
|
||||
|
||||
name: Verify
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- master
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
|
||||
|
||||
jobs:
|
||||
# setup is now handled by a composite action used by downstream jobs to keep
|
||||
# the workflow DRY. The composite action performs checkout, cache restore and
|
||||
# toolchain setup.
|
||||
|
||||
verify-generated-code:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Rust, checkout and restore caches
|
||||
uses: ./.github/actions/setup-rust
|
||||
|
||||
- name: generate entities from migration files
|
||||
run: |
|
||||
cd apps/cli
|
||||
cargo run -- db:migrate_and_generate --output-path ../../public/database/src/generated/entities
|
||||
- name: Check for uncommitted changes in /generated/
|
||||
run: |
|
||||
if [[ -n $(git status --porcelain | grep '^ M .*\/generated\/') ]]; then
|
||||
echo "Generated code is not up to date. Please run the code generation locally and commit the changes."
|
||||
git status --porcelain | grep '^ M .*\/generated\/'
|
||||
exit 1
|
||||
else
|
||||
echo "Generated code is up to date."
|
||||
fi
|
||||
|
||||
verify-openapi-spec:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Check whether apps/api/src/routes changed
|
||||
id: check_changes
|
||||
run: |
|
||||
if [ "${{ github.event_name }}" = "pull_request" ]; then
|
||||
BASE_SHA=${{ github.event.pull_request.base.sha }}
|
||||
HEAD_SHA=${{ github.event.pull_request.head.sha }}
|
||||
else
|
||||
BASE_SHA=${{ github.event.before }}
|
||||
HEAD_SHA=${{ github.sha }}
|
||||
fi
|
||||
|
||||
# Provide safe fallbacks when GitHub context values are empty (e.g. when using act)
|
||||
if [ -z "$HEAD_SHA" ]; then
|
||||
HEAD_SHA=$(git rev-parse --verify HEAD 2>/dev/null || echo "")
|
||||
fi
|
||||
|
||||
if [ -z "$BASE_SHA" ]; then
|
||||
# Try the parent of HEAD, fall back to HEAD if unavailable
|
||||
PREV=$(git rev-parse --verify "${HEAD_SHA}^" 2>/dev/null || true)
|
||||
if [ -n "$PREV" ]; then
|
||||
BASE_SHA=$PREV
|
||||
else
|
||||
BASE_SHA=$HEAD_SHA
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "Comparing $BASE_SHA..$HEAD_SHA"
|
||||
CHANGED_FILES=$(git diff --name-only "$BASE_SHA" "$HEAD_SHA" || true)
|
||||
echo "$CHANGED_FILES"
|
||||
|
||||
echo "$CHANGED_FILES" | grep -E '^(apps/api/src/routes/?|apps/api/swagger.json)' >/dev/null 2>&1 && echo "changed=true" >> $GITHUB_OUTPUT || echo "changed=false" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Setup Rust, checkout and restore caches
|
||||
if: steps.check_changes.outputs.changed == 'true'
|
||||
uses: ./.github/actions/setup-rust
|
||||
|
||||
- name: Generate dummy frontend build (to satisfy dependencies)
|
||||
if: steps.check_changes.outputs.changed == 'true'
|
||||
run: |
|
||||
mkdir -p apps/frontend/build/client
|
||||
echo "dummy file" > apps/frontend/build/client/dummy.txt
|
||||
|
||||
- name: Generate OpenAPI spec
|
||||
if: steps.check_changes.outputs.changed == 'true'
|
||||
run: |
|
||||
cd apps/api
|
||||
cargo run -- generate:openapi --output-path ./swagger.json
|
||||
|
||||
- name: Check for uncommitted changes in swagger.json
|
||||
if: steps.check_changes.outputs.changed == 'true'
|
||||
run: |
|
||||
if [[ -n $(git status --porcelain | grep '^ M apps/api/swagger.json') ]]; then
|
||||
echo "OpenAPI spec is not up to date. Please run the OpenAPI generation locally and commit the changes."
|
||||
git status --porcelain | grep '^ M apps/api/swagger.json'
|
||||
exit 1
|
||||
else
|
||||
echo "OpenAPI spec is up to date."
|
||||
fi
|
||||
|
||||
- name: Skip OpenAPI generation (no relevant changes)
|
||||
if: steps.check_changes.outputs.changed == 'false'
|
||||
run: echo "No changes in apps/api/src/routes/ nor apps/api/swagger.json, skipping OpenAPI generation verification."
|
||||
|
||||
verify-frontend-api-client:
|
||||
runs-on: ubuntu-latest
|
||||
needs: verify-openapi-spec
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Check whether apps/api/swagger.json or apps/frontend/app/generated/api-client changed
|
||||
id: check_swagger_changes
|
||||
run: |
|
||||
if [ "${{ github.event_name }}" = "pull_request" ]; then
|
||||
BASE_SHA=${{ github.event.pull_request.base.sha }}
|
||||
HEAD_SHA=${{ github.event.pull_request.head.sha }}
|
||||
else
|
||||
BASE_SHA=${{ github.event.before }}
|
||||
HEAD_SHA=${{ github.sha }}
|
||||
fi
|
||||
|
||||
# Provide safe fallbacks when GitHub context values are empty (e.g. when using act)
|
||||
if [ -z "$HEAD_SHA" ]; then
|
||||
HEAD_SHA=$(git rev-parse --verify HEAD 2>/dev/null || echo "")
|
||||
fi
|
||||
|
||||
if [ -z "$BASE_SHA" ]; then
|
||||
# Try the parent of HEAD, fall back to HEAD if unavailable
|
||||
PREV=$(git rev-parse --verify "${HEAD_SHA}^" 2>/dev/null || true)
|
||||
if [ -n "$PREV" ]; then
|
||||
BASE_SHA=$PREV
|
||||
else
|
||||
BASE_SHA=$HEAD_SHA
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "Comparing $BASE_SHA..$HEAD_SHA"
|
||||
CHANGED_FILES=$(git diff --name-only "$BASE_SHA" "$HEAD_SHA" || true)
|
||||
echo "$CHANGED_FILES"
|
||||
|
||||
echo "$CHANGED_FILES" | grep -E '^(apps/api/swagger.json|apps/frontend/app/generated/api-client)' >/dev/null 2>&1 && echo "changed=true" >> $GITHUB_OUTPUT || echo "changed=false" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Setup PNPM
|
||||
uses: pnpm/action-setup@v4
|
||||
if: steps.check_swagger_changes.outputs.changed == 'true'
|
||||
with:
|
||||
version: 10
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
if: steps.check_swagger_changes.outputs.changed == 'true'
|
||||
with:
|
||||
node-version: 22
|
||||
cache: 'pnpm'
|
||||
cache-dependency-path: apps/frontend/pnpm-lock.yaml
|
||||
|
||||
- name: Install frontend dependencies
|
||||
if: steps.check_swagger_changes.outputs.changed == 'true'
|
||||
run: |
|
||||
cd apps/frontend
|
||||
pnpm install
|
||||
|
||||
- name: Generate frontend API client
|
||||
if: steps.check_swagger_changes.outputs.changed == 'true'
|
||||
run: |
|
||||
cd apps/frontend
|
||||
pnpm generate:openapi
|
||||
|
||||
- name: Check for uncommitted changes in frontend API client
|
||||
if: steps.check_swagger_changes.outputs.changed == 'true'
|
||||
run: |
|
||||
if [[ -n $(git status --porcelain | grep '^ M apps/frontend/app/generated/api-client') ]]; then
|
||||
echo "Frontend API client is not up to date. Please run the API client generation locally and commit the changes."
|
||||
git status --porcelain | grep '^ M apps/frontend/app/generated/api-client'
|
||||
exit 1
|
||||
else
|
||||
echo "Frontend API client is up to date."
|
||||
fi
|
||||
|
||||
- name: Skip frontend API client generation (no relevant changes)
|
||||
if: steps.check_swagger_changes.outputs.changed == 'false'
|
||||
run: echo "No changes in apps/api/swagger.json nor apps/frontend/app/generated/api-client, skipping frontend API client generation verification."
|
||||
12
.vscode/settings.json
vendored
Normal file
12
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"cSpell.words": ["chrono", "jsonwebtoken", "oneshot", "utoipa", "YANPM"],
|
||||
"sqltools.useNodeRuntime": true,
|
||||
"sqltools.connections": [
|
||||
{
|
||||
"previewLimit": 50,
|
||||
"driver": "SQLite",
|
||||
"database": "${workspaceFolder:yet-another-nginx-proxy-manager}/apps/container/generated/sqlite/sqlite.db",
|
||||
"name": "YANPM"
|
||||
}
|
||||
]
|
||||
}
|
||||
475
Cargo.lock
generated
475
Cargo.lock
generated
@@ -93,6 +93,18 @@ dependencies = [
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "argon2"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"blake2",
|
||||
"cpufeatures",
|
||||
"password-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arraydeque"
|
||||
version = "0.5.1"
|
||||
@@ -212,6 +224,28 @@ dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "axum-extra"
|
||||
version = "0.12.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dbfe9f610fe4e99cf0cfcd03ccf8c63c28c616fe714d80475ef731f3b13dd21b"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"axum-core",
|
||||
"bytes",
|
||||
"cookie",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"mime",
|
||||
"pin-project-lite",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "axum-macros"
|
||||
version = "0.5.0"
|
||||
@@ -223,6 +257,12 @@ dependencies = [
|
||||
"syn 2.0.110",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "base16ct"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.21.7"
|
||||
@@ -282,6 +322,15 @@ dependencies = [
|
||||
"wyz",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "blake2"
|
||||
version = "0.10.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
|
||||
dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
@@ -580,6 +629,17 @@ dependencies = [
|
||||
"unicode-segmentation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cookie"
|
||||
version = "0.18.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747"
|
||||
dependencies = [
|
||||
"percent-encoding",
|
||||
"time",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation"
|
||||
version = "0.9.4"
|
||||
@@ -651,6 +711,18 @@ version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
|
||||
|
||||
[[package]]
|
||||
name = "crypto-bigint"
|
||||
version = "0.5.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"rand_core 0.6.4",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
@@ -661,6 +733,33 @@ dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek"
|
||||
version = "4.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"curve25519-dalek-derive",
|
||||
"digest",
|
||||
"fiat-crypto",
|
||||
"rustc_version",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek-derive"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.110",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling"
|
||||
version = "0.20.11"
|
||||
@@ -841,6 +940,44 @@ version = "1.0.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
|
||||
|
||||
[[package]]
|
||||
name = "ecdsa"
|
||||
version = "0.16.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"
|
||||
dependencies = [
|
||||
"der",
|
||||
"digest",
|
||||
"elliptic-curve",
|
||||
"rfc6979",
|
||||
"signature",
|
||||
"spki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519"
|
||||
version = "2.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
|
||||
dependencies = [
|
||||
"pkcs8",
|
||||
"signature",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519-dalek"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"
|
||||
dependencies = [
|
||||
"curve25519-dalek",
|
||||
"ed25519",
|
||||
"serde",
|
||||
"sha2",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.15.0"
|
||||
@@ -850,6 +987,27 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "elliptic-curve"
|
||||
version = "0.13.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47"
|
||||
dependencies = [
|
||||
"base16ct",
|
||||
"crypto-bigint",
|
||||
"digest",
|
||||
"ff",
|
||||
"generic-array",
|
||||
"group",
|
||||
"hkdf",
|
||||
"pem-rfc7468",
|
||||
"pkcs8",
|
||||
"rand_core 0.6.4",
|
||||
"sec1",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "encoding_rs"
|
||||
version = "0.8.35"
|
||||
@@ -925,6 +1083,22 @@ version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
|
||||
|
||||
[[package]]
|
||||
name = "ff"
|
||||
version = "0.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393"
|
||||
dependencies = [
|
||||
"rand_core 0.6.4",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fiat-crypto"
|
||||
version = "0.2.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
|
||||
|
||||
[[package]]
|
||||
name = "filetime"
|
||||
version = "0.2.26"
|
||||
@@ -1104,6 +1278,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1135,6 +1310,36 @@ version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
|
||||
|
||||
[[package]]
|
||||
name = "group"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63"
|
||||
dependencies = [
|
||||
"ff",
|
||||
"rand_core 0.6.4",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "h2"
|
||||
version = "0.4.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f3c0b69cfcb4e1b9f1bf2f53f95f766e4661169728ec61cd3fe5a0166f2d1386"
|
||||
dependencies = [
|
||||
"atomic-waker",
|
||||
"bytes",
|
||||
"fnv",
|
||||
"futures-core",
|
||||
"futures-sink",
|
||||
"http",
|
||||
"indexmap 2.12.0",
|
||||
"slab",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.12.3"
|
||||
@@ -1277,6 +1482,7 @@ dependencies = [
|
||||
"bytes",
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
"h2",
|
||||
"http",
|
||||
"http-body",
|
||||
"httparse",
|
||||
@@ -1488,6 +1694,25 @@ dependencies = [
|
||||
"icu_properties",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "include_dir"
|
||||
version = "0.7.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "923d117408f1e49d914f1a379a309cffe4f18c05cf4e3d12e613a15fc81bd0dd"
|
||||
dependencies = [
|
||||
"include_dir_macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "include_dir_macros"
|
||||
version = "0.7.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7cab85a7ed0bd5f0e76d93846e0147172bed2e2d3f859bcc33a8d9699cad1a75"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "1.9.3"
|
||||
@@ -1573,6 +1798,29 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonwebtoken"
|
||||
version = "10.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c76e1c7d7df3e34443b3621b459b066a7b79644f059fc8b2db7070c825fd417e"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"ed25519-dalek",
|
||||
"getrandom 0.2.16",
|
||||
"hmac",
|
||||
"js-sys",
|
||||
"p256",
|
||||
"p384",
|
||||
"pem",
|
||||
"rand 0.8.5",
|
||||
"rsa",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"signature",
|
||||
"simple_asn1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lazy_static"
|
||||
version = "1.5.0"
|
||||
@@ -1690,6 +1938,16 @@ version = "0.3.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
|
||||
|
||||
[[package]]
|
||||
name = "mime_guess"
|
||||
version = "2.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"
|
||||
dependencies = [
|
||||
"mime",
|
||||
"unicase",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "1.1.0"
|
||||
@@ -1748,7 +2006,7 @@ dependencies = [
|
||||
"num-integer",
|
||||
"num-iter",
|
||||
"num-traits",
|
||||
"rand",
|
||||
"rand 0.8.5",
|
||||
"smallvec",
|
||||
"zeroize",
|
||||
]
|
||||
@@ -1888,6 +2146,30 @@ dependencies = [
|
||||
"syn 2.0.110",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "p256"
|
||||
version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b"
|
||||
dependencies = [
|
||||
"ecdsa",
|
||||
"elliptic-curve",
|
||||
"primeorder",
|
||||
"sha2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "p384"
|
||||
version = "0.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6"
|
||||
dependencies = [
|
||||
"ecdsa",
|
||||
"elliptic-curve",
|
||||
"primeorder",
|
||||
"sha2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parking"
|
||||
version = "2.2.1"
|
||||
@@ -1942,6 +2224,17 @@ dependencies = [
|
||||
"syn 2.0.110",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "password-hash"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"rand_core 0.6.4",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "path-clean"
|
||||
version = "1.0.1"
|
||||
@@ -1954,6 +2247,16 @@ version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3"
|
||||
|
||||
[[package]]
|
||||
name = "pem"
|
||||
version = "3.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pem-rfc7468"
|
||||
version = "0.7.0"
|
||||
@@ -2104,6 +2407,15 @@ dependencies = [
|
||||
"syn 2.0.110",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "primeorder"
|
||||
version = "0.13.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6"
|
||||
dependencies = [
|
||||
"elliptic-curve",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro-crate"
|
||||
version = "3.4.0"
|
||||
@@ -2205,8 +2517,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rand_chacha",
|
||||
"rand_core",
|
||||
"rand_chacha 0.3.1",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.9.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"
|
||||
dependencies = [
|
||||
"rand_chacha 0.9.0",
|
||||
"rand_core 0.9.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2216,7 +2538,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core 0.9.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2228,6 +2560,15 @@ dependencies = [
|
||||
"getrandom 0.2.16",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.9.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.3.5"
|
||||
@@ -2304,6 +2645,16 @@ dependencies = [
|
||||
"bytecheck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rfc6979"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2"
|
||||
dependencies = [
|
||||
"hmac",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ring"
|
||||
version = "0.17.14"
|
||||
@@ -2374,7 +2725,7 @@ dependencies = [
|
||||
"num-traits",
|
||||
"pkcs1",
|
||||
"pkcs8",
|
||||
"rand_core",
|
||||
"rand_core 0.6.4",
|
||||
"signature",
|
||||
"spki",
|
||||
"subtle",
|
||||
@@ -2401,12 +2752,21 @@ dependencies = [
|
||||
"borsh",
|
||||
"bytes",
|
||||
"num-traits",
|
||||
"rand",
|
||||
"rand 0.8.5",
|
||||
"rkyv",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc_version"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
|
||||
dependencies = [
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.2"
|
||||
@@ -2716,6 +3076,20 @@ version = "4.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b"
|
||||
|
||||
[[package]]
|
||||
name = "sec1"
|
||||
version = "0.7.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc"
|
||||
dependencies = [
|
||||
"base16ct",
|
||||
"der",
|
||||
"generic-array",
|
||||
"pkcs8",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "security-framework"
|
||||
version = "2.11.1"
|
||||
@@ -2752,6 +3126,12 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.228"
|
||||
@@ -2938,7 +3318,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
|
||||
dependencies = [
|
||||
"digest",
|
||||
"rand_core",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2947,6 +3327,18 @@ version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
|
||||
|
||||
[[package]]
|
||||
name = "simple_asn1"
|
||||
version = "0.6.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "297f631f50729c8c99b84667867963997ec0b50f32b2a7dbcab828ef0541e8bb"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"num-traits",
|
||||
"thiserror",
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.11"
|
||||
@@ -3115,7 +3507,7 @@ dependencies = [
|
||||
"memchr",
|
||||
"once_cell",
|
||||
"percent-encoding",
|
||||
"rand",
|
||||
"rand 0.8.5",
|
||||
"rsa",
|
||||
"rust_decimal",
|
||||
"serde",
|
||||
@@ -3159,7 +3551,7 @@ dependencies = [
|
||||
"memchr",
|
||||
"num-bigint",
|
||||
"once_cell",
|
||||
"rand",
|
||||
"rand 0.8.5",
|
||||
"rust_decimal",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -3583,6 +3975,20 @@ dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tower-http"
|
||||
version = "0.6.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8"
|
||||
dependencies = [
|
||||
"bitflags 2.10.0",
|
||||
"bytes",
|
||||
"http",
|
||||
"pin-project-lite",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tower-layer"
|
||||
version = "0.3.3"
|
||||
@@ -3696,6 +4102,12 @@ version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971"
|
||||
|
||||
[[package]]
|
||||
name = "unicase"
|
||||
version = "2.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-bidi"
|
||||
version = "0.3.18"
|
||||
@@ -3766,13 +4178,40 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.18.1"
|
||||
name = "utoipa"
|
||||
version = "5.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2"
|
||||
checksum = "2fcc29c80c21c31608227e0912b2d7fddba57ad76b606890627ba8ee7964e993"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"indexmap 2.12.0",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"utoipa-gen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "utoipa-gen"
|
||||
version = "5.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6d79d08d92ab8af4c5e8a6da20c47ae3f61a0f1dabc1997cdf2d082b757ca08b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"regex",
|
||||
"syn 2.0.110",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e2e054861b4bd027cd373e18e8d8d8e6548085000e41290d95ce0c373a654b4a"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"js-sys",
|
||||
"rand 0.9.2",
|
||||
"serde_core",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
@@ -4270,19 +4709,29 @@ checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049"
|
||||
name = "yet-another-nginx-proxy-manager"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"async-trait",
|
||||
"axum",
|
||||
"axum-extra",
|
||||
"chrono",
|
||||
"clap",
|
||||
"config",
|
||||
"database",
|
||||
"include_dir",
|
||||
"jsonwebtoken",
|
||||
"migration",
|
||||
"mime_guess",
|
||||
"once_cell",
|
||||
"sea-orm",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
"tower",
|
||||
"tower-http",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"utoipa",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
674
LICENSE
Normal file
674
LICENSE
Normal file
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
18
README.md
Normal file
18
README.md
Normal file
@@ -0,0 +1,18 @@
|
||||
# Yet Another Nginx Proxy Manager (YANPM)
|
||||
|
||||
Yet Another Nginx Proxy Manager (YANPM) is an open-source web application designed to simplify the management of Nginx proxy servers. It targets at small footprint and high performance with plugin support.
|
||||
|
||||
## Features
|
||||
|
||||
- Easy-to-use web interface for managing Nginx proxies
|
||||
- User authentication and access control
|
||||
- Plugin architecture for extensibility
|
||||
- Lightweight and efficient design
|
||||
|
||||
## Installation
|
||||
|
||||
TBD
|
||||
|
||||
## Development Setup
|
||||
|
||||
Refer to the [Development Guide](doc/development.md) for detailed instructions on setting up the development environment, including backend and frontend development.
|
||||
@@ -7,7 +7,8 @@ edition = "2024"
|
||||
database = { path = "../../public/database" }
|
||||
migration = { path = "../../public/migration" }
|
||||
|
||||
axum = { version = "0.8.7", features = ["form", "http1", "json", "matched-path", "original-uri", "query", "tokio", "tower-log", "tracing", "macros"]}
|
||||
axum = { version = "0.8.7", features = ["form", "http1", "http2", "json", "matched-path", "original-uri", "query", "tokio", "tower-log", "tracing", "macros"] }
|
||||
axum-extra = { version = "0.12.2", features = ["cookie"] }
|
||||
async-trait = { version = "0.1.89" }
|
||||
chrono = { version = "0.4.42", features = ["clock", "std", "oldtime", "wasmbind", "serde"] }
|
||||
config = { version = "0.15.19", features = ["toml", "json", "yaml", "ini", "ron", "json5", "convert-case", "async"] }
|
||||
@@ -18,3 +19,13 @@ tracing-subscriber = { version = "0.3.20", features = ["smallvec", "fmt", "ansi"
|
||||
serde_json = { version = "1.0.145", features = ["std"] }
|
||||
serde = { version = "1.0.228", features = ["std", "derive"] }
|
||||
sea-orm = { workspace = true }
|
||||
include_dir = { version = "0.7.4" }
|
||||
mime_guess = { version = "2.0.5" }
|
||||
utoipa = { version = "5.4.0", features = ["macros", "axum_extras", "chrono", "decimal", "uuid", "time", "openapi_extensions"] }
|
||||
clap = { version = "4.5.53" }
|
||||
once_cell = { version = "1.21.3" }
|
||||
argon2 = { version = "0.5.3", features = ["std"] }
|
||||
jsonwebtoken = { version = "10.2.0", features = ["rust_crypto"] }
|
||||
uuid = { version = "1.19.0", features = ["v4", "serde", "fast-rng"] }
|
||||
tower-http = { version = "0.6.8", features = ["cors"] }
|
||||
|
||||
|
||||
49
apps/api/src/cmd.rs
Normal file
49
apps/api/src/cmd.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
mod generate_openapi;
|
||||
mod start_server;
|
||||
|
||||
pub use start_server::start_server;
|
||||
|
||||
use std::pin::Pin;
|
||||
use std::{future::Future, process::exit};
|
||||
|
||||
use clap::{ArgMatches, Command};
|
||||
|
||||
pub struct CliCommand {
|
||||
pub command: Command,
|
||||
pub action: fn(&clap::ArgMatches) -> Pin<Box<dyn std::future::Future<Output = ()> + Send>>,
|
||||
}
|
||||
|
||||
static CLI_COMMANDS: once_cell::sync::Lazy<
|
||||
[CliCommand; 2 /* Update this count when adding new commands */],
|
||||
> =
|
||||
once_cell::sync::Lazy::new(|| {
|
||||
[
|
||||
// Add new commands here
|
||||
generate_openapi::get_cli_command(),
|
||||
start_server::get_cli_command(),
|
||||
]
|
||||
});
|
||||
|
||||
pub fn get_command() -> Command {
|
||||
let mut c = Command::new("cmd");
|
||||
|
||||
for cmd in CLI_COMMANDS.iter() {
|
||||
c = c.subcommand(cmd.command.clone());
|
||||
}
|
||||
|
||||
c
|
||||
}
|
||||
|
||||
pub fn execute(matches: &ArgMatches, help_msg: &str) -> Pin<Box<dyn Future<Output = ()> + Send>> {
|
||||
if let Some((subcommand_name, subcommand_matches)) = matches.subcommand() {
|
||||
for cmd in CLI_COMMANDS.iter() {
|
||||
if cmd.command.get_name() == subcommand_name {
|
||||
return (cmd.action)(subcommand_matches);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
eprintln!("Error: No valid subcommand provided.");
|
||||
eprintln!("{}", help_msg);
|
||||
exit(1);
|
||||
}
|
||||
44
apps/api/src/cmd/generate_openapi.rs
Normal file
44
apps/api/src/cmd/generate_openapi.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
use clap::{Arg, Command};
|
||||
use tracing::info;
|
||||
use utoipa::OpenApi;
|
||||
|
||||
use crate::{cmd::CliCommand, log, routes::ApiDoc};
|
||||
|
||||
pub fn get_cli_command() -> CliCommand {
|
||||
CliCommand {
|
||||
command: command(),
|
||||
action,
|
||||
}
|
||||
}
|
||||
|
||||
fn command() -> Command {
|
||||
Command::new("generate:openapi")
|
||||
.arg(
|
||||
Arg::new("output_path")
|
||||
.short('o')
|
||||
.long("output-path")
|
||||
.value_name("PATH")
|
||||
.help("Path to output the generated OpenAPI documentation")
|
||||
.required(true),
|
||||
)
|
||||
.about("Generate OpenAPI documentation")
|
||||
}
|
||||
|
||||
fn action(
|
||||
_matches: &clap::ArgMatches,
|
||||
) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> {
|
||||
let output_path = _matches.get_one::<String>("output_path");
|
||||
let output_path = output_path.unwrap().to_string();
|
||||
|
||||
Box::pin(async move {
|
||||
tracing::subscriber::with_default(log::make_temporary_subscriber(), || {
|
||||
info!("Generating OpenAPI documentation...");
|
||||
let doc = ApiDoc::openapi();
|
||||
let json = doc
|
||||
.to_pretty_json()
|
||||
.expect("Failed to serialize OpenAPI doc to JSON");
|
||||
std::fs::write(&output_path, json).expect("Failed to write OpenAPI doc to file");
|
||||
info!("OpenAPI documentation generated at {}", output_path);
|
||||
})
|
||||
})
|
||||
}
|
||||
182
apps/api/src/cmd/start_server.rs
Normal file
182
apps/api/src/cmd/start_server.rs
Normal file
@@ -0,0 +1,182 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::Router;
|
||||
use clap::Command;
|
||||
use database::get_connection;
|
||||
use sea_orm::ConnectOptions;
|
||||
use tracing::{debug, info};
|
||||
use tracing_subscriber::fmt::format::{DefaultFields, Format};
|
||||
|
||||
use crate::{
|
||||
cmd::CliCommand,
|
||||
configs::{ProgramSettings, get_program_settings, logging::LoggingSettings},
|
||||
log,
|
||||
routes::{self, AppService, AppState},
|
||||
services::{
|
||||
auth::{
|
||||
authentication::{AuthenticationServiceImpl, strategies::password::PasswordStrategy},
|
||||
user::UserServiceImpl,
|
||||
},
|
||||
server_state::ServerStateService,
|
||||
settings::SettingsService,
|
||||
},
|
||||
tasks,
|
||||
};
|
||||
|
||||
pub fn get_cli_command() -> CliCommand {
|
||||
CliCommand {
|
||||
command: command(),
|
||||
action,
|
||||
}
|
||||
}
|
||||
|
||||
fn command() -> Command {
|
||||
Command::new("start").about("Start the server")
|
||||
}
|
||||
|
||||
fn action(
|
||||
_matches: &clap::ArgMatches,
|
||||
) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> {
|
||||
Box::pin(async move {})
|
||||
}
|
||||
|
||||
pub async fn start_server() {
|
||||
let settings = tracing::subscriber::with_default(
|
||||
log::make_temporary_subscriber(),
|
||||
|| -> ProgramSettings {
|
||||
debug!("Temporary subscriber installed.");
|
||||
info!("Reading configuration...");
|
||||
let settings = get_program_settings();
|
||||
info!("Configuration read successfully.");
|
||||
debug!("Resetting global subscriber...");
|
||||
|
||||
let subscriber = get_global_tracing_subscriber_builder(&settings.logging).finish();
|
||||
tracing::subscriber::set_global_default(subscriber)
|
||||
.expect("Failed to set global default subscriber");
|
||||
|
||||
debug!(
|
||||
"Global subscriber set with logging level: {:?}",
|
||||
settings.logging.level
|
||||
);
|
||||
|
||||
settings
|
||||
},
|
||||
);
|
||||
|
||||
tasks::startup::run_startup_tasks(&settings)
|
||||
.await
|
||||
.inspect_err(|err| {
|
||||
tracing::error!("Failed to run startup tasks: {}", err);
|
||||
})
|
||||
.expect("Failed to run startup tasks");
|
||||
|
||||
// setup database connection pool
|
||||
info!("Establishing database connection...");
|
||||
debug!("Database URL: {}", settings.database.url);
|
||||
|
||||
let db_options = |options: &mut ConnectOptions| {
|
||||
options.max_connections(settings.database.max_connections);
|
||||
};
|
||||
|
||||
let db_connection = Arc::new(
|
||||
get_connection(&settings.database.url, Some(db_options))
|
||||
.await
|
||||
.expect("Failed to establish database connection"),
|
||||
);
|
||||
|
||||
info!("Database connection established.");
|
||||
|
||||
// build the axum app and run the server...
|
||||
info!("Starting application...");
|
||||
let mut app: Router = routes::get_root_router(
|
||||
Arc::new(get_app_state(&db_connection, &settings)),
|
||||
Arc::new(settings.server.cors.clone()),
|
||||
);
|
||||
|
||||
if settings.server.serve_openapi {
|
||||
info!("Enabling OpenAPI documentation endpoint at /openapi.json");
|
||||
app = app.route(
|
||||
"/openapi.json",
|
||||
axum::routing::get(|| async {
|
||||
use utoipa::OpenApi;
|
||||
let doc = routes::ApiDoc::openapi();
|
||||
doc.to_pretty_json()
|
||||
.expect("Failed to serialize OpenAPI doc to JSON")
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
let address = format!("{}:{}", settings.server.address, settings.server.port);
|
||||
info!("Starting server at http://{}", address);
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(address)
|
||||
.await
|
||||
.expect("Failed to bind to address");
|
||||
|
||||
axum::serve(listener, app)
|
||||
.await
|
||||
.expect("Failed to run the server");
|
||||
}
|
||||
|
||||
fn get_global_tracing_subscriber_builder(
|
||||
settings: &LoggingSettings,
|
||||
) -> tracing_subscriber::fmt::SubscriberBuilder<
|
||||
DefaultFields,
|
||||
Format<tracing_subscriber::fmt::format::Full, BoxedTimer>,
|
||||
> {
|
||||
// After configuration is read, install the global subscriber
|
||||
let builder = tracing_subscriber::fmt()
|
||||
.with_max_level(settings.level)
|
||||
.with_target(false)
|
||||
.with_level(true);
|
||||
|
||||
if settings.utc {
|
||||
builder.with_timer(BoxedTimer(Box::new(
|
||||
tracing_subscriber::fmt::time::UtcTime::rfc_3339(),
|
||||
)))
|
||||
} else {
|
||||
builder.with_timer(BoxedTimer(Box::new(
|
||||
tracing_subscriber::fmt::time::ChronoLocal::rfc_3339(),
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
fn get_app_state(
|
||||
db_connection: &Arc<sea_orm::DatabaseConnection>,
|
||||
settings: &ProgramSettings,
|
||||
) -> AppState {
|
||||
AppState {
|
||||
database_connection: db_connection.clone(),
|
||||
config: Arc::new(settings.clone()),
|
||||
service: Arc::new(AppService {
|
||||
server_state: Arc::new(ServerStateService::new(db_connection.clone())),
|
||||
settings: Arc::new(SettingsService::new(db_connection.clone())),
|
||||
auth_state: routes::AuthState {
|
||||
strategy: routes::AuthStrategy {
|
||||
password: Arc::new(PasswordStrategy::new(db_connection.clone())),
|
||||
},
|
||||
authentication: Arc::new(AuthenticationServiceImpl::new(
|
||||
settings.auth.jwt_secret.clone(),
|
||||
)),
|
||||
},
|
||||
user: Arc::new(UserServiceImpl::new(db_connection.clone())),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
// A small wrapper that holds a boxed `FormatTime` trait object and itself
|
||||
// implements `FormatTime`, allowing us to use it as a concrete type with
|
||||
// `builder.with_timer` while still picking the concrete timer implementation
|
||||
// at runtime.
|
||||
// wrapper type to hold boxed timers and implement the `FormatTime` trait for
|
||||
// a concrete type so `with_timer` may be called once outside the conditional.
|
||||
struct BoxedTimer(Box<dyn tracing_subscriber::fmt::time::FormatTime + Send + Sync + 'static>);
|
||||
|
||||
impl tracing_subscriber::fmt::time::FormatTime for BoxedTimer {
|
||||
fn format_time(
|
||||
&self,
|
||||
w: &mut tracing_subscriber::fmt::format::Writer<'_>,
|
||||
) -> std::result::Result<(), std::fmt::Error> {
|
||||
self.0.format_time(w)
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod auth;
|
||||
pub mod database;
|
||||
pub mod logging;
|
||||
pub mod server;
|
||||
@@ -10,6 +11,8 @@ use tracing::{debug, error};
|
||||
pub trait FromConfig: Sized {
|
||||
fn from_config(config: &Config) -> Result<Self, String>;
|
||||
fn validate(&self) -> Result<(), String>;
|
||||
#[cfg(test)]
|
||||
fn mock() -> Self;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -17,6 +20,7 @@ pub struct ProgramSettings {
|
||||
pub logging: logging::LoggingSettings,
|
||||
pub database: database::DatabaseSettings,
|
||||
pub server: server::ServerSettings,
|
||||
pub auth: auth::AuthSettings,
|
||||
}
|
||||
|
||||
impl FromConfig for ProgramSettings {
|
||||
@@ -25,6 +29,7 @@ impl FromConfig for ProgramSettings {
|
||||
logging: logging::LoggingSettings::from_config(_config)?,
|
||||
database: database::DatabaseSettings::from_config(_config)?,
|
||||
server: server::ServerSettings::from_config(_config)?,
|
||||
auth: auth::AuthSettings::from_config(_config)?,
|
||||
};
|
||||
config.validate()?;
|
||||
Ok(config)
|
||||
@@ -34,8 +39,19 @@ impl FromConfig for ProgramSettings {
|
||||
self.logging.validate()?;
|
||||
self.database.validate()?;
|
||||
self.server.validate()?;
|
||||
self.auth.validate()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn mock() -> Self {
|
||||
ProgramSettings {
|
||||
logging: logging::LoggingSettings::mock(),
|
||||
database: database::DatabaseSettings::mock(),
|
||||
server: server::ServerSettings::mock(),
|
||||
auth: auth::AuthSettings::mock(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_program_settings() -> ProgramSettings {
|
||||
|
||||
60
apps/api/src/configs/auth.rs
Normal file
60
apps/api/src/configs/auth.rs
Normal file
@@ -0,0 +1,60 @@
|
||||
use config::{Config, ConfigError};
|
||||
use tracing::warn;
|
||||
|
||||
use crate::configs::key::{
|
||||
AUTH_DEFAULT_ADMIN_PASSWORD_KEY, AUTH_DEFAULT_ADMIN_USERNAME_KEY, AUTH_JWT_SECRET_KEY,
|
||||
};
|
||||
|
||||
use super::FromConfig;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AuthSettings {
|
||||
pub jwt_secret: Option<String>,
|
||||
pub default_admin_username: Option<String>,
|
||||
pub default_admin_password: Option<String>,
|
||||
}
|
||||
|
||||
impl FromConfig for AuthSettings {
|
||||
fn from_config(_config: &Config) -> Result<Self, String> {
|
||||
Ok(AuthSettings {
|
||||
jwt_secret: _config
|
||||
.get_string(AUTH_JWT_SECRET_KEY)
|
||||
.inspect_err(|err| {
|
||||
match err {
|
||||
ConfigError::NotFound(_) => {
|
||||
warn!(
|
||||
"{} not found in configuration, A random secret will be generated at runtime.",
|
||||
AUTH_JWT_SECRET_KEY
|
||||
);
|
||||
}
|
||||
_ => {
|
||||
warn!(
|
||||
"Failed to read {} from configuration, A random secret will be generated at runtime: {}",
|
||||
AUTH_JWT_SECRET_KEY, err
|
||||
);
|
||||
}
|
||||
};
|
||||
})
|
||||
.ok(),
|
||||
default_admin_username: _config
|
||||
.get_string(AUTH_DEFAULT_ADMIN_USERNAME_KEY)
|
||||
.ok(),
|
||||
default_admin_password: _config
|
||||
.get_string(AUTH_DEFAULT_ADMIN_PASSWORD_KEY)
|
||||
.ok(),
|
||||
})
|
||||
}
|
||||
|
||||
fn validate(&self) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn mock() -> Self {
|
||||
AuthSettings {
|
||||
jwt_secret: Some("mock_jwt_secret".to_string()),
|
||||
default_admin_username: Some("admin".to_string()),
|
||||
default_admin_password: Some("password".to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,4 +50,13 @@ impl FromConfig for DatabaseSettings {
|
||||
fn validate(&self) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn mock() -> Self {
|
||||
DatabaseSettings {
|
||||
url: "sqlite::memory:".to_string(),
|
||||
max_connections: 5,
|
||||
migrate_on_startup: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,14 @@ pub(crate) const LOGGING_UTC_KEY: &str = "LOGGING.UTC";
|
||||
//
|
||||
pub(crate) const SERVER_ADDRESS_KEY: &str = "SERVER.ADDRESS";
|
||||
pub(crate) const SERVER_PORT_KEY: &str = "SERVER.PORT";
|
||||
pub(crate) const SERVER_SERVE_OPENAPI_KEY: &str = "SERVER.SERVE_OPENAPI";
|
||||
pub(crate) const SERVER_CORS_ALLOWED_ORIGINS_KEY: &str = "SERVER.CORS.ALLOWED_ORIGINS";
|
||||
pub(crate) const SERVER_COOKIES_SECURE_KEY: &str = "SERVER.COOKIES.SECURE";
|
||||
//
|
||||
pub(crate) const DATABASE_URL_KEY: &str = "DATABASE.URL";
|
||||
pub(crate) const DATABASE_MAX_CONNECTIONS_KEY: &str = "DATABASE.MAX_CONNECTIONS";
|
||||
pub(crate) const DATABASE_MIGRATE_ON_STARTUP_KEY: &str = "DATABASE.MIGRATION.MIGRATE_ON_STARTUP";
|
||||
//
|
||||
pub(crate) const AUTH_JWT_SECRET_KEY: &str = "AUTH.JWT_SECRET";
|
||||
pub(crate) const AUTH_DEFAULT_ADMIN_USERNAME_KEY: &str = "AUTH.DEFAULT_ADMIN_USERNAME";
|
||||
pub(crate) const AUTH_DEFAULT_ADMIN_PASSWORD_KEY: &str = "AUTH.DEFAULT_ADMIN_PASSWORD";
|
||||
|
||||
@@ -49,4 +49,12 @@ impl FromConfig for LoggingSettings {
|
||||
fn validate(&self) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn mock() -> Self {
|
||||
LoggingSettings {
|
||||
level: Level::INFO,
|
||||
utc: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,10 @@ use std::net::IpAddr;
|
||||
use config::{Config, ConfigError};
|
||||
use tracing::warn;
|
||||
|
||||
use crate::configs::key::{
|
||||
SERVER_COOKIES_SECURE_KEY, SERVER_CORS_ALLOWED_ORIGINS_KEY, SERVER_SERVE_OPENAPI_KEY,
|
||||
};
|
||||
|
||||
use super::{
|
||||
FromConfig,
|
||||
key::{SERVER_ADDRESS_KEY, SERVER_PORT_KEY},
|
||||
@@ -12,6 +16,19 @@ use super::{
|
||||
pub struct ServerSettings {
|
||||
pub address: IpAddr,
|
||||
pub port: u16,
|
||||
pub serve_openapi: bool,
|
||||
pub cors: CORSSettings,
|
||||
pub cookies: CookiesSettings,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CORSSettings {
|
||||
pub allowed_origins: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CookiesSettings {
|
||||
pub secure: bool,
|
||||
}
|
||||
|
||||
impl FromConfig for ServerSettings {
|
||||
@@ -43,6 +60,53 @@ impl FromConfig for ServerSettings {
|
||||
);
|
||||
DEFAULT_PORT
|
||||
}) as u16,
|
||||
|
||||
serve_openapi: _config
|
||||
.get_bool(SERVER_SERVE_OPENAPI_KEY)
|
||||
.unwrap_or_else(|err| {
|
||||
const DEFAULT_SERVE_OPENAPI: bool = false;
|
||||
warn!(
|
||||
"{} not set or invalid in configuration, defaulting to {}. Error: {}",
|
||||
SERVER_SERVE_OPENAPI_KEY, DEFAULT_SERVE_OPENAPI, err
|
||||
);
|
||||
DEFAULT_SERVE_OPENAPI
|
||||
}),
|
||||
|
||||
cors: CORSSettings {
|
||||
allowed_origins: _config
|
||||
.get_array(SERVER_CORS_ALLOWED_ORIGINS_KEY)
|
||||
.unwrap_or_else(|_| vec![])
|
||||
.into_iter()
|
||||
.filter_map(|val| match val.into_string() {
|
||||
Ok(s) => Some(s),
|
||||
Err(e) => {
|
||||
warn!(
|
||||
"Invalid origin in {} configuration: {}",
|
||||
SERVER_CORS_ALLOWED_ORIGINS_KEY, e
|
||||
);
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
|
||||
cookies: CookiesSettings {
|
||||
secure: _config
|
||||
.get_bool(SERVER_COOKIES_SECURE_KEY)
|
||||
.inspect(|is_secure| {
|
||||
if !*is_secure {
|
||||
warn!("Cookie 'secure' flag is disabled; this is not recommended in production environments.");
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|err| {
|
||||
const DEFAULT_COOKIES_SECURE: bool = true;
|
||||
warn!(
|
||||
"{} not set or invalid in configuration, defaulting to {}. Error: {}",
|
||||
SERVER_COOKIES_SECURE_KEY, DEFAULT_COOKIES_SECURE, err
|
||||
);
|
||||
DEFAULT_COOKIES_SECURE
|
||||
}),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -53,4 +117,17 @@ impl FromConfig for ServerSettings {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn mock() -> Self {
|
||||
ServerSettings {
|
||||
address: "0.0.0.0".parse().unwrap(),
|
||||
port: 8080,
|
||||
serve_openapi: false,
|
||||
cors: CORSSettings {
|
||||
allowed_origins: vec![],
|
||||
},
|
||||
cookies: CookiesSettings { secure: true },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,39 @@
|
||||
pub type ServiceError = Box<dyn std::error::Error + Send + Sync>;
|
||||
use sea_orm::DbErr;
|
||||
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
pub trait IntoServiceError {
|
||||
fn into_service_error(self) -> ServiceError;
|
||||
#[derive(Debug)]
|
||||
pub enum ServiceError {
|
||||
NotFound(String),
|
||||
DatabaseError(String),
|
||||
Unauthorized(String),
|
||||
InternalError(String),
|
||||
BadRequest(String),
|
||||
}
|
||||
|
||||
impl<T> IntoServiceError for T
|
||||
where
|
||||
T: std::error::Error + Send + Sync + 'static,
|
||||
{
|
||||
fn into_service_error(self) -> ServiceError {
|
||||
Box::new(self)
|
||||
impl From<Box<dyn std::error::Error + Send + Sync + 'static>> for ServiceError {
|
||||
fn from(err: Box<dyn std::error::Error + Send + Sync + 'static>) -> Self {
|
||||
ServiceError::InternalError(err.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ServiceError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ServiceError::NotFound(msg) => write!(f, "Not Found: {}", msg),
|
||||
ServiceError::DatabaseError(msg) => write!(f, "Database Error: {}", msg),
|
||||
ServiceError::Unauthorized(msg) => write!(f, "Unauthorized: {}", msg),
|
||||
ServiceError::InternalError(msg) => write!(f, "Internal Error: {}", msg),
|
||||
ServiceError::BadRequest(msg) => write!(f, "Bad Request: {}", msg),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ServiceError {}
|
||||
|
||||
impl From<DbErr> for ServiceError {
|
||||
fn from(err: DbErr) -> Self {
|
||||
match err {
|
||||
DbErr::RecordNotFound(msg) => ServiceError::NotFound(msg),
|
||||
_ => ServiceError::DatabaseError(err.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
2
apps/api/src/helpers.rs
Normal file
2
apps/api/src/helpers.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub mod constants;
|
||||
pub mod database;
|
||||
3
apps/api/src/helpers/constants.rs
Normal file
3
apps/api/src/helpers/constants.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
pub const ADMIN_INIT_SECRET_KEY: &str = "admin_init_secret";
|
||||
//
|
||||
pub const JWT_COOKIE_NAME: &str = "session_jwt";
|
||||
13
apps/api/src/helpers/database.rs
Normal file
13
apps/api/src/helpers/database.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
#[macro_export]
|
||||
macro_rules! with_conn {
|
||||
// Usage: with_conn!(&connection, tx_option, ident, |conn|-> { ... })
|
||||
($conn:expr, $tx:expr, $ident:ident, $body:block) => {{
|
||||
if let Some(t) = &$tx {
|
||||
let $ident = t;
|
||||
$body
|
||||
} else {
|
||||
let $ident = &$conn;
|
||||
$body
|
||||
}
|
||||
}};
|
||||
}
|
||||
7
apps/api/src/log.rs
Normal file
7
apps/api/src/log.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
pub fn make_temporary_subscriber() -> tracing_subscriber::fmt::Subscriber {
|
||||
tracing_subscriber::fmt()
|
||||
.with_max_level(tracing::Level::DEBUG)
|
||||
.with_target(false)
|
||||
.with_level(true)
|
||||
.finish()
|
||||
}
|
||||
@@ -1,136 +1,42 @@
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod cmd;
|
||||
mod configs;
|
||||
mod errors;
|
||||
mod helpers;
|
||||
mod log;
|
||||
mod middlewares;
|
||||
mod routes;
|
||||
mod services;
|
||||
mod tasks;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::Router;
|
||||
use database::get_connection;
|
||||
use sea_orm::ConnectOptions;
|
||||
use tracing::{debug, info};
|
||||
use tracing_subscriber::fmt::format::{DefaultFields, Format};
|
||||
|
||||
use crate::{
|
||||
configs::{ProgramSettings, get_program_settings, logging::LoggingSettings},
|
||||
routes::{AppService, AppState},
|
||||
services::settings::SettingsService,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
// Temporary subscriber for initial logging during configuration reading
|
||||
let make_temporary_subscriber = || {
|
||||
tracing_subscriber::fmt()
|
||||
.with_max_level(tracing::Level::DEBUG)
|
||||
.with_target(false)
|
||||
.with_level(true)
|
||||
.finish()
|
||||
};
|
||||
|
||||
let settings =
|
||||
tracing::subscriber::with_default(make_temporary_subscriber(), || -> ProgramSettings {
|
||||
debug!("Temporary subscriber installed.");
|
||||
info!("Reading configuration...");
|
||||
let settings = get_program_settings();
|
||||
info!("Configuration read successfully.");
|
||||
debug!("Resetting global subscriber...");
|
||||
|
||||
let subscriber = get_global_tracing_subscriber_builder(&settings.logging).finish();
|
||||
tracing::subscriber::set_global_default(subscriber)
|
||||
.expect("Failed to set global default subscriber");
|
||||
|
||||
debug!(
|
||||
"Global subscriber set with logging level: {:?}",
|
||||
settings.logging.level
|
||||
);
|
||||
|
||||
settings
|
||||
});
|
||||
|
||||
tasks::startup::run_startup_tasks(&settings)
|
||||
.await
|
||||
.expect("Failed to run startup tasks");
|
||||
|
||||
// setup database connection pool
|
||||
info!("Establishing database connection...");
|
||||
debug!("Database URL: {}", settings.database.url);
|
||||
|
||||
let db_options = |options: &mut ConnectOptions| {
|
||||
options.max_connections(settings.database.max_connections);
|
||||
};
|
||||
|
||||
let db_connection = Arc::new(
|
||||
get_connection(&settings.database.url, Some(db_options))
|
||||
.await
|
||||
.expect("Failed to establish database connection"),
|
||||
);
|
||||
|
||||
info!("Database connection established.");
|
||||
|
||||
// build the axum app and run the server...
|
||||
info!("Starting application...");
|
||||
let app: Router = routes::get_root_router(Arc::new(get_app_state(&db_connection)));
|
||||
|
||||
let address = format!("{}:{}", settings.server.address, settings.server.port);
|
||||
info!("Starting server at http://{}", address);
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(address)
|
||||
.await
|
||||
.expect("Failed to bind to address");
|
||||
|
||||
axum::serve(listener, app)
|
||||
.await
|
||||
.expect("Failed to run the server");
|
||||
}
|
||||
|
||||
fn get_global_tracing_subscriber_builder(
|
||||
settings: &LoggingSettings,
|
||||
) -> tracing_subscriber::fmt::SubscriberBuilder<
|
||||
DefaultFields,
|
||||
Format<tracing_subscriber::fmt::format::Full, BoxedTimer>,
|
||||
> {
|
||||
// After configuration is read, install the global subscriber
|
||||
let builder = tracing_subscriber::fmt()
|
||||
.with_max_level(settings.level)
|
||||
.with_target(false)
|
||||
.with_level(true);
|
||||
|
||||
if settings.utc {
|
||||
builder.with_timer(BoxedTimer(Box::new(
|
||||
tracing_subscriber::fmt::time::UtcTime::rfc_3339(),
|
||||
)))
|
||||
} else {
|
||||
builder.with_timer(BoxedTimer(Box::new(
|
||||
tracing_subscriber::fmt::time::ChronoLocal::rfc_3339(),
|
||||
)))
|
||||
// If there are command-line arguments, treat it as a CLI command
|
||||
if std::env::args().len() > 1 {
|
||||
tracing::subscriber::with_default(log::make_temporary_subscriber(), || {
|
||||
use clap::error::ErrorKind;
|
||||
//
|
||||
let mut command = cmd::get_command();
|
||||
let help_output = format!("{}", command.render_help());
|
||||
let matches = command
|
||||
.try_get_matches()
|
||||
.unwrap_or_else(|err| match err.kind() {
|
||||
ErrorKind::DisplayHelp | ErrorKind::DisplayVersion => {
|
||||
err.print().expect("Error writing Error");
|
||||
std::process::exit(0);
|
||||
}
|
||||
_ => {
|
||||
err.print().expect("Error writing Error");
|
||||
std::process::exit(1);
|
||||
}
|
||||
});
|
||||
cmd::execute(&matches, &help_output)
|
||||
})
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
fn get_app_state(db_connection: &Arc<sea_orm::DatabaseConnection>) -> AppState {
|
||||
AppState {
|
||||
database_connection: db_connection.clone(),
|
||||
service: Arc::new(AppService {
|
||||
settings: Arc::new(SettingsService::new(db_connection.clone())),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
// A small wrapper that holds a boxed `FormatTime` trait object and itself
|
||||
// implements `FormatTime`, allowing us to use it as a concrete type with
|
||||
// `builder.with_timer` while still picking the concrete timer implementation
|
||||
// at runtime.
|
||||
// wrapper type to hold boxed timers and implement the `FormatTime` trait for
|
||||
// a concrete type so `with_timer` may be called once outside the conditional.
|
||||
struct BoxedTimer(Box<dyn tracing_subscriber::fmt::time::FormatTime + Send + Sync + 'static>);
|
||||
|
||||
impl tracing_subscriber::fmt::time::FormatTime for BoxedTimer {
|
||||
fn format_time(
|
||||
&self,
|
||||
w: &mut tracing_subscriber::fmt::format::Writer<'_>,
|
||||
) -> std::result::Result<(), std::fmt::Error> {
|
||||
self.0.format_time(w)
|
||||
}
|
||||
// No command-line arguments, start the server normally
|
||||
cmd::start_server().await;
|
||||
}
|
||||
|
||||
@@ -1,25 +1,60 @@
|
||||
pub mod request_info;
|
||||
pub mod require_auth;
|
||||
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use axum::{
|
||||
BoxError, Router,
|
||||
error_handling::HandleErrorLayer,
|
||||
http::{Method, StatusCode, Uri},
|
||||
http::{HeaderValue, Method, StatusCode, Uri},
|
||||
};
|
||||
use std::time::Duration;
|
||||
use tower::{ServiceBuilder, timeout::TimeoutLayer};
|
||||
|
||||
use tower_http::cors::{AllowHeaders, AllowOrigin, CorsLayer};
|
||||
use tracing::warn;
|
||||
|
||||
use crate::{configs::server::CORSSettings, routes::AppState};
|
||||
|
||||
pub const TIMEOUT_DURATION_SECS: u64 = 30;
|
||||
|
||||
pub fn apply_root_middleware(router: Router) -> Router {
|
||||
pub fn apply_root_middleware(
|
||||
router: Router,
|
||||
_state: Arc<AppState>,
|
||||
cors_settings: Arc<CORSSettings>,
|
||||
) -> Router {
|
||||
let timeout_layer = TimeoutLayer::new(Duration::from_secs(TIMEOUT_DURATION_SECS));
|
||||
|
||||
let service_builder = ServiceBuilder::new()
|
||||
.layer(HandleErrorLayer::new(handle_timeout_error))
|
||||
.layer(timeout_layer);
|
||||
.layer(timeout_layer)
|
||||
.layer(get_cors_layer(cors_settings));
|
||||
|
||||
router.layer(service_builder)
|
||||
}
|
||||
|
||||
pub fn get_cors_layer(cors_settings: Arc<CORSSettings>) -> CorsLayer {
|
||||
let mut cors_layer = CorsLayer::new()
|
||||
.allow_credentials(true)
|
||||
.allow_headers(AllowHeaders::mirror_request());
|
||||
|
||||
let allowed_origins = &cors_settings.allowed_origins;
|
||||
if allowed_origins.contains(&"*".to_string()) {
|
||||
cors_layer = cors_layer.allow_origin(AllowOrigin::mirror_request());
|
||||
warn!(
|
||||
"Wildcard origin is found in allowed origins. CORS is configured to allow requests from any origin. Only use this setting in development or if you understand the security implications."
|
||||
);
|
||||
} else {
|
||||
for origin in allowed_origins {
|
||||
if let Ok(header_value) = HeaderValue::from_str(origin) {
|
||||
cors_layer = cors_layer.allow_origin(AllowOrigin::exact(header_value));
|
||||
} else {
|
||||
warn!("Invalid CORS origin: {}", origin);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cors_layer
|
||||
}
|
||||
|
||||
pub async fn handle_timeout_error(
|
||||
method: Method,
|
||||
uri: Uri,
|
||||
|
||||
6
apps/api/src/middlewares/request_info.rs
Normal file
6
apps/api/src/middlewares/request_info.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RequestInfo {
|
||||
pub user_id: Option<Uuid>,
|
||||
}
|
||||
70
apps/api/src/middlewares/require_auth.rs
Normal file
70
apps/api/src/middlewares/require_auth.rs
Normal file
@@ -0,0 +1,70 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{
|
||||
extract::State,
|
||||
http::{Request, StatusCode},
|
||||
middleware::Next,
|
||||
response::Response,
|
||||
};
|
||||
use axum_extra::extract::cookie::CookieJar;
|
||||
use tracing::debug;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
errors::service_error::ServiceError, helpers::constants::JWT_COOKIE_NAME,
|
||||
middlewares::request_info::RequestInfo, routes::AppState,
|
||||
};
|
||||
|
||||
pub async fn require_auth(
|
||||
cookies: CookieJar,
|
||||
State(state): State<Arc<AppState>>,
|
||||
req: Request<axum::body::Body>,
|
||||
next: Next,
|
||||
) -> Result<Response, StatusCode> {
|
||||
// get jwt from cookies
|
||||
let auth_service = &state.service.auth_state.authentication;
|
||||
let token = if let Some(cookie) = cookies.get(JWT_COOKIE_NAME) {
|
||||
cookie.value().to_string()
|
||||
} else {
|
||||
debug!("No JWT cookie found. cookies: {:?}", cookies);
|
||||
return handle_unauthenticated().await;
|
||||
};
|
||||
|
||||
// validate jwt
|
||||
let is_valid = auth_service.is_valid_jwt(&token, None).await;
|
||||
let user_id = match is_valid {
|
||||
Ok(Some(claims)) => claims
|
||||
.sub
|
||||
.parse::<Uuid>()
|
||||
.map_err(|_| StatusCode::UNAUTHORIZED)?,
|
||||
Ok(None) => return handle_unauthenticated().await,
|
||||
Err(err) => {
|
||||
tracing::error!("Error validating JWT: {}", err);
|
||||
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
};
|
||||
|
||||
// ensure user exists
|
||||
if let Err(err) = state.service.user.get_user_by_id(user_id, None).await {
|
||||
match err {
|
||||
ServiceError::NotFound(_) => return handle_unauthenticated().await,
|
||||
_ => {
|
||||
tracing::error!("Error fetching user by ID: {}", err);
|
||||
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut req = req;
|
||||
let user = req
|
||||
.extensions_mut()
|
||||
.get_or_insert_with(|| RequestInfo { user_id: None });
|
||||
user.user_id = Some(user_id);
|
||||
|
||||
Ok(next.run(req).await)
|
||||
}
|
||||
|
||||
async fn handle_unauthenticated() -> Result<Response, StatusCode> {
|
||||
// TODO: log unauthenticated access attempts
|
||||
Err(StatusCode::UNAUTHORIZED)
|
||||
}
|
||||
@@ -1,33 +1,65 @@
|
||||
mod api;
|
||||
mod view;
|
||||
|
||||
pub use self::api::ApiDoc;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{Extension, Router};
|
||||
use migration::sea_orm::DatabaseConnection;
|
||||
|
||||
use crate::{middlewares, services::settings::SettingsStore};
|
||||
use crate::{
|
||||
configs::{ProgramSettings, server::CORSSettings},
|
||||
middlewares,
|
||||
services::{
|
||||
auth::{
|
||||
authentication::{AuthenticationService, strategies::password::PasswordStrategy},
|
||||
user::UserService,
|
||||
},
|
||||
server_state::ServerStateStore,
|
||||
settings::SettingsStore,
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
// TODO: remove dead_code allowances when fields are used
|
||||
#[allow(dead_code)]
|
||||
pub database_connection: Arc<DatabaseConnection>,
|
||||
// TODO: remove dead_code allowances when fields are used
|
||||
#[allow(dead_code)]
|
||||
pub service: Arc<AppService>,
|
||||
pub config: Arc<ProgramSettings>,
|
||||
}
|
||||
|
||||
pub type ServiceState<T> = Arc<T>;
|
||||
|
||||
pub struct AppService {
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
pub settings: ServiceState<dyn SettingsStore>,
|
||||
pub struct AuthStrategy {
|
||||
pub password: ServiceState<PasswordStrategy>,
|
||||
}
|
||||
|
||||
pub fn get_root_router(state: impl Into<Arc<AppState>>) -> Router {
|
||||
pub struct AuthState {
|
||||
pub strategy: AuthStrategy,
|
||||
pub authentication: ServiceState<dyn AuthenticationService>,
|
||||
}
|
||||
|
||||
pub struct AppService {
|
||||
pub settings: ServiceState<dyn SettingsStore>,
|
||||
pub auth_state: AuthState,
|
||||
pub user: ServiceState<dyn UserService>,
|
||||
pub server_state: ServiceState<dyn ServerStateStore>,
|
||||
}
|
||||
|
||||
pub fn get_root_router(
|
||||
state: impl Into<Arc<AppState>>,
|
||||
cors_settings: Arc<CORSSettings>,
|
||||
) -> Router {
|
||||
let mut router = Router::new();
|
||||
let state = state.into();
|
||||
|
||||
router = middlewares::apply_root_middleware(router);
|
||||
router = router
|
||||
.nest("/api", api::get_api_router(state.clone()))
|
||||
.merge(view::get_view_router());
|
||||
|
||||
router = router.layer(Extension(state.into()));
|
||||
router = middlewares::apply_root_middleware(router, state.clone(), cors_settings);
|
||||
|
||||
router = router.layer(Extension(state.clone()));
|
||||
|
||||
router
|
||||
}
|
||||
|
||||
25
apps/api/src/routes/api.rs
Normal file
25
apps/api/src/routes/api.rs
Normal file
@@ -0,0 +1,25 @@
|
||||
mod auth;
|
||||
mod health;
|
||||
mod openapi;
|
||||
mod restricted;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::routes::AppState;
|
||||
|
||||
pub use self::openapi::ApiDoc;
|
||||
|
||||
use axum::{Router, response::IntoResponse, routing::any};
|
||||
|
||||
pub fn get_api_router(state: Arc<AppState>) -> Router {
|
||||
Router::new()
|
||||
.nest("/health", health::get_health_router(state.clone()))
|
||||
.merge(auth::get_basic_auth_router(state.clone()))
|
||||
.merge(restricted::get_restricted_router(state.clone()))
|
||||
// explicit fallback for unmatched API routes
|
||||
.route("/{*wildcard}", any(api_fallback_handler))
|
||||
}
|
||||
|
||||
async fn api_fallback_handler() -> impl IntoResponse {
|
||||
(axum::http::StatusCode::NOT_FOUND, "API route not found").into_response()
|
||||
}
|
||||
15
apps/api/src/routes/api/auth.rs
Normal file
15
apps/api/src/routes/api/auth.rs
Normal file
@@ -0,0 +1,15 @@
|
||||
pub mod init_admin;
|
||||
pub mod login;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{Router, routing::post};
|
||||
|
||||
use crate::routes::AppState;
|
||||
|
||||
pub fn get_basic_auth_router(state: Arc<AppState>) -> Router {
|
||||
Router::new()
|
||||
.route("/auth/login", post(login::login))
|
||||
.route("/auth/init_admin", post(init_admin::init_admin))
|
||||
.with_state(state)
|
||||
}
|
||||
143
apps/api/src/routes/api/auth/init_admin.rs
Normal file
143
apps/api/src/routes/api/auth/init_admin.rs
Normal file
@@ -0,0 +1,143 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{
|
||||
Json,
|
||||
extract::State,
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use database::generated::entities::user;
|
||||
use sea_orm::{ColumnTrait, EntityTrait, QueryFilter, TransactionTrait};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, from_value};
|
||||
use tracing::{debug, error, info, warn};
|
||||
|
||||
use crate::{
|
||||
helpers::constants::ADMIN_INIT_SECRET_KEY,
|
||||
routes::{AppState, api::openapi::tag::AUTH_TAG},
|
||||
services::auth::user::NewUser,
|
||||
};
|
||||
|
||||
/// Login request payload
|
||||
#[derive(Serialize, Deserialize, utoipa::ToSchema)]
|
||||
pub struct AdminInitRequest {
|
||||
username: String,
|
||||
password: String,
|
||||
// The secret key required to initialize the admin user
|
||||
setup_secret: String,
|
||||
}
|
||||
|
||||
/// Initializes the admin user
|
||||
///
|
||||
/// Initializes the admin user if no admin user exists and the correct setup secret is provided.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/auth/init_admin",
|
||||
request_body = AdminInitRequest,
|
||||
responses(
|
||||
(status = 200, description = "Admin user initialized successfully"),
|
||||
(status = 400, description = "Invalid request payload"),
|
||||
(status = 401, description = "Unauthorized: Admin user already exists or invalid setup secret"),
|
||||
(status = 500, description = "Internal server error"),
|
||||
),
|
||||
tag = AUTH_TAG,
|
||||
)]
|
||||
pub async fn init_admin(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Json(payload): Json<Value>,
|
||||
) -> Response {
|
||||
if user::Entity::find()
|
||||
.filter(user::Column::IsAdmin.eq(true))
|
||||
.filter(user::Column::IsActive.eq(true))
|
||||
.one(state.database_connection.as_ref())
|
||||
.await
|
||||
.map_err(|err| {
|
||||
error!("Failed to query for existing admin user: {}", err);
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})
|
||||
.unwrap_or(None)
|
||||
.is_some()
|
||||
{
|
||||
warn!("Admin user already exists. Skipping admin initialization.");
|
||||
return (StatusCode::UNAUTHORIZED).into_response();
|
||||
}
|
||||
|
||||
let init_request: AdminInitRequest = match from_value(payload) {
|
||||
Ok(req) => req,
|
||||
Err(e) => {
|
||||
warn!("Invalid login request: {}", e);
|
||||
return (StatusCode::BAD_REQUEST).into_response();
|
||||
}
|
||||
};
|
||||
|
||||
let admin_secret = match state
|
||||
.service
|
||||
.settings
|
||||
.get_setting(ADMIN_INIT_SECRET_KEY)
|
||||
.await
|
||||
{
|
||||
Ok(secret) => secret,
|
||||
Err(e) => {
|
||||
error!(
|
||||
"Failed to retrieve admin initialization secret. Invalid internal state?: {}",
|
||||
e
|
||||
);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR).into_response();
|
||||
}
|
||||
};
|
||||
|
||||
if init_request.setup_secret != admin_secret {
|
||||
info!("{},{}", init_request.setup_secret, admin_secret);
|
||||
warn!("Invalid admin initialization secret provided.");
|
||||
return (StatusCode::UNAUTHORIZED).into_response();
|
||||
}
|
||||
|
||||
let mut tx = match state.database_connection.begin().await {
|
||||
Ok(tx) => tx,
|
||||
Err(e) => {
|
||||
error!("Failed to start transaction: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR).into_response();
|
||||
}
|
||||
};
|
||||
|
||||
let user = match state
|
||||
.service
|
||||
.user
|
||||
.create_user(
|
||||
NewUser {
|
||||
username: init_request.username,
|
||||
is_admin: true,
|
||||
},
|
||||
Some(&mut tx),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(user) => user,
|
||||
Err(e) => {
|
||||
error!("Failed to initialize admin user: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR).into_response();
|
||||
}
|
||||
};
|
||||
|
||||
debug!("Created admin user with ID: {}", user.id);
|
||||
match state
|
||||
.service
|
||||
.auth_state
|
||||
.strategy
|
||||
.password
|
||||
.create_identity(user.id, &init_request.password, Some(&mut tx))
|
||||
.await
|
||||
{
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
error!("Failed to create admin user identity: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR).into_response();
|
||||
}
|
||||
};
|
||||
|
||||
tx.commit().await.unwrap_or_else(|e| {
|
||||
error!("Failed to commit transaction: {}", e);
|
||||
});
|
||||
|
||||
(StatusCode::OK).into_response()
|
||||
}
|
||||
107
apps/api/src/routes/api/auth/login.rs
Normal file
107
apps/api/src/routes/api/auth/login.rs
Normal file
@@ -0,0 +1,107 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{
|
||||
Json,
|
||||
body::Body,
|
||||
extract::State,
|
||||
http::{StatusCode, header::SET_COOKIE},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, from_value};
|
||||
use tracing::{error, warn};
|
||||
|
||||
use crate::{
|
||||
helpers::constants::JWT_COOKIE_NAME,
|
||||
routes::{AppState, api::openapi::tag::AUTH_TAG},
|
||||
};
|
||||
|
||||
/// Login request payload
|
||||
#[derive(Serialize, Deserialize, utoipa::ToSchema)]
|
||||
pub struct LoginRequest {
|
||||
username: String,
|
||||
password: String,
|
||||
}
|
||||
|
||||
/// Login endpoint
|
||||
///
|
||||
/// Authenticates a user and returns a JWT in an HttpOnly cookie.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/auth/login",
|
||||
request_body = LoginRequest,
|
||||
responses(
|
||||
(status = 200, description = "User authenticated successfully", body = ()),
|
||||
(status = 401, description = "Authentication failed"),
|
||||
(status = 500, description = "Internal server error"),
|
||||
),
|
||||
tag = AUTH_TAG,
|
||||
)]
|
||||
pub async fn login(State(state): State<Arc<AppState>>, Json(payload): Json<Value>) -> Response {
|
||||
let login_request: LoginRequest = match from_value(payload) {
|
||||
Ok(req) => req,
|
||||
Err(e) => {
|
||||
warn!("Invalid login request: {}", e);
|
||||
return (StatusCode::BAD_REQUEST).into_response();
|
||||
}
|
||||
};
|
||||
|
||||
let user_id = match state
|
||||
.service
|
||||
.auth_state
|
||||
.strategy
|
||||
.password
|
||||
.authenticate(&login_request.username, &login_request.password, None)
|
||||
.await
|
||||
{
|
||||
Ok(user_id) => user_id,
|
||||
Err(e) => {
|
||||
warn!(
|
||||
"Authentication failed for user {}: {}",
|
||||
login_request.username, e
|
||||
);
|
||||
return (StatusCode::UNAUTHORIZED).into_response();
|
||||
}
|
||||
};
|
||||
|
||||
let (jwt, claims) = match state
|
||||
.service
|
||||
.auth_state
|
||||
.authentication
|
||||
.generate_jwt(user_id, 3600)
|
||||
.await
|
||||
{
|
||||
Ok(token) => token,
|
||||
Err(e) => {
|
||||
error!("Error generating JWT for user {}: {}", user_id, e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR).into_response();
|
||||
}
|
||||
};
|
||||
|
||||
let response_builder = Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
// add jwt as cookie
|
||||
.header(
|
||||
SET_COOKIE,
|
||||
format!(
|
||||
"{}={}; HttpOnly; Path=/; Max-Age={}; SameSite=Strict;{}",
|
||||
JWT_COOKIE_NAME,
|
||||
jwt,
|
||||
claims.exp - claims.iat,
|
||||
if state.config.server.cookies.secure {
|
||||
" Secure;"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
),
|
||||
)
|
||||
.body(Body::from(()));
|
||||
|
||||
match response_builder {
|
||||
Ok(resp) => resp,
|
||||
Err(e) => {
|
||||
error!("Error building response: {}", e);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR).into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
17
apps/api/src/routes/api/health.rs
Normal file
17
apps/api/src/routes/api/health.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
pub mod info;
|
||||
mod state;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{Router, routing::get};
|
||||
|
||||
use crate::routes::{AppState, api::health::state::AppStateWithHealth};
|
||||
|
||||
pub fn get_health_router(app_state: Arc<AppState>) -> Router {
|
||||
Router::new()
|
||||
.route("/info", get(info::get_health_info))
|
||||
.with_state(Arc::new(AppStateWithHealth {
|
||||
app_state: app_state.clone(),
|
||||
health_state: Arc::new(state::HealthState::default()),
|
||||
}))
|
||||
}
|
||||
149
apps/api/src/routes/api/health/info.rs
Normal file
149
apps/api/src/routes/api/health/info.rs
Normal file
@@ -0,0 +1,149 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{Json, extract::State, http::StatusCode};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tracing::error;
|
||||
|
||||
use crate::routes::api::{health::state::AppStateWithHealth, openapi::tag::HEALTH_TAG};
|
||||
|
||||
const STATUS_HEALTHY: &str = "healthy";
|
||||
const STATUS_UNHEALTHY: &str = "unhealthy";
|
||||
|
||||
/// System health information
|
||||
#[derive(Serialize, Deserialize, utoipa::ToSchema)]
|
||||
pub struct HealthInfo {
|
||||
/// Health status: "healthy" or "unhealthy"
|
||||
pub status: String,
|
||||
/// Application version
|
||||
pub version: String,
|
||||
/// RFC 3339 formatted timestamp
|
||||
pub up_since: DateTime<Utc>,
|
||||
/// List of error messages if unhealthy
|
||||
pub errors: Option<Vec<String>>,
|
||||
/// Is initialized
|
||||
pub is_initialized: bool,
|
||||
}
|
||||
|
||||
/// Health check endpoint
|
||||
///
|
||||
/// Returns the health status, version, uptime, and any errors if unhealthy.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/health/info",
|
||||
responses(
|
||||
(status = 200, description = "Health information retrieved successfully", body = HealthInfo),
|
||||
(status = NOT_FOUND, description = "Health information not found")
|
||||
),
|
||||
tag = HEALTH_TAG,
|
||||
)]
|
||||
pub async fn get_health_info(
|
||||
State(app_state_with_health): State<Arc<AppStateWithHealth>>,
|
||||
) -> (StatusCode, Json<HealthInfo>) {
|
||||
#[allow(unused_mut)]
|
||||
let mut errors = vec![];
|
||||
|
||||
let is_healthy = errors.is_empty();
|
||||
let health_state = &app_state_with_health.health_state;
|
||||
let app_state = &app_state_with_health.app_state;
|
||||
|
||||
let is_initialized = match app_state.service.server_state.is_server_initialized().await {
|
||||
Ok(initialized) => initialized,
|
||||
Err(err) => {
|
||||
errors.push("Failed to determine if server is initialized".to_string());
|
||||
error!("Error checking server initialization status: {}", err);
|
||||
false
|
||||
}
|
||||
};
|
||||
|
||||
(
|
||||
if is_healthy {
|
||||
StatusCode::OK
|
||||
} else {
|
||||
StatusCode::SERVICE_UNAVAILABLE
|
||||
},
|
||||
Json(HealthInfo {
|
||||
status: if is_healthy {
|
||||
STATUS_HEALTHY.into()
|
||||
} else {
|
||||
STATUS_UNHEALTHY.into()
|
||||
},
|
||||
version: env!("CARGO_PKG_VERSION").into(),
|
||||
up_since: *health_state.get_start_at(),
|
||||
errors: if is_healthy { None } else { Some(errors) },
|
||||
is_initialized,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::configs::FromConfig;
|
||||
use crate::{
|
||||
routes::{AppState, api::health::state::HealthState},
|
||||
services::{
|
||||
auth::{
|
||||
authentication::{
|
||||
AuthenticationServiceImpl, strategies::password::PasswordStrategy,
|
||||
},
|
||||
user::UserServiceImpl,
|
||||
},
|
||||
server_state::ServerStateService,
|
||||
settings::SettingsService,
|
||||
},
|
||||
};
|
||||
|
||||
use super::*;
|
||||
use axum::body::to_bytes;
|
||||
use axum::{
|
||||
Router,
|
||||
body::Body,
|
||||
http::{Request, StatusCode},
|
||||
};
|
||||
use sea_orm::MockDatabase;
|
||||
use tower::ServiceExt;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_get_health_info() {
|
||||
let health_state = Arc::new(HealthState::default());
|
||||
let db = MockDatabase::new(sea_orm::DatabaseBackend::Sqlite)
|
||||
.append_query_results(vec![Vec::<sea_orm::MockRow>::new()])
|
||||
.into_connection();
|
||||
let db = Arc::new(db);
|
||||
|
||||
let app_state = Arc::new(AppState {
|
||||
database_connection: db.clone(),
|
||||
config: Arc::new(crate::configs::ProgramSettings::mock()),
|
||||
service: Arc::new(crate::routes::AppService {
|
||||
settings: Arc::new(SettingsService::new(db.clone())),
|
||||
auth_state: crate::routes::AuthState {
|
||||
strategy: crate::routes::AuthStrategy {
|
||||
password: Arc::new(PasswordStrategy::new(db.clone())),
|
||||
},
|
||||
authentication: Arc::new(AuthenticationServiceImpl::new(None)),
|
||||
},
|
||||
user: Arc::new(UserServiceImpl::new(db.clone())),
|
||||
server_state: Arc::new(ServerStateService::new(db.clone())),
|
||||
}),
|
||||
});
|
||||
|
||||
let app = Router::new()
|
||||
.route("/info", axum::routing::get(get_health_info))
|
||||
.with_state(Arc::new(AppStateWithHealth {
|
||||
app_state: app_state.clone(),
|
||||
health_state: health_state.clone(),
|
||||
}));
|
||||
|
||||
let response = app
|
||||
.oneshot(Request::builder().uri("/info").body(Body::empty()).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = to_bytes(response.into_body(), 1024 * 1024).await.unwrap(); // Set limit to 1 MB
|
||||
let health_info: HealthInfo = serde_json::from_slice(&body).unwrap();
|
||||
assert_eq!(health_info.status, STATUS_HEALTHY);
|
||||
assert_eq!(health_info.version, env!("CARGO_PKG_VERSION"));
|
||||
assert!(health_info.errors.is_none());
|
||||
}
|
||||
}
|
||||
28
apps/api/src/routes/api/health/state.rs
Normal file
28
apps/api/src/routes/api/health/state.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
use crate::routes::AppState;
|
||||
|
||||
pub struct AppStateWithHealth {
|
||||
pub app_state: Arc<AppState>,
|
||||
pub health_state: Arc<HealthState>,
|
||||
}
|
||||
|
||||
pub struct HealthState {
|
||||
start_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl Default for HealthState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
start_at: Utc::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HealthState {
|
||||
pub fn get_start_at(&self) -> &DateTime<Utc> {
|
||||
&self.start_at
|
||||
}
|
||||
}
|
||||
32
apps/api/src/routes/api/openapi.rs
Normal file
32
apps/api/src/routes/api/openapi.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
pub mod tag {
|
||||
/// Health tag constant
|
||||
pub const HEALTH_TAG: &str = "Health";
|
||||
pub const AUTH_TAG: &str = "Authentication";
|
||||
pub const USER_TAG: &str = "User";
|
||||
}
|
||||
|
||||
#[derive(utoipa::OpenApi)]
|
||||
#[openapi(
|
||||
paths(
|
||||
crate::routes::api::health::info::get_health_info,
|
||||
// Authentication paths
|
||||
crate::routes::api::auth::login::login,
|
||||
crate::routes::api::auth::init_admin::init_admin,
|
||||
// User management paths
|
||||
crate::routes::api::restricted::user::me::get_user_info,
|
||||
),
|
||||
components(
|
||||
schemas(crate::routes::api::health::info::HealthInfo),
|
||||
// Authentication schemas
|
||||
schemas(crate::routes::api::auth::login::LoginRequest),
|
||||
schemas(crate::routes::api::auth::init_admin::AdminInitRequest),
|
||||
// User management schemas
|
||||
schemas(crate::routes::api::restricted::user::me::UserInfo),
|
||||
),
|
||||
tags(
|
||||
(name = tag::HEALTH_TAG, description = "Health information API"),
|
||||
(name = tag::AUTH_TAG, description = "Authentication API"),
|
||||
(name = tag::USER_TAG, description = "User management API")
|
||||
)
|
||||
)]
|
||||
pub struct ApiDoc;
|
||||
16
apps/api/src/routes/api/restricted.rs
Normal file
16
apps/api/src/routes/api/restricted.rs
Normal file
@@ -0,0 +1,16 @@
|
||||
pub mod user;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::Router;
|
||||
|
||||
use crate::{middlewares::require_auth::require_auth, routes::AppState};
|
||||
|
||||
pub fn get_restricted_router(state: Arc<AppState>) -> Router {
|
||||
Router::new()
|
||||
.nest("/user", user::get_user_router(state.clone()))
|
||||
.layer(axum::middleware::from_fn_with_state(
|
||||
state.clone(),
|
||||
require_auth,
|
||||
))
|
||||
}
|
||||
13
apps/api/src/routes/api/restricted/user.rs
Normal file
13
apps/api/src/routes/api/restricted/user.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
pub mod me;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::Router;
|
||||
|
||||
use crate::routes::AppState;
|
||||
|
||||
pub fn get_user_router(state: Arc<AppState>) -> Router {
|
||||
Router::new()
|
||||
.route("/me", axum::routing::get(me::get_user_info))
|
||||
.with_state(state)
|
||||
}
|
||||
64
apps/api/src/routes/api/restricted/user/me.rs
Normal file
64
apps/api/src/routes/api/restricted/user/me.rs
Normal file
@@ -0,0 +1,64 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{
|
||||
Extension, Json,
|
||||
extract::State,
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tracing::error;
|
||||
|
||||
use crate::{
|
||||
middlewares::request_info::RequestInfo,
|
||||
routes::{AppState, api::openapi::tag::USER_TAG},
|
||||
};
|
||||
|
||||
/// System health information
|
||||
#[derive(Serialize, Deserialize, utoipa::ToSchema)]
|
||||
pub struct UserInfo {
|
||||
/// User ID
|
||||
pub id: uuid::Uuid,
|
||||
/// Username
|
||||
pub username: String,
|
||||
}
|
||||
|
||||
/// Get current user information
|
||||
///
|
||||
/// Returns the information of the currently authenticated user.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/user/me",
|
||||
responses(
|
||||
(status = 200, description = "User information retrieved successfully", body = UserInfo),
|
||||
(status = 401, description = "Unauthorized"),
|
||||
(status = 500, description = "Internal server error"),
|
||||
),
|
||||
tag = USER_TAG,
|
||||
)]
|
||||
pub async fn get_user_info(
|
||||
State(app_state): State<Arc<AppState>>,
|
||||
request_info: Extension<Arc<RequestInfo>>,
|
||||
) -> Response {
|
||||
let user_id = match request_info.user_id {
|
||||
Some(id) => id,
|
||||
None => {
|
||||
error!("User ID not found in request info");
|
||||
return (StatusCode::UNAUTHORIZED).into_response();
|
||||
}
|
||||
};
|
||||
|
||||
match app_state.service.user.get_user_by_id(user_id, None).await {
|
||||
Ok(user) => {
|
||||
let user_info = UserInfo {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
};
|
||||
(StatusCode::OK, Json(user_info)).into_response()
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Error fetching user info: {}", err);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR).into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
71
apps/api/src/routes/view.rs
Normal file
71
apps/api/src/routes/view.rs
Normal file
@@ -0,0 +1,71 @@
|
||||
use axum::{
|
||||
Router,
|
||||
body::Bytes,
|
||||
extract::Path,
|
||||
http::{StatusCode, header},
|
||||
response::IntoResponse,
|
||||
routing::{MethodRouter, get},
|
||||
};
|
||||
use include_dir::{Dir, include_dir};
|
||||
use mime_guess::from_path;
|
||||
|
||||
static DIST_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/../frontend/build/client");
|
||||
const INDEX_HTML_PATH: &str = "index.html";
|
||||
const INDEX_FILE_NOT_FOUND_HTML: &str = r#"
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>404 Not Found</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>404 Not Found</h1>
|
||||
<p>The requested resource was not found on this server. Possibly the frontend build is missing or corrupted.</p>
|
||||
</body>
|
||||
</html>
|
||||
"#;
|
||||
|
||||
pub fn get_view_router() -> Router {
|
||||
Router::new()
|
||||
// Serve the root index.html
|
||||
.route("/", get(root_view_handler))
|
||||
.route(
|
||||
"/{*wildcard}",
|
||||
MethodRouter::new()
|
||||
.get(|Path(path): Path<String>| async move { view_handler(Some(path)).await }),
|
||||
)
|
||||
}
|
||||
|
||||
async fn root_view_handler() -> impl IntoResponse {
|
||||
view_handler(None).await
|
||||
}
|
||||
|
||||
async fn view_handler(path: Option<String>) -> impl IntoResponse {
|
||||
// If path is empty, serve index.html
|
||||
let incoming_path = if let Some(p) = path {
|
||||
p.trim_start_matches('/').to_string()
|
||||
} else {
|
||||
INDEX_HTML_PATH.to_string()
|
||||
};
|
||||
|
||||
let path = match DIST_DIR.get_file(&incoming_path) {
|
||||
Some(_) => incoming_path,
|
||||
None => INDEX_HTML_PATH.to_string(),
|
||||
};
|
||||
|
||||
match DIST_DIR.get_file(&path) {
|
||||
Some(file) => {
|
||||
let mime = from_path(&path).first_or_octet_stream();
|
||||
let body: Bytes = Bytes::copy_from_slice(file.contents());
|
||||
([(header::CONTENT_TYPE, mime.as_ref())], body).into_response()
|
||||
}
|
||||
// This should never happen, but just in case...
|
||||
None => (
|
||||
StatusCode::NOT_FOUND,
|
||||
[(header::CONTENT_TYPE, "text/plain")],
|
||||
Bytes::from(INDEX_FILE_NOT_FOUND_HTML),
|
||||
)
|
||||
.into_response(),
|
||||
}
|
||||
}
|
||||
@@ -1 +1,3 @@
|
||||
pub mod auth;
|
||||
pub mod server_state;
|
||||
pub mod settings;
|
||||
|
||||
2
apps/api/src/services/auth.rs
Normal file
2
apps/api/src/services/auth.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub mod authentication;
|
||||
pub mod user;
|
||||
289
apps/api/src/services/auth/authentication.rs
Normal file
289
apps/api/src/services/auth/authentication.rs
Normal file
@@ -0,0 +1,289 @@
|
||||
pub mod strategies;
|
||||
|
||||
use std::{collections::HashSet, sync::Arc};
|
||||
|
||||
use argon2::password_hash::{SaltString, rand_core::OsRng};
|
||||
use jsonwebtoken::{
|
||||
DecodingKey, EncodingKey, Header, Validation, decode, encode,
|
||||
errors::ErrorKind::{ExpiredSignature, InvalidSignature, InvalidSubject, InvalidToken},
|
||||
};
|
||||
use sea_orm::prelude::Uuid;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
use crate::errors::service_error::ServiceError;
|
||||
|
||||
// Number of requests between invalidation cache cleanups
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
const INVALIDATE_CACHE_CLEANUP_INTERVAL_REQUESTS: usize = 100; // Cleanup every 100 for invalidation checks
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone)]
|
||||
pub struct Claims {
|
||||
// Subject - user ID
|
||||
pub sub: String,
|
||||
// Issued at as UNIX timestamp
|
||||
pub iat: u64,
|
||||
// Expiration time as UNIX timestamp
|
||||
pub exp: u64,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
pub trait AuthenticationService: Send + Sync {
|
||||
async fn generate_jwt(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
duration_secs: u64,
|
||||
) -> Result<(String, Claims), ServiceError>;
|
||||
async fn is_valid_jwt(
|
||||
&self,
|
||||
token: &str,
|
||||
target_sub: Option<String>,
|
||||
) -> Result<Option<Claims>, ServiceError>;
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
async fn parse_jwt(&self, token: &str) -> Result<Claims, ServiceError>;
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
async fn invalidate_jwt(&self, token: &str) -> Result<(), ServiceError>;
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
async fn refresh_jwt(&self, token: &str, duration_secs: u64) -> Result<String, ServiceError>;
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
async fn logout(&self, token: &str) -> Result<(), ServiceError>;
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
async fn cleanup_invalidation_cache(&self);
|
||||
}
|
||||
|
||||
#[derive(Eq, Hash, PartialEq)]
|
||||
struct InvalidationEntry {
|
||||
token: String,
|
||||
invalidated_at: u64,
|
||||
valid_until: u64,
|
||||
}
|
||||
|
||||
pub struct AuthenticationServiceImpl {
|
||||
secret: String,
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
invalidation_cache: Arc<RwLock<HashSet<InvalidationEntry>>>,
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
cache_cleanup_counter: Arc<RwLock<usize>>,
|
||||
}
|
||||
|
||||
impl AuthenticationServiceImpl {
|
||||
pub fn new(secret: Option<String>) -> Self {
|
||||
let secret = secret.unwrap_or_else(|| {
|
||||
// generate a random secret if none is provided
|
||||
SaltString::generate(&mut OsRng).as_str().to_owned()
|
||||
});
|
||||
|
||||
Self {
|
||||
secret,
|
||||
invalidation_cache: Arc::new(RwLock::new(HashSet::new())),
|
||||
cache_cleanup_counter: Arc::new(RwLock::new(0)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl AuthenticationService for AuthenticationServiceImpl {
|
||||
async fn generate_jwt(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
duration_secs: u64,
|
||||
) -> Result<(String, Claims), ServiceError> {
|
||||
let header = Header::default();
|
||||
let expiration = chrono::Utc::now()
|
||||
.checked_add_signed(chrono::Duration::seconds(duration_secs as i64))
|
||||
.ok_or(ServiceError::InternalError(
|
||||
"Invalid expiration time".into(),
|
||||
))?
|
||||
.timestamp() as u64;
|
||||
let claims = Claims {
|
||||
sub: user_id.to_string(),
|
||||
iat: chrono::Utc::now().timestamp() as u64,
|
||||
exp: expiration,
|
||||
};
|
||||
let token = encode(
|
||||
&header,
|
||||
&claims,
|
||||
&EncodingKey::from_secret(self.secret.as_ref()),
|
||||
)
|
||||
.map_err(|e| ServiceError::InternalError(format!("JWT generation error: {}", e)))?;
|
||||
Ok((token, claims))
|
||||
}
|
||||
|
||||
async fn is_valid_jwt(
|
||||
&self,
|
||||
token: &str,
|
||||
target_sub: Option<String>,
|
||||
) -> Result<Option<Claims>, ServiceError> {
|
||||
let mut validation = Validation::default();
|
||||
// disable leeway for strict expiration checking
|
||||
validation.leeway = 0;
|
||||
if let Some(expected_sub) = target_sub {
|
||||
validation.sub = Some(expected_sub);
|
||||
}
|
||||
let decoding_key = DecodingKey::from_secret(self.secret.as_ref());
|
||||
match decode::<Claims>(token, &decoding_key, &validation) {
|
||||
Ok(data) => Ok(Some(data.claims)),
|
||||
Err(err) => match *err.kind() {
|
||||
InvalidToken | InvalidSubject | ExpiredSignature | InvalidSignature => Ok(None),
|
||||
_ => Err(ServiceError::InternalError(format!(
|
||||
"JWT validation error: {}",
|
||||
err
|
||||
))),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async fn parse_jwt(&self, token: &str) -> Result<Claims, ServiceError> {
|
||||
let decoding_key = DecodingKey::from_secret(self.secret.as_ref());
|
||||
let token_data = decode::<Claims>(token, &decoding_key, &Validation::default())
|
||||
.map_err(|e| ServiceError::InternalError(format!("JWT parsing error: {}", e)))?;
|
||||
Ok(token_data.claims)
|
||||
}
|
||||
|
||||
async fn invalidate_jwt(&self, token: &str) -> Result<(), ServiceError> {
|
||||
let claims = self.parse_jwt(token).await?;
|
||||
let valid_until = claims.exp;
|
||||
let invalidated_at = chrono::Utc::now().timestamp() as u64;
|
||||
let entry = InvalidationEntry {
|
||||
token: token.to_string(),
|
||||
invalidated_at,
|
||||
valid_until,
|
||||
};
|
||||
|
||||
{
|
||||
self.invalidation_cache.write().await.insert(entry);
|
||||
}
|
||||
//
|
||||
if self.cache_cleanup_counter.read().await.wrapping_add(1)
|
||||
% INVALIDATE_CACHE_CLEANUP_INTERVAL_REQUESTS
|
||||
== 0
|
||||
{
|
||||
self.cleanup_invalidation_cache().await;
|
||||
}
|
||||
//
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn refresh_jwt(&self, token: &str, duration_secs: u64) -> Result<String, ServiceError> {
|
||||
let claims = self.parse_jwt(token).await?;
|
||||
let user_id = Uuid::parse_str(&claims.sub).map_err(|e| {
|
||||
ServiceError::InternalError(format!("Invalid user ID in JWT claims: {}", e))
|
||||
})?;
|
||||
let (new_token, _) = self.generate_jwt(user_id, duration_secs).await?;
|
||||
Ok(new_token)
|
||||
}
|
||||
|
||||
async fn logout(&self, token: &str) -> Result<(), ServiceError> {
|
||||
self.invalidate_jwt(token).await
|
||||
}
|
||||
|
||||
async fn cleanup_invalidation_cache(&self) {
|
||||
let now = chrono::Utc::now().timestamp() as u64;
|
||||
let mut cache = self.invalidation_cache.write().await;
|
||||
cache.retain(|entry| entry.valid_until > now);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tokio::time::{Duration, sleep};
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_jwt_generation_and_validation() {
|
||||
let service = AuthenticationServiceImpl::new(Some("secret".to_string()));
|
||||
|
||||
let user_id = Uuid::new_v4();
|
||||
let (token, _) = service
|
||||
.generate_jwt(user_id, 60)
|
||||
.await
|
||||
.expect("generate jwt");
|
||||
|
||||
let valid = service
|
||||
.is_valid_jwt(&token, None)
|
||||
.await
|
||||
.expect("validate jwt");
|
||||
assert!(valid.is_some(), "Generated token should be valid");
|
||||
let claims = service.parse_jwt(&token).await.expect("parse jwt");
|
||||
assert_eq!(claims.sub, user_id.to_string());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_jwt_validation_with_wrong_subject() {
|
||||
let service = AuthenticationServiceImpl::new(Some("secret".to_string()));
|
||||
|
||||
let user_id = Uuid::new_v4();
|
||||
let (token, _) = service.generate_jwt(user_id, 60).await.unwrap();
|
||||
|
||||
let other_sub = Uuid::new_v4().to_string();
|
||||
let valid = service.is_valid_jwt(&token, Some(other_sub)).await.unwrap();
|
||||
assert!(
|
||||
valid.is_none(),
|
||||
"Token should be invalid for a different subject"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_parse_jwt_invalid_token() {
|
||||
let service = AuthenticationServiceImpl::new(Some("secret".to_string()));
|
||||
|
||||
let res = service.parse_jwt("not_a_token").await;
|
||||
assert!(matches!(res, Err(ServiceError::InternalError(_))));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_refresh_jwt() {
|
||||
let service = AuthenticationServiceImpl::new(Some("secret".to_string()));
|
||||
|
||||
let user_id = Uuid::new_v4();
|
||||
let (token, _) = service.generate_jwt(user_id, 60).await.unwrap();
|
||||
let new_token = service.refresh_jwt(&token, 120).await.unwrap();
|
||||
|
||||
let claims = service.parse_jwt(&new_token).await.unwrap();
|
||||
assert_eq!(claims.sub, user_id.to_string());
|
||||
assert_eq!(claims.exp - claims.iat, 120);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_is_valid_jwt_expired() {
|
||||
let service = AuthenticationServiceImpl::new(Some("secret".to_string()));
|
||||
|
||||
let user_id = Uuid::new_v4();
|
||||
let (token, claims) = service.generate_jwt(user_id, 1).await.unwrap();
|
||||
sleep(Duration::from_secs(2)).await;
|
||||
|
||||
let valid = service.is_valid_jwt(&token, None).await.unwrap();
|
||||
assert!(
|
||||
valid.is_none(),
|
||||
"Token should be expired and thus invalid. Current time: {:?}. Diff: {}",
|
||||
chrono::Utc::now(),
|
||||
chrono::Utc::now().timestamp() - claims.exp as i64
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_invalidate_and_cleanup() {
|
||||
let service = AuthenticationServiceImpl::new(Some("secret".to_string()));
|
||||
|
||||
let user_id = Uuid::new_v4();
|
||||
let (token, _) = service.generate_jwt(user_id, 1).await.unwrap();
|
||||
|
||||
service.invalidate_jwt(&token).await.unwrap();
|
||||
|
||||
// ensure entry is present
|
||||
{
|
||||
let cache = service.invalidation_cache.read().await;
|
||||
assert!(cache.iter().any(|e| e.token == token));
|
||||
}
|
||||
|
||||
// wait until token validity ends and cleanup
|
||||
sleep(Duration::from_secs(2)).await;
|
||||
service.cleanup_invalidation_cache().await;
|
||||
|
||||
let cache = service.invalidation_cache.read().await;
|
||||
assert!(
|
||||
cache.is_empty(),
|
||||
"Cleanup should remove expired invalidation entries"
|
||||
);
|
||||
}
|
||||
}
|
||||
1
apps/api/src/services/auth/authentication/strategies.rs
Normal file
1
apps/api/src/services/auth/authentication/strategies.rs
Normal file
@@ -0,0 +1 @@
|
||||
pub mod password;
|
||||
490
apps/api/src/services/auth/authentication/strategies/password.rs
Normal file
490
apps/api/src/services/auth/authentication/strategies/password.rs
Normal file
@@ -0,0 +1,490 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{errors::service_error::ServiceError, with_conn};
|
||||
use argon2::{
|
||||
Argon2,
|
||||
password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString, rand_core::OsRng},
|
||||
};
|
||||
use database::generated::entities::{user, user_identity};
|
||||
use sea_orm::{
|
||||
ColumnTrait, DatabaseConnection, DatabaseTransaction, EntityTrait, IntoActiveModel,
|
||||
QueryFilter, prelude::Uuid,
|
||||
};
|
||||
|
||||
pub struct PasswordStrategy {
|
||||
connection: Arc<DatabaseConnection>,
|
||||
}
|
||||
|
||||
const MAX_PASSWORD_LENGTH: usize = 32;
|
||||
const PASSWORD_PROVIDER: &str = "password";
|
||||
|
||||
impl PasswordStrategy {
|
||||
pub fn new(connection: Arc<DatabaseConnection>) -> Self {
|
||||
Self { connection }
|
||||
}
|
||||
|
||||
pub async fn authenticate(
|
||||
&self,
|
||||
username: &str,
|
||||
password: &str,
|
||||
tx: Option<&mut DatabaseTransaction>,
|
||||
) -> Result<Uuid, ServiceError> {
|
||||
// Find user by username
|
||||
let user = with_conn!(&*self.connection, tx, conn, {
|
||||
user::Entity::find()
|
||||
.filter(user::Column::Name.eq(username))
|
||||
.one(*conn)
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
ServiceError::Unauthorized("Invalid username or password".to_string())
|
||||
})?
|
||||
});
|
||||
// Get user's identity
|
||||
let identity = with_conn!(&*self.connection, tx, conn, {
|
||||
user_identity::Entity::find()
|
||||
.filter(user_identity::Column::UserId.eq(user.id))
|
||||
.one(*conn)
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
ServiceError::Unauthorized("Invalid username or password".to_string())
|
||||
})?
|
||||
});
|
||||
|
||||
// Check if revoked
|
||||
if identity.is_revoked {
|
||||
return Err(ServiceError::Unauthorized("Account is revoked".to_string()));
|
||||
}
|
||||
|
||||
// Verify password
|
||||
let password_hash = identity
|
||||
.password_hash
|
||||
.ok_or_else(|| ServiceError::InternalError("Invalid password hash".to_string()))?;
|
||||
let parsed_hash = PasswordHash::new(&password_hash)
|
||||
.map_err(|_| ServiceError::InternalError("Invalid password hash".to_string()))?;
|
||||
|
||||
Argon2::default()
|
||||
.verify_password(password.as_bytes(), &parsed_hash)
|
||||
.map_err(|_| ServiceError::Unauthorized("Invalid username or password".to_string()))?;
|
||||
|
||||
Ok(user.id)
|
||||
}
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
pub async fn revoke_identity(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
tx: Option<&mut DatabaseTransaction>,
|
||||
) -> Result<(), ServiceError> {
|
||||
let mut identity = with_conn!(&*self.connection, tx, conn, {
|
||||
user_identity::Entity::find()
|
||||
.filter(user_identity::Column::UserId.eq(user_id))
|
||||
.one(*conn)
|
||||
.await?
|
||||
.ok_or_else(|| ServiceError::NotFound("User identity not found".to_string()))?
|
||||
});
|
||||
|
||||
identity.is_revoked = true;
|
||||
|
||||
with_conn!(&*self.connection, tx, conn, {
|
||||
user_identity::Entity::update(identity.into_active_model())
|
||||
.exec(*conn)
|
||||
.await
|
||||
.map_err(ServiceError::from)
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn create_identity(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
password: &str,
|
||||
tx: Option<&mut DatabaseTransaction>,
|
||||
) -> Result<(), ServiceError> {
|
||||
Self::is_valid_password(password).map_err(ServiceError::BadRequest)?;
|
||||
|
||||
// If an identity already exists for this user/provider, treat as success.
|
||||
// This also allows tests using MockDatabase to provide a query result
|
||||
// for an existing identity without requiring an insert exec result.
|
||||
let existing = with_conn!(&*self.connection, tx, conn, {
|
||||
user_identity::Entity::find()
|
||||
.filter(user_identity::Column::UserId.eq(user_id))
|
||||
.filter(user_identity::Column::Provider.eq(PASSWORD_PROVIDER.to_string()))
|
||||
.one(*conn)
|
||||
.await?
|
||||
});
|
||||
|
||||
if existing.is_some() {
|
||||
return Err(ServiceError::BadRequest(
|
||||
"Identity already exists".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let password_hash = Argon2::default()
|
||||
.hash_password(password.as_bytes(), &SaltString::generate(&mut OsRng))
|
||||
.map_err(|_| ServiceError::InternalError("Failed to hash password".to_string()))?
|
||||
.to_string();
|
||||
|
||||
let new_identity = user_identity::ActiveModel {
|
||||
id: sea_orm::ActiveValue::Set(Uuid::new_v4()),
|
||||
user_id: sea_orm::ActiveValue::Set(user_id),
|
||||
provider: sea_orm::ActiveValue::Set(PASSWORD_PROVIDER.to_string()),
|
||||
password_hash: sea_orm::ActiveValue::Set(Some(password_hash)),
|
||||
metadata: sea_orm::ActiveValue::Set(None),
|
||||
is_revoked: sea_orm::ActiveValue::Set(false),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
with_conn!(&*self.connection, tx, conn, {
|
||||
user_identity::Entity::insert(new_identity)
|
||||
.exec(*conn)
|
||||
.await
|
||||
.map_err(ServiceError::from)
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
pub async fn update_password(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
new_password: &str,
|
||||
tx: Option<&mut DatabaseTransaction>,
|
||||
) -> Result<(), ServiceError> {
|
||||
Self::is_valid_password(new_password).map_err(ServiceError::BadRequest)?;
|
||||
|
||||
let password_hash = Argon2::default()
|
||||
.hash_password(new_password.as_bytes(), &SaltString::generate(&mut OsRng))
|
||||
.map_err(|_| ServiceError::InternalError("Failed to hash password".to_string()))?
|
||||
.to_string();
|
||||
|
||||
let mut identity = with_conn!(&*self.connection, tx, conn, {
|
||||
user_identity::Entity::find()
|
||||
.filter(user_identity::Column::UserId.eq(user_id))
|
||||
.one(*conn)
|
||||
.await?
|
||||
.ok_or_else(|| ServiceError::NotFound("User identity not found".to_string()))?
|
||||
});
|
||||
|
||||
identity.password_hash = Some(password_hash);
|
||||
identity.password_changed_at = Some(chrono::Utc::now());
|
||||
|
||||
with_conn!(&*self.connection, tx, conn, {
|
||||
user_identity::Entity::update(identity.into_active_model())
|
||||
.exec(*conn)
|
||||
.await
|
||||
.map_err(ServiceError::from)
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_valid_password(password: &str) -> Result<(), String> {
|
||||
if password.is_empty() {
|
||||
return Err("Password cannot be empty".to_string());
|
||||
}
|
||||
if password.len() > MAX_PASSWORD_LENGTH {
|
||||
return Err(format!(
|
||||
"Password cannot be longer than {} characters",
|
||||
MAX_PASSWORD_LENGTH
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use database::generated::entities::{user, user_identity};
|
||||
use sea_orm::MockDatabase;
|
||||
|
||||
#[test]
|
||||
fn ensure_send_sync() {
|
||||
fn assert_send_sync<T: Send + Sync>() {}
|
||||
assert_send_sync::<PasswordStrategy>();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn password_validation() {
|
||||
let valid_password = "ValidPassword123!";
|
||||
let long_password = "a".repeat(129);
|
||||
|
||||
assert!(PasswordStrategy::is_valid_password(valid_password).is_ok());
|
||||
assert!(PasswordStrategy::is_valid_password(long_password.as_str()).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn authenticate_user_not_found() {
|
||||
let db = MockDatabase::new(sea_orm::DatabaseBackend::Sqlite)
|
||||
.append_query_results(vec![Vec::<sea_orm::MockRow>::new()])
|
||||
.into_connection();
|
||||
|
||||
let strategy = PasswordStrategy::new(Arc::new(db));
|
||||
|
||||
let result = strategy
|
||||
.authenticate("nonexistent_user", "password", None)
|
||||
.await;
|
||||
|
||||
assert!(matches!(result, Err(ServiceError::Unauthorized(_))));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn authenticate_invalid_password() {
|
||||
let user_id = Uuid::new_v4();
|
||||
let password_hash = Argon2::default()
|
||||
.hash_password(
|
||||
"CorrectPassword".as_bytes(),
|
||||
&SaltString::generate(&mut OsRng),
|
||||
)
|
||||
.unwrap()
|
||||
.to_string();
|
||||
let db = MockDatabase::new(sea_orm::DatabaseBackend::Sqlite)
|
||||
.append_query_results(vec![vec![user::Model {
|
||||
id: user_id,
|
||||
name: "test_user".to_string(),
|
||||
is_active: true,
|
||||
is_admin: false,
|
||||
created_at: chrono::Utc::now(),
|
||||
updated_at: chrono::Utc::now(),
|
||||
deleted_at: None,
|
||||
last_login_at: None,
|
||||
}]])
|
||||
.append_query_results(vec![vec![user_identity::Model {
|
||||
id: Uuid::new_v4(),
|
||||
user_id,
|
||||
email: None,
|
||||
provider: PASSWORD_PROVIDER.to_string(),
|
||||
password_hash: Some(password_hash),
|
||||
metadata: None,
|
||||
is_revoked: false,
|
||||
revoked_at: None,
|
||||
created_at: chrono::Utc::now(),
|
||||
updated_at: chrono::Utc::now(),
|
||||
password_changed_at: None,
|
||||
}]])
|
||||
.into_connection();
|
||||
|
||||
let strategy = PasswordStrategy::new(Arc::new(db));
|
||||
|
||||
let result = strategy
|
||||
.authenticate("test_user", "InvalidPassword", None)
|
||||
.await;
|
||||
|
||||
assert!(matches!(result, Err(ServiceError::Unauthorized(_))));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn authenticate_success() {
|
||||
let user_id = Uuid::new_v4();
|
||||
let password_hash = Argon2::default()
|
||||
.hash_password(
|
||||
"CorrectPassword".as_bytes(),
|
||||
&SaltString::generate(&mut OsRng),
|
||||
)
|
||||
.unwrap()
|
||||
.to_string();
|
||||
let db = MockDatabase::new(sea_orm::DatabaseBackend::Sqlite)
|
||||
.append_query_results(vec![vec![user::Model {
|
||||
id: user_id,
|
||||
name: "test_user".to_string(),
|
||||
is_active: true,
|
||||
is_admin: false,
|
||||
created_at: chrono::Utc::now(),
|
||||
updated_at: chrono::Utc::now(),
|
||||
deleted_at: None,
|
||||
last_login_at: None,
|
||||
}]])
|
||||
.append_query_results(vec![vec![user_identity::Model {
|
||||
id: Uuid::new_v4(),
|
||||
user_id,
|
||||
email: None,
|
||||
provider: PASSWORD_PROVIDER.to_string(),
|
||||
password_hash: Some(password_hash),
|
||||
metadata: None,
|
||||
is_revoked: false,
|
||||
revoked_at: None,
|
||||
created_at: chrono::Utc::now(),
|
||||
updated_at: chrono::Utc::now(),
|
||||
password_changed_at: None,
|
||||
}]])
|
||||
.into_connection();
|
||||
|
||||
let strategy = PasswordStrategy::new(Arc::new(db));
|
||||
|
||||
let result = strategy
|
||||
.authenticate("test_user", "CorrectPassword", None)
|
||||
.await;
|
||||
|
||||
assert!(matches!(result, Ok(id) if id == user_id));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn revoke_identity_not_found() {
|
||||
let user_id = Uuid::new_v4();
|
||||
let db = MockDatabase::new(sea_orm::DatabaseBackend::Sqlite)
|
||||
.append_query_results(vec![Vec::<sea_orm::MockRow>::new()])
|
||||
.into_connection();
|
||||
|
||||
let strategy = PasswordStrategy::new(Arc::new(db));
|
||||
|
||||
let result = strategy.revoke_identity(user_id, None).await;
|
||||
|
||||
assert!(matches!(result, Err(ServiceError::NotFound(_))));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn revoke_identity_success() {
|
||||
let user_id = Uuid::new_v4();
|
||||
let identity = user_identity::Model {
|
||||
id: Uuid::new_v4(),
|
||||
user_id,
|
||||
email: None,
|
||||
provider: PASSWORD_PROVIDER.to_string(),
|
||||
password_hash: None,
|
||||
metadata: None,
|
||||
is_revoked: false,
|
||||
revoked_at: None,
|
||||
created_at: chrono::Utc::now(),
|
||||
updated_at: chrono::Utc::now(),
|
||||
password_changed_at: None,
|
||||
};
|
||||
|
||||
let db = MockDatabase::new(sea_orm::DatabaseBackend::Sqlite)
|
||||
.append_query_results(vec![
|
||||
vec![identity.clone()],
|
||||
vec![user_identity::Model {
|
||||
is_revoked: true,
|
||||
..identity
|
||||
}],
|
||||
])
|
||||
.into_connection();
|
||||
|
||||
let strategy = PasswordStrategy::new(Arc::new(db));
|
||||
|
||||
let result = strategy.revoke_identity(user_id, None).await;
|
||||
|
||||
assert!(result.is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_identity_invalid_password() {
|
||||
let db = MockDatabase::new(sea_orm::DatabaseBackend::Sqlite).into_connection();
|
||||
|
||||
let strategy = PasswordStrategy::new(Arc::new(db));
|
||||
|
||||
let result = strategy.create_identity(Uuid::new_v4(), "", None).await;
|
||||
|
||||
assert!(matches!(result, Err(ServiceError::BadRequest(_))));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_identity_success() {
|
||||
let db = MockDatabase::new(sea_orm::DatabaseBackend::Sqlite)
|
||||
// No existing identity
|
||||
.append_query_results(vec![Vec::<sea_orm::MockRow>::new()])
|
||||
// Insert exec result (mock exec result for insert)
|
||||
.append_exec_results(vec![sea_orm::MockExecResult {
|
||||
rows_affected: 1,
|
||||
last_insert_id: 0,
|
||||
}])
|
||||
// Return inserted identity for any subsequent queries
|
||||
.into_connection();
|
||||
|
||||
let strategy = PasswordStrategy::new(Arc::new(db));
|
||||
|
||||
let result = strategy
|
||||
.create_identity(Uuid::new_v4(), "ValidPass1!", None)
|
||||
.await;
|
||||
|
||||
assert!(
|
||||
result.is_ok(),
|
||||
"Failed to create identity, error: {:?}",
|
||||
result.err()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_identity_existing() {
|
||||
let user_id = Uuid::new_v4();
|
||||
let identity = user_identity::Model {
|
||||
id: Uuid::new_v4(),
|
||||
user_id,
|
||||
email: None,
|
||||
provider: PASSWORD_PROVIDER.to_string(),
|
||||
password_hash: Some("hash".to_string()),
|
||||
metadata: None,
|
||||
is_revoked: false,
|
||||
revoked_at: None,
|
||||
created_at: chrono::Utc::now(),
|
||||
updated_at: chrono::Utc::now(),
|
||||
password_changed_at: None,
|
||||
};
|
||||
let db = MockDatabase::new(sea_orm::DatabaseBackend::Sqlite)
|
||||
.append_query_results(vec![vec![identity]])
|
||||
.into_connection();
|
||||
let strategy = PasswordStrategy::new(Arc::new(db));
|
||||
let result = strategy.create_identity(user_id, "ValidPass1!", None).await;
|
||||
assert!(matches!(result, Err(ServiceError::BadRequest(_))));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn update_password_not_found() {
|
||||
let user_id = Uuid::new_v4();
|
||||
let db = MockDatabase::new(sea_orm::DatabaseBackend::Sqlite)
|
||||
.append_query_results(vec![Vec::<sea_orm::MockRow>::new()])
|
||||
.into_connection();
|
||||
|
||||
let strategy = PasswordStrategy::new(Arc::new(db));
|
||||
|
||||
let result = strategy.update_password(user_id, "NewPass1!", None).await;
|
||||
|
||||
assert!(matches!(result, Err(ServiceError::NotFound(_))));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn update_password_success() {
|
||||
let user_id = Uuid::new_v4();
|
||||
let identity = user_identity::Model {
|
||||
id: Uuid::new_v4(),
|
||||
user_id,
|
||||
email: None,
|
||||
provider: PASSWORD_PROVIDER.to_string(),
|
||||
password_hash: Some("old_hash".to_string()),
|
||||
metadata: None,
|
||||
is_revoked: false,
|
||||
revoked_at: None,
|
||||
created_at: chrono::Utc::now(),
|
||||
updated_at: chrono::Utc::now(),
|
||||
password_changed_at: None,
|
||||
};
|
||||
|
||||
let db = MockDatabase::new(sea_orm::DatabaseBackend::Sqlite)
|
||||
.append_query_results(vec![
|
||||
vec![identity],
|
||||
vec![user_identity::Model {
|
||||
id: Uuid::new_v4(),
|
||||
user_id,
|
||||
email: None,
|
||||
provider: PASSWORD_PROVIDER.to_string(),
|
||||
password_hash: Some("new_hash".to_string()),
|
||||
metadata: None,
|
||||
is_revoked: false,
|
||||
revoked_at: None,
|
||||
created_at: chrono::Utc::now(),
|
||||
updated_at: chrono::Utc::now(),
|
||||
password_changed_at: None,
|
||||
}],
|
||||
])
|
||||
.into_connection();
|
||||
|
||||
let strategy = PasswordStrategy::new(Arc::new(db));
|
||||
|
||||
let result = strategy.update_password(user_id, "NewPass1!", None).await;
|
||||
|
||||
assert!(
|
||||
result.is_ok(),
|
||||
"Failed to update password, error: {:?}",
|
||||
result.err()
|
||||
);
|
||||
}
|
||||
}
|
||||
217
apps/api/src/services/auth/user.rs
Normal file
217
apps/api/src/services/auth/user.rs
Normal file
@@ -0,0 +1,217 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use database::generated::entities::user::{
|
||||
self, ActiveModel as UserActiveModel, Model as UserModel,
|
||||
};
|
||||
use sea_orm::{
|
||||
ActiveModelTrait, ActiveValue, ColumnTrait, DatabaseConnection, DatabaseTransaction, DbErr,
|
||||
EntityTrait, IntoActiveModel, QueryFilter, prelude::Uuid,
|
||||
};
|
||||
|
||||
use crate::{errors::service_error::ServiceError, with_conn};
|
||||
|
||||
#[async_trait::async_trait]
|
||||
pub trait UserService: Send + Sync {
|
||||
async fn get_user_by_id(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
tx: Option<&mut DatabaseTransaction>,
|
||||
) -> Result<User, ServiceError>;
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
async fn is_admin(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
tx: Option<&mut DatabaseTransaction>,
|
||||
) -> Result<bool, ServiceError>;
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
async fn user_exists(
|
||||
&self,
|
||||
username: &str,
|
||||
tx: Option<&mut DatabaseTransaction>,
|
||||
) -> Result<bool, ServiceError>;
|
||||
async fn create_user(
|
||||
&self,
|
||||
user: NewUser,
|
||||
tx: Option<&mut DatabaseTransaction>,
|
||||
) -> Result<User, ServiceError>;
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
async fn update_user(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
user: UpdateUser,
|
||||
tx: Option<&mut DatabaseTransaction>,
|
||||
) -> Result<User, ServiceError>;
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
async fn delete_user(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
tx: Option<&mut DatabaseTransaction>,
|
||||
) -> Result<(), ServiceError>;
|
||||
}
|
||||
|
||||
pub struct User {
|
||||
pub id: Uuid,
|
||||
pub username: String,
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
pub is_admin: bool,
|
||||
}
|
||||
|
||||
impl From<UserModel> for User {
|
||||
fn from(model: UserModel) -> Self {
|
||||
Self {
|
||||
id: model.id,
|
||||
username: model.name,
|
||||
is_admin: model.is_admin,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NewUser {
|
||||
pub username: String,
|
||||
pub is_admin: bool,
|
||||
}
|
||||
|
||||
pub struct UpdateUser {
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
pub username: Option<String>,
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
pub is_admin: Option<bool>,
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
pub is_active: Option<bool>,
|
||||
}
|
||||
|
||||
impl UpdateUser {
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
fn apply_to_active_model(&self, model: &mut UserActiveModel) {
|
||||
if let Some(username) = &self.username {
|
||||
model.name = ActiveValue::Set(username.clone());
|
||||
}
|
||||
if let Some(is_admin) = self.is_admin {
|
||||
model.is_admin = ActiveValue::Set(is_admin);
|
||||
}
|
||||
if let Some(is_active) = self.is_active {
|
||||
model.is_active = ActiveValue::Set(is_active);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct UserServiceImpl {
|
||||
connection: Arc<DatabaseConnection>,
|
||||
}
|
||||
|
||||
impl UserServiceImpl {
|
||||
pub fn new(connection: Arc<DatabaseConnection>) -> Self {
|
||||
Self { connection }
|
||||
}
|
||||
|
||||
async fn get_user_by_id_from_db(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
tx: Option<&mut DatabaseTransaction>,
|
||||
) -> Result<UserModel, ServiceError> {
|
||||
let user = with_conn!(&*self.connection, tx, conn, {
|
||||
user::Entity::find_by_id(user_id).one(*conn).await
|
||||
});
|
||||
|
||||
match user {
|
||||
Err(err) => Err(ServiceError::from(err)),
|
||||
Ok(None) => Err(ServiceError::NotFound(format!(
|
||||
"User with id '{}' not found",
|
||||
user_id
|
||||
))),
|
||||
Ok(Some(record)) => Ok(record),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl UserService for UserServiceImpl {
|
||||
async fn get_user_by_id(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
tx: Option<&mut DatabaseTransaction>,
|
||||
) -> Result<User, ServiceError> {
|
||||
let user = self.get_user_by_id_from_db(user_id, tx).await?;
|
||||
Ok(User::from(user))
|
||||
}
|
||||
|
||||
async fn is_admin(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
tx: Option<&mut DatabaseTransaction>,
|
||||
) -> Result<bool, ServiceError> {
|
||||
let user = self.get_user_by_id(user_id, tx).await?;
|
||||
Ok(user.is_admin)
|
||||
}
|
||||
|
||||
async fn user_exists(
|
||||
&self,
|
||||
username: &str,
|
||||
tx: Option<&mut DatabaseTransaction>,
|
||||
) -> Result<bool, ServiceError> {
|
||||
let user = with_conn!(&*self.connection, tx, conn, {
|
||||
user::Entity::find()
|
||||
.filter(user::Column::Name.eq(username))
|
||||
.one(*conn)
|
||||
.await
|
||||
});
|
||||
|
||||
match user {
|
||||
Err(err) => match err {
|
||||
DbErr::RecordNotFound(_) => Ok(false),
|
||||
_ => Err(ServiceError::from(err)),
|
||||
},
|
||||
Ok(None) => Ok(false),
|
||||
Ok(Some(_)) => Ok(true),
|
||||
}
|
||||
}
|
||||
|
||||
async fn create_user(
|
||||
&self,
|
||||
user: NewUser,
|
||||
tx: Option<&mut DatabaseTransaction>,
|
||||
) -> Result<User, ServiceError> {
|
||||
let user_active_model = UserActiveModel {
|
||||
id: ActiveValue::Set(Uuid::new_v4()),
|
||||
name: ActiveValue::Set(user.username),
|
||||
is_admin: ActiveValue::Set(user.is_admin),
|
||||
is_active: ActiveValue::Set(true),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let user_model = with_conn!(&*self.connection, tx, conn, {
|
||||
user_active_model.insert(*conn).await
|
||||
})?;
|
||||
|
||||
Ok(User::from(user_model))
|
||||
}
|
||||
|
||||
async fn update_user(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
update_user: UpdateUser,
|
||||
tx: Option<&mut DatabaseTransaction>,
|
||||
) -> Result<User, ServiceError> {
|
||||
let existing_user = self.get_user_by_id_from_db(user_id, tx).await?;
|
||||
|
||||
let mut user_active_model = existing_user.into_active_model();
|
||||
update_user.apply_to_active_model(&mut user_active_model);
|
||||
|
||||
let user_model = user_active_model.update(&*self.connection).await?;
|
||||
|
||||
Ok(User::from(user_model))
|
||||
}
|
||||
|
||||
async fn delete_user(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
tx: Option<&mut DatabaseTransaction>,
|
||||
) -> Result<(), ServiceError> {
|
||||
let user = self.get_user_by_id_from_db(user_id, tx).await?;
|
||||
|
||||
let user_active_model = user.into_active_model();
|
||||
user_active_model.delete(&*self.connection).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
36
apps/api/src/services/server_state.rs
Normal file
36
apps/api/src/services/server_state.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use sea_orm::{DatabaseConnection, prelude::*};
|
||||
|
||||
use crate::errors::service_error::ServiceError;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
pub trait ServerStateStore: Send + Sync {
|
||||
async fn is_server_initialized(&self) -> Result<bool, ServiceError>;
|
||||
}
|
||||
|
||||
pub struct ServerStateService {
|
||||
connection: Arc<DatabaseConnection>,
|
||||
}
|
||||
|
||||
impl ServerStateService {
|
||||
pub fn new(connection: Arc<DatabaseConnection>) -> Self {
|
||||
Self { connection }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ServerStateStore for ServerStateService {
|
||||
async fn is_server_initialized(&self) -> Result<bool, ServiceError> {
|
||||
// For example, check if any admin user exists to determine if the server is initialized
|
||||
let admin_exists = database::generated::entities::user::Entity::find()
|
||||
.filter(database::generated::entities::user::Column::IsAdmin.eq(true))
|
||||
.filter(database::generated::entities::user::Column::IsActive.eq(true))
|
||||
.one(&*self.connection)
|
||||
.await
|
||||
.map_err(ServiceError::from)?
|
||||
.is_some();
|
||||
|
||||
Ok(admin_exists)
|
||||
}
|
||||
}
|
||||
@@ -7,18 +7,15 @@ use sea_orm::{
|
||||
IntoActiveModel, QueryFilter,
|
||||
};
|
||||
|
||||
use crate::errors::service_error::{IntoServiceError, ServiceError};
|
||||
use crate::errors::service_error::ServiceError;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
pub trait SettingsStore: Send + Sync {
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
async fn get_setting(&self, key: &str) -> Result<String, ServiceError>;
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
async fn set_setting(&self, key: &str, value: String) -> Result<(), ServiceError>;
|
||||
}
|
||||
|
||||
pub struct SettingsService {
|
||||
#[allow(dead_code)] // TODO: remove when used
|
||||
connection: Arc<DatabaseConnection>,
|
||||
}
|
||||
|
||||
@@ -37,11 +34,11 @@ impl SettingsStore for SettingsService {
|
||||
.await;
|
||||
|
||||
match setting {
|
||||
Err(err) => Err(err.into_service_error()),
|
||||
Ok(None) => Err(
|
||||
DbErr::RecordNotFound(format!("Setting with key '{}' not found", key))
|
||||
.into_service_error(),
|
||||
),
|
||||
Err(err) => Err(ServiceError::from(err)),
|
||||
Ok(None) => Err(ServiceError::from(DbErr::RecordNotFound(format!(
|
||||
"Setting with key '{}' not found",
|
||||
key
|
||||
)))),
|
||||
Ok(Some(record)) => Ok(record.value),
|
||||
}
|
||||
}
|
||||
@@ -62,7 +59,7 @@ impl SettingsStore for SettingsService {
|
||||
new_record
|
||||
.insert(&*self.connection)
|
||||
.await
|
||||
.map_err(|err| err.into_service_error())
|
||||
.map_err(ServiceError::from)
|
||||
};
|
||||
|
||||
match existing {
|
||||
@@ -71,19 +68,20 @@ impl SettingsStore for SettingsService {
|
||||
handle_not_found(key.to_string(), value).await?;
|
||||
}
|
||||
_ => {
|
||||
return Err(Box::new(err));
|
||||
return Err(ServiceError::from(err));
|
||||
}
|
||||
},
|
||||
Ok(None) => {
|
||||
handle_not_found(key.to_string(), value).await?;
|
||||
}
|
||||
Ok(Some(mut record)) => {
|
||||
record.value = value;
|
||||
record
|
||||
.into_active_model()
|
||||
Ok(Some(record)) => {
|
||||
let mut record_active_model = record.into_active_model();
|
||||
record_active_model.value = ActiveValue::Set(value);
|
||||
record_active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
|
||||
record_active_model
|
||||
.update(&*self.connection)
|
||||
.await
|
||||
.map_err(|err| err.into_service_error())?;
|
||||
.map_err(ServiceError::from)?;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,25 +1,34 @@
|
||||
use migration::migrate_database;
|
||||
use tracing::{debug, info};
|
||||
mod db_migrate;
|
||||
mod init_admin;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use sea_orm::ConnectOptions;
|
||||
use tracing::info;
|
||||
|
||||
use crate::configs::ProgramSettings;
|
||||
use database::get_connection;
|
||||
|
||||
pub async fn run_startup_tasks(config: &ProgramSettings) -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Here you can add any startup tasks you want to run when the application starts.
|
||||
info!("Running startup tasks...");
|
||||
|
||||
let db_options = |options: &mut ConnectOptions| {
|
||||
options.max_connections(config.database.max_connections);
|
||||
};
|
||||
|
||||
let db_connection = Arc::new(
|
||||
get_connection(&config.database.url, Some(db_options))
|
||||
.await
|
||||
.map_err(|err| format!("Failed to establish database connection: {}", err))?,
|
||||
);
|
||||
|
||||
if config.database.migrate_on_startup {
|
||||
run_database_migrations(&config.database.url).await?;
|
||||
db_migrate::run_database_migrations(&config.database.url).await?;
|
||||
} else {
|
||||
info!("Database migration on startup is disabled. Skipping migration.");
|
||||
}
|
||||
init_admin::init_admin(config, db_connection.clone()).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_database_migrations(db_url: &str) -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Logic to run database migrations
|
||||
info!("Running database migrations...");
|
||||
debug!("Database URL: {}", db_url);
|
||||
migrate_database(db_url).await.map_err(Box::new)?;
|
||||
info!("Database migrations completed.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
11
apps/api/src/tasks/startup/db_migrate.rs
Normal file
11
apps/api/src/tasks/startup/db_migrate.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
use migration::migrate_database;
|
||||
use tracing::{debug, info};
|
||||
|
||||
pub async fn run_database_migrations(db_url: &str) -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Logic to run database migrations
|
||||
info!("Running database migrations...");
|
||||
debug!("Database URL: {}", db_url);
|
||||
migrate_database(db_url).await.map_err(Box::new)?;
|
||||
info!("Database migrations completed.");
|
||||
Ok(())
|
||||
}
|
||||
116
apps/api/src/tasks/startup/init_admin.rs
Normal file
116
apps/api/src/tasks/startup/init_admin.rs
Normal file
@@ -0,0 +1,116 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use argon2::password_hash::{SaltString, rand_core::OsRng};
|
||||
use database::generated::entities::user;
|
||||
use sea_orm::{ColumnTrait, DatabaseConnection, EntityTrait, QueryFilter, TransactionTrait};
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use crate::configs::ProgramSettings;
|
||||
use crate::helpers::constants::ADMIN_INIT_SECRET_KEY;
|
||||
use crate::services::{
|
||||
auth::{
|
||||
authentication::strategies::password::PasswordStrategy,
|
||||
user::{NewUser, UserService, UserServiceImpl},
|
||||
},
|
||||
settings::{SettingsService, SettingsStore},
|
||||
};
|
||||
|
||||
pub async fn init_admin(
|
||||
config: &ProgramSettings,
|
||||
db: Arc<DatabaseConnection>,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
// if admin user already exists, skip
|
||||
let admin_exists = user::Entity::find()
|
||||
.filter(user::Column::IsAdmin.eq(true))
|
||||
.filter(user::Column::IsActive.eq(true))
|
||||
.one(db.as_ref())
|
||||
.await
|
||||
.map_err(|err| format!("Failed to query for existing admin user: {}", err))?
|
||||
.is_some();
|
||||
|
||||
if admin_exists {
|
||||
debug!("Admin user already exists. Skipping admin initialization.");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// if config contains admin init settings, run admin init
|
||||
if let (Some(username), Some(password)) = (
|
||||
&config.auth.default_admin_username,
|
||||
&config.auth.default_admin_password,
|
||||
) {
|
||||
let r = _init_admin(username, password, db.clone()).await;
|
||||
if let Err(e) = r {
|
||||
warn!("Failed to initialize admin user: {}", e);
|
||||
info!("Defaulting to manual creation from dashboard.");
|
||||
} else {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
// else generate a random secret to be used when initializing admin from dashboard
|
||||
let secret = generate_admin_init_secret(db.clone()).await?;
|
||||
info!(
|
||||
"Admin initialization secret generated. Use this secret to initialize the admin user from the dashboard: {}. This secret will only be shown once and is only valid until the admin user is created or the application is restarted.",
|
||||
secret
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn generate_admin_init_secret(
|
||||
db: Arc<DatabaseConnection>,
|
||||
) -> Result<String, Box<dyn std::error::Error>> {
|
||||
let secret = SaltString::generate(&mut OsRng).as_str().to_owned();
|
||||
|
||||
// Store the secret in a settings table
|
||||
let setting = SettingsService::new(db.clone());
|
||||
setting
|
||||
.set_setting(ADMIN_INIT_SECRET_KEY, secret.clone())
|
||||
.await
|
||||
.map_err(|err| format!("Failed to store admin init secret: {}", err))?;
|
||||
|
||||
Ok(secret)
|
||||
}
|
||||
|
||||
async fn _init_admin(
|
||||
username: &str,
|
||||
password: &str,
|
||||
db: Arc<DatabaseConnection>,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
info!("Initializing admin user...");
|
||||
// Check if an admin user already exists
|
||||
let admin_exists = user::Entity::find()
|
||||
.filter(user::Column::IsAdmin.eq(true))
|
||||
.one(db.as_ref())
|
||||
.await?
|
||||
.is_some();
|
||||
|
||||
if admin_exists {
|
||||
debug!("Admin user already exists. Skipping initialization.");
|
||||
return Ok(());
|
||||
}
|
||||
info!("No admin user found. Creating default admin user...");
|
||||
|
||||
let user_service = UserServiceImpl::new(db.clone());
|
||||
let password_strategy = PasswordStrategy::new(db.clone());
|
||||
|
||||
let user = NewUser {
|
||||
username: username.to_string(),
|
||||
is_admin: true,
|
||||
};
|
||||
|
||||
let mut tx = db.begin().await?;
|
||||
// create user
|
||||
let user = user_service.create_user(user, Some(&mut tx)).await?;
|
||||
// create temporary password
|
||||
password_strategy
|
||||
.create_identity(user.id, password, Some(&mut tx))
|
||||
.await?;
|
||||
//
|
||||
tx.commit().await?;
|
||||
|
||||
info!(
|
||||
"Default admin user created successfully, username: {}",
|
||||
username
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
250
apps/api/swagger.json
Normal file
250
apps/api/swagger.json
Normal file
@@ -0,0 +1,250 @@
|
||||
{
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "yet-another-nginx-proxy-manager",
|
||||
"description": "",
|
||||
"license": {
|
||||
"name": ""
|
||||
},
|
||||
"version": "0.1.0"
|
||||
},
|
||||
"paths": {
|
||||
"/api/auth/init_admin": {
|
||||
"post": {
|
||||
"tags": [
|
||||
"Authentication"
|
||||
],
|
||||
"summary": "Initializes the admin user",
|
||||
"description": "Initializes the admin user if no admin user exists and the correct setup secret is provided.",
|
||||
"operationId": "init_admin",
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/AdminInitRequest"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Admin user initialized successfully"
|
||||
},
|
||||
"400": {
|
||||
"description": "Invalid request payload"
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized: Admin user already exists or invalid setup secret"
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal server error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/auth/login": {
|
||||
"post": {
|
||||
"tags": [
|
||||
"Authentication"
|
||||
],
|
||||
"summary": "Login endpoint",
|
||||
"description": "Authenticates a user and returns a JWT in an HttpOnly cookie.",
|
||||
"operationId": "login",
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/LoginRequest"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "User authenticated successfully",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"default": null
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Authentication failed"
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal server error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/health/info": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Health"
|
||||
],
|
||||
"summary": "Health check endpoint",
|
||||
"description": "Returns the health status, version, uptime, and any errors if unhealthy.",
|
||||
"operationId": "get_health_info",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Health information retrieved successfully",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HealthInfo"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Health information not found"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/user/me": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"User"
|
||||
],
|
||||
"summary": "Get current user information",
|
||||
"description": "Returns the information of the currently authenticated user.",
|
||||
"operationId": "get_user_info",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "User information retrieved successfully",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/UserInfo"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized"
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal server error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
"schemas": {
|
||||
"AdminInitRequest": {
|
||||
"type": "object",
|
||||
"description": "Login request payload",
|
||||
"required": [
|
||||
"username",
|
||||
"password",
|
||||
"setup_secret"
|
||||
],
|
||||
"properties": {
|
||||
"password": {
|
||||
"type": "string"
|
||||
},
|
||||
"setup_secret": {
|
||||
"type": "string"
|
||||
},
|
||||
"username": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"HealthInfo": {
|
||||
"type": "object",
|
||||
"description": "System health information",
|
||||
"required": [
|
||||
"status",
|
||||
"version",
|
||||
"up_since",
|
||||
"is_initialized"
|
||||
],
|
||||
"properties": {
|
||||
"errors": {
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "List of error messages if unhealthy"
|
||||
},
|
||||
"is_initialized": {
|
||||
"type": "boolean",
|
||||
"description": "Is initialized"
|
||||
},
|
||||
"status": {
|
||||
"type": "string",
|
||||
"description": "Health status: \"healthy\" or \"unhealthy\""
|
||||
},
|
||||
"up_since": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"description": "RFC 3339 formatted timestamp"
|
||||
},
|
||||
"version": {
|
||||
"type": "string",
|
||||
"description": "Application version"
|
||||
}
|
||||
}
|
||||
},
|
||||
"LoginRequest": {
|
||||
"type": "object",
|
||||
"description": "Login request payload",
|
||||
"required": [
|
||||
"username",
|
||||
"password"
|
||||
],
|
||||
"properties": {
|
||||
"password": {
|
||||
"type": "string"
|
||||
},
|
||||
"username": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"UserInfo": {
|
||||
"type": "object",
|
||||
"description": "System health information",
|
||||
"required": [
|
||||
"id",
|
||||
"username"
|
||||
],
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"format": "uuid",
|
||||
"description": "User ID"
|
||||
},
|
||||
"username": {
|
||||
"type": "string",
|
||||
"description": "Username"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
{
|
||||
"name": "Health",
|
||||
"description": "Health information API"
|
||||
},
|
||||
{
|
||||
"name": "Authentication",
|
||||
"description": "Authentication API"
|
||||
},
|
||||
{
|
||||
"name": "User",
|
||||
"description": "User management API"
|
||||
}
|
||||
]
|
||||
}
|
||||
4
apps/frontend/.dockerignore
Normal file
4
apps/frontend/.dockerignore
Normal file
@@ -0,0 +1,4 @@
|
||||
.react-router
|
||||
build
|
||||
node_modules
|
||||
README.md
|
||||
1
apps/frontend/.env.example
Normal file
1
apps/frontend/.env.example
Normal file
@@ -0,0 +1 @@
|
||||
VITE_API_BASE_URL=<optional_api_base_url>
|
||||
7
apps/frontend/.gitignore
vendored
Normal file
7
apps/frontend/.gitignore
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
.DS_Store
|
||||
.env
|
||||
/node_modules/
|
||||
|
||||
# React Router
|
||||
/.react-router/
|
||||
/build/
|
||||
9
apps/frontend/app/app.css
Normal file
9
apps/frontend/app/app.css
Normal file
@@ -0,0 +1,9 @@
|
||||
@import 'tailwindcss';
|
||||
|
||||
@theme {
|
||||
--font-sans: 'Inter', ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
}
|
||||
46
apps/frontend/app/components/Form/Button.tsx
Normal file
46
apps/frontend/app/components/Form/Button.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
import { Button, type ButtonProps } from '@radix-ui/themes';
|
||||
import { LoaderCircle } from 'lucide-react';
|
||||
|
||||
export type SubmitButtonProps = {
|
||||
loading?: boolean;
|
||||
label?:
|
||||
| {
|
||||
default?: string;
|
||||
loading?: string;
|
||||
}
|
||||
| string;
|
||||
} & React.ButtonHTMLAttributes<HTMLButtonElement> &
|
||||
ButtonProps;
|
||||
|
||||
export function SubmitButton({ loading, label, ...props }: SubmitButtonProps) {
|
||||
return (
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
style={{
|
||||
padding: '10px 14px',
|
||||
borderRadius: 6,
|
||||
border: 'none',
|
||||
backgroundColor: 'var(--iris-9)',
|
||||
}}
|
||||
size="3"
|
||||
{...props}
|
||||
>
|
||||
{loading
|
||||
? typeof label === 'string'
|
||||
? label
|
||||
: label?.loading ?? <LoaderCircle className="animate-spin" style={{ width: 24, height: 24, marginRight: 4, verticalAlign: 'middle', color: 'white' }} />
|
||||
: typeof label === 'string'
|
||||
? label
|
||||
: label?.default ?? 'Submit'}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
export function ResetButton(props: React.ButtonHTMLAttributes<HTMLButtonElement>) {
|
||||
return (
|
||||
<button type="reset" {...props} style={{ padding: '10px 14px', borderRadius: 6, border: '1px solid var(--gray-5)', background: 'white', ...props.style }}>
|
||||
{props.children ?? 'Reset'}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
103
apps/frontend/app/components/Form/TextField.tsx
Normal file
103
apps/frontend/app/components/Form/TextField.tsx
Normal file
@@ -0,0 +1,103 @@
|
||||
import type { AnyFieldMeta } from '@tanstack/react-form';
|
||||
import { LucideEye, LucideEyeClosed } from 'lucide-react';
|
||||
import { useCallback, useId, useState } from 'react';
|
||||
import { InfoIcon, type InfoIconProps } from '../info';
|
||||
import { Text } from '@radix-ui/themes';
|
||||
|
||||
export type TextFieldProps = {
|
||||
label?: string;
|
||||
value?: string;
|
||||
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
|
||||
labelProps?: React.LabelHTMLAttributes<HTMLLabelElement>;
|
||||
labelDivProps?: React.HTMLAttributes<HTMLDivElement>;
|
||||
infoIconProps?: InfoIconProps;
|
||||
} & React.InputHTMLAttributes<HTMLInputElement> & {
|
||||
type?: 'password';
|
||||
showPasswordToggle?: boolean;
|
||||
};
|
||||
|
||||
export function TextField({ label, value, onChange, labelProps, labelDivProps, showPasswordToggle, infoIconProps, ...rest }: TextFieldProps) {
|
||||
const id = useId();
|
||||
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
|
||||
const handlePasswordVisibilitySet = useCallback(
|
||||
(e: React.MouseEvent | React.TouchEvent, visible: boolean) => {
|
||||
if (rest.type !== 'password') return;
|
||||
e.preventDefault();
|
||||
setIsPasswordVisible(() => visible);
|
||||
},
|
||||
[rest.type]
|
||||
);
|
||||
|
||||
return (
|
||||
<label htmlFor={id} style={{ display: 'block', marginBottom: 8 }} {...labelProps}>
|
||||
{label && (
|
||||
<div style={{ fontSize: 12, color: 'var(--gray-9)', marginBottom: 6, display: 'flex', alignItems: 'center' }} {...labelDivProps}>
|
||||
{label}
|
||||
{rest?.required && (
|
||||
<Text size="3" style={{ color: 'var(--red-9)', marginLeft: 2 }}>
|
||||
*
|
||||
</Text>
|
||||
)}
|
||||
{infoIconProps && <InfoIcon {...infoIconProps} style={{ marginLeft: 4, verticalAlign: 'middle' }} />}
|
||||
</div>
|
||||
)}
|
||||
<div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<input
|
||||
{...rest}
|
||||
type={rest.type === 'password' ? (isPasswordVisible && showPasswordToggle ? 'text' : 'password') : rest.type}
|
||||
id={id}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '10px 12px',
|
||||
borderRadius: 6,
|
||||
border: '1px solid var(--gray-5)',
|
||||
...rest?.style,
|
||||
}}
|
||||
/>
|
||||
|
||||
<div
|
||||
style={{ position: 'absolute', right: 12 }}
|
||||
onMouseDown={(e) => {
|
||||
handlePasswordVisibilitySet(e, true);
|
||||
}}
|
||||
onMouseUp={(e) => {
|
||||
handlePasswordVisibilitySet(e, false);
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
handlePasswordVisibilitySet(e, false);
|
||||
}}
|
||||
onTouchStart={(e) => {
|
||||
handlePasswordVisibilitySet(e, true);
|
||||
}}
|
||||
onTouchEnd={(e) => {
|
||||
handlePasswordVisibilitySet(e, false);
|
||||
}}
|
||||
>
|
||||
{showPasswordToggle ? isPasswordVisible ? <LucideEye size={16} /> : <LucideEyeClosed size={16} /> : null}
|
||||
</div>
|
||||
</div>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
export type TextFieldErrorMessageProps = AnyFieldMeta & {
|
||||
errorMessage?: string;
|
||||
};
|
||||
|
||||
export function TextFieldErrorMessage({ isValid, errors, errorMessage }: TextFieldErrorMessageProps) {
|
||||
return (
|
||||
!isValid && (
|
||||
<div
|
||||
style={{
|
||||
marginTop: 4,
|
||||
fontSize: 12,
|
||||
color: 'var(--red-9)',
|
||||
}}
|
||||
>
|
||||
{errorMessage ?? errors?.reduce((msg, err) => msg + err.message + ' ', '')}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
27
apps/frontend/app/components/home/TablePlaceholder.tsx
Normal file
27
apps/frontend/app/components/home/TablePlaceholder.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
import React from 'react';
|
||||
import { Flex, Text, Button, Separator, Box, Badge } from '@radix-ui/themes';
|
||||
|
||||
export default function TablePlaceholder() {
|
||||
return (
|
||||
<Flex direction="column" gap="3" p="4">
|
||||
<Flex justify="between" align="center">
|
||||
<Text weight="bold">Proxy Hosts</Text>
|
||||
<Button size="1">Add Host</Button>
|
||||
</Flex>
|
||||
<Separator size="4" />
|
||||
{[1, 2, 3].map((i) => (
|
||||
<Flex key={i} justify="between" align="center">
|
||||
<Box>
|
||||
<Text size="2" weight="bold" as="div">
|
||||
{`host-${i}.example.com`}
|
||||
</Text>
|
||||
<Text size="1" color="gray">
|
||||
{`http://10.0.0.${i}:8080`}
|
||||
</Text>
|
||||
</Box>
|
||||
<Badge color="green">Online</Badge>
|
||||
</Flex>
|
||||
))}
|
||||
</Flex>
|
||||
);
|
||||
}
|
||||
59
apps/frontend/app/components/info.tsx
Normal file
59
apps/frontend/app/components/info.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
import { Box } from '@radix-ui/themes';
|
||||
import { Info, type LucideProps } from 'lucide-react';
|
||||
import { Tooltip } from 'radix-ui';
|
||||
import type { PropsWithChildren } from 'react';
|
||||
|
||||
export type InfoIconProps = PropsWithChildren<
|
||||
{
|
||||
tooltipContainerProps?: Omit<Tooltip.TooltipContentProps & React.RefAttributes<HTMLDivElement>, 'children'>;
|
||||
} & Omit<LucideProps, 'ref'> &
|
||||
React.RefAttributes<SVGSVGElement>
|
||||
>;
|
||||
|
||||
export function InfoIcon({ tooltipContainerProps, children, ...iconProps }: InfoIconProps) {
|
||||
return (
|
||||
<Tooltip.Root>
|
||||
<Tooltip.Trigger asChild>
|
||||
<Info size={16} {...iconProps} />
|
||||
</Tooltip.Trigger>
|
||||
<Tooltip.Portal>
|
||||
<Tooltip.Content
|
||||
//
|
||||
side="top"
|
||||
align="center"
|
||||
sideOffset={5}
|
||||
alignOffset={0}
|
||||
avoidCollisions={true}
|
||||
style={{
|
||||
color: 'black',
|
||||
backgroundColor: 'white',
|
||||
fontSize: 12,
|
||||
boxShadow: '0 2px 10px rgba(0, 0, 0, 0.3)',
|
||||
border: '1px solid var(--gray-5)',
|
||||
}}
|
||||
{...tooltipContainerProps}
|
||||
>
|
||||
{children}
|
||||
<Tooltip.Arrow className="TooltipArrow" fill="white" />
|
||||
</Tooltip.Content>
|
||||
</Tooltip.Portal>
|
||||
</Tooltip.Root>
|
||||
);
|
||||
}
|
||||
|
||||
export function TooltipContentContainer({ children, ...props }: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return (
|
||||
<Box
|
||||
style={{
|
||||
padding: '8px 12px',
|
||||
color: 'black',
|
||||
backgroundColor: 'white',
|
||||
borderRadius: 4,
|
||||
fontSize: 12,
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
89
apps/frontend/app/components/layout/SidebarContent.tsx
Normal file
89
apps/frontend/app/components/layout/SidebarContent.tsx
Normal file
@@ -0,0 +1,89 @@
|
||||
import type React from 'react';
|
||||
import { Box, Button, Flex, Heading, Separator, Text } from '@radix-ui/themes';
|
||||
import type { NavItem } from './types';
|
||||
import { Home, Globe, ArrowRight, Lock, Settings, User } from 'lucide-react';
|
||||
import { useLayout } from '../../providers/LayoutProvider';
|
||||
|
||||
const navItems: { label: NavItem; icon: React.ReactNode }[] = [
|
||||
{ label: 'Dashboard', icon: <Home size={16} /> },
|
||||
{ label: 'Proxy Hosts', icon: <Globe size={16} /> },
|
||||
{ label: 'Redirection', icon: <ArrowRight size={16} /> },
|
||||
{ label: 'SSL', icon: <Lock size={16} /> },
|
||||
{ label: 'Settings', icon: <Settings size={16} /> },
|
||||
{ label: 'Profile', icon: <User size={16} /> },
|
||||
] as const;
|
||||
|
||||
export function SidebarContent() {
|
||||
const { activeTab, setActiveTab, setIsMobileMenuOpen } = useLayout();
|
||||
|
||||
return (
|
||||
<Flex direction="column" gap="2" p="4" style={{ height: '100%' }}>
|
||||
<Flex align="center" gap="2" mb="6" px="2">
|
||||
<Box
|
||||
style={{
|
||||
width: 32,
|
||||
height: 32,
|
||||
backgroundColor: 'var(--iris-9)',
|
||||
borderRadius: 'var(--radius-2)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
color: 'white',
|
||||
fontWeight: 'bold',
|
||||
}}
|
||||
>
|
||||
Y
|
||||
</Box>
|
||||
<Heading size="4" weight="bold">
|
||||
YANPM
|
||||
</Heading>
|
||||
</Flex>
|
||||
|
||||
<Flex direction="column" gap="1">
|
||||
{navItems.map((item) => (
|
||||
<Button
|
||||
key={item.label}
|
||||
variant={activeTab === item.label ? 'soft' : 'ghost'}
|
||||
color={activeTab === item.label ? 'iris' : 'gray'}
|
||||
onClick={() => {
|
||||
setActiveTab(item.label);
|
||||
setIsMobileMenuOpen(false);
|
||||
}}
|
||||
style={{ cursor: 'pointer', width: '100%', justifyContent: 'flex-start' }}
|
||||
>
|
||||
<Flex align="center" gap="3">
|
||||
{item.icon}
|
||||
<Text size="2" weight={activeTab === item.label ? 'bold' : 'medium'}>
|
||||
{item.label}
|
||||
</Text>
|
||||
</Flex>
|
||||
</Button>
|
||||
))}
|
||||
</Flex>
|
||||
|
||||
<Box style={{ marginTop: 'auto' }} pt="4">
|
||||
<Separator size="4" mb="4" />
|
||||
<Flex align="center" gap="3" px="2">
|
||||
<Box
|
||||
style={{
|
||||
width: 32,
|
||||
height: 32,
|
||||
backgroundColor: 'var(--gray-5)',
|
||||
borderRadius: '50%',
|
||||
}}
|
||||
/>
|
||||
<Box>
|
||||
<Text size="1" weight="bold" as="div">
|
||||
Admin User
|
||||
</Text>
|
||||
<Text size="1" color="gray">
|
||||
admin@example.com
|
||||
</Text>
|
||||
</Box>
|
||||
</Flex>
|
||||
</Box>
|
||||
</Flex>
|
||||
);
|
||||
}
|
||||
|
||||
export default SidebarContent;
|
||||
1
apps/frontend/app/components/layout/types.ts
Normal file
1
apps/frontend/app/components/layout/types.ts
Normal file
@@ -0,0 +1 @@
|
||||
export type NavItem = 'Dashboard' | 'Proxy Hosts' | 'Redirection' | 'SSL' | 'Settings' | 'Profile';
|
||||
16
apps/frontend/app/components/theme.tsx
Normal file
16
apps/frontend/app/components/theme.tsx
Normal file
@@ -0,0 +1,16 @@
|
||||
import type React from 'react';
|
||||
import { Theme } from '@radix-ui/themes';
|
||||
|
||||
export type AppThemeProps = {
|
||||
children: React.ReactNode;
|
||||
};
|
||||
|
||||
export function AppTheme({ children }: AppThemeProps) {
|
||||
return (
|
||||
<Theme accentColor="iris" grayColor="slate" panelBackground="translucent" radius="large">
|
||||
{children}
|
||||
</Theme>
|
||||
);
|
||||
}
|
||||
|
||||
export default AppTheme;
|
||||
1
apps/frontend/app/empty-toastify.css
Normal file
1
apps/frontend/app/empty-toastify.css
Normal file
@@ -0,0 +1 @@
|
||||
/* intentionally empty: used to stub react-toastify CSS in production builds */
|
||||
488
apps/frontend/app/generated/api-client/api-client.ts
Normal file
488
apps/frontend/app/generated/api-client/api-client.ts
Normal file
@@ -0,0 +1,488 @@
|
||||
export namespace Schemas {
|
||||
// <Schemas>
|
||||
export type AdminInitRequest = { password: string; setup_secret: string; username: string };
|
||||
export type HealthInfo = {
|
||||
errors?: (Array<string> | null) | undefined;
|
||||
is_initialized: boolean;
|
||||
status: string;
|
||||
up_since: string;
|
||||
version: string;
|
||||
};
|
||||
export type LoginRequest = { password: string; username: string };
|
||||
export type UserInfo = { id: string; username: string };
|
||||
|
||||
// </Schemas>
|
||||
}
|
||||
|
||||
export namespace Endpoints {
|
||||
// <Endpoints>
|
||||
|
||||
export type post_Init_admin = {
|
||||
method: "POST";
|
||||
path: "/api/auth/init_admin";
|
||||
requestFormat: "json";
|
||||
parameters: {
|
||||
body: Schemas.AdminInitRequest;
|
||||
};
|
||||
responses: { 200: unknown; 400: unknown; 401: unknown; 500: unknown };
|
||||
};
|
||||
export type post_Login = {
|
||||
method: "POST";
|
||||
path: "/api/auth/login";
|
||||
requestFormat: "json";
|
||||
parameters: {
|
||||
body: Schemas.LoginRequest;
|
||||
};
|
||||
responses: { 200: unknown; 401: unknown; 500: unknown };
|
||||
};
|
||||
export type get_Get_health_info = {
|
||||
method: "GET";
|
||||
path: "/api/health/info";
|
||||
requestFormat: "json";
|
||||
parameters: never;
|
||||
responses: { 200: Schemas.HealthInfo; 404: unknown };
|
||||
};
|
||||
export type get_Get_user_info = {
|
||||
method: "GET";
|
||||
path: "/api/user/me";
|
||||
requestFormat: "json";
|
||||
parameters: never;
|
||||
responses: { 200: Schemas.UserInfo; 401: unknown; 500: unknown };
|
||||
};
|
||||
|
||||
// </Endpoints>
|
||||
}
|
||||
|
||||
// <EndpointByMethod>
|
||||
export type EndpointByMethod = {
|
||||
post: {
|
||||
"/api/auth/init_admin": Endpoints.post_Init_admin;
|
||||
"/api/auth/login": Endpoints.post_Login;
|
||||
};
|
||||
get: {
|
||||
"/api/health/info": Endpoints.get_Get_health_info;
|
||||
"/api/user/me": Endpoints.get_Get_user_info;
|
||||
};
|
||||
};
|
||||
|
||||
// </EndpointByMethod>
|
||||
|
||||
// <EndpointByMethod.Shorthands>
|
||||
export type PostEndpoints = EndpointByMethod["post"];
|
||||
export type GetEndpoints = EndpointByMethod["get"];
|
||||
// </EndpointByMethod.Shorthands>
|
||||
|
||||
// <ApiClientTypes>
|
||||
export type EndpointParameters = {
|
||||
body?: unknown;
|
||||
query?: Record<string, unknown>;
|
||||
header?: Record<string, unknown>;
|
||||
path?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export type MutationMethod = "post" | "put" | "patch" | "delete";
|
||||
export type Method = "get" | "head" | "options" | MutationMethod;
|
||||
|
||||
type RequestFormat = "json" | "form-data" | "form-url" | "binary" | "text";
|
||||
|
||||
export type DefaultEndpoint = {
|
||||
parameters?: EndpointParameters | undefined;
|
||||
responses?: Record<string, unknown>;
|
||||
responseHeaders?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export type Endpoint<TConfig extends DefaultEndpoint = DefaultEndpoint> = {
|
||||
operationId: string;
|
||||
method: Method;
|
||||
path: string;
|
||||
requestFormat: RequestFormat;
|
||||
parameters?: TConfig["parameters"];
|
||||
meta: {
|
||||
alias: string;
|
||||
hasParameters: boolean;
|
||||
areParametersRequired: boolean;
|
||||
};
|
||||
responses?: TConfig["responses"];
|
||||
responseHeaders?: TConfig["responseHeaders"];
|
||||
};
|
||||
|
||||
export interface Fetcher {
|
||||
decodePathParams?: (path: string, pathParams: Record<string, string>) => string;
|
||||
encodeSearchParams?: (searchParams: Record<string, unknown> | undefined) => URLSearchParams;
|
||||
//
|
||||
fetch: (input: {
|
||||
method: Method;
|
||||
url: URL;
|
||||
urlSearchParams?: URLSearchParams | undefined;
|
||||
parameters?: EndpointParameters | undefined;
|
||||
path: string;
|
||||
overrides?: RequestInit;
|
||||
throwOnStatusError?: boolean;
|
||||
}) => Promise<Response>;
|
||||
parseResponseData?: (response: Response) => Promise<unknown>;
|
||||
}
|
||||
|
||||
export const successStatusCodes = [
|
||||
200, 201, 202, 203, 204, 205, 206, 207, 208, 226, 300, 301, 302, 303, 304, 305, 306, 307, 308,
|
||||
] as const;
|
||||
export type SuccessStatusCode = (typeof successStatusCodes)[number];
|
||||
|
||||
export const errorStatusCodes = [
|
||||
400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 421, 422, 423, 424,
|
||||
425, 426, 428, 429, 431, 451, 500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511,
|
||||
] as const;
|
||||
export type ErrorStatusCode = (typeof errorStatusCodes)[number];
|
||||
|
||||
// Taken from https://github.com/unjs/fetchdts/blob/ec4eaeab5d287116171fc1efd61f4a1ad34e4609/src/fetch.ts#L3
|
||||
export interface TypedHeaders<TypedHeaderValues extends Record<string, string> | unknown>
|
||||
extends Omit<Headers, "append" | "delete" | "get" | "getSetCookie" | "has" | "set" | "forEach"> {
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) */
|
||||
append: <Name extends Extract<keyof TypedHeaderValues, string> | (string & {})>(
|
||||
name: Name,
|
||||
value: Lowercase<Name> extends keyof TypedHeaderValues ? TypedHeaderValues[Lowercase<Name>] : string,
|
||||
) => void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) */
|
||||
delete: <Name extends Extract<keyof TypedHeaderValues, string> | (string & {})>(name: Name) => void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) */
|
||||
get: <Name extends Extract<keyof TypedHeaderValues, string> | (string & {})>(
|
||||
name: Name,
|
||||
) => (Lowercase<Name> extends keyof TypedHeaderValues ? TypedHeaderValues[Lowercase<Name>] : string) | null;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) */
|
||||
getSetCookie: () => string[];
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) */
|
||||
has: <Name extends Extract<keyof TypedHeaderValues, string> | (string & {})>(name: Name) => boolean;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) */
|
||||
set: <Name extends Extract<keyof TypedHeaderValues, string> | (string & {})>(
|
||||
name: Name,
|
||||
value: Lowercase<Name> extends keyof TypedHeaderValues ? TypedHeaderValues[Lowercase<Name>] : string,
|
||||
) => void;
|
||||
forEach: (
|
||||
callbackfn: (
|
||||
value: TypedHeaderValues[keyof TypedHeaderValues] | (string & {}),
|
||||
key: Extract<keyof TypedHeaderValues, string> | (string & {}),
|
||||
parent: TypedHeaders<TypedHeaderValues>,
|
||||
) => void,
|
||||
thisArg?: any,
|
||||
) => void;
|
||||
}
|
||||
|
||||
/** @see https://developer.mozilla.org/en-US/docs/Web/API/Response */
|
||||
export interface TypedSuccessResponse<TSuccess, TStatusCode, THeaders>
|
||||
extends Omit<Response, "ok" | "status" | "json" | "headers"> {
|
||||
ok: true;
|
||||
status: TStatusCode;
|
||||
headers: never extends THeaders ? Headers : TypedHeaders<THeaders>;
|
||||
data: TSuccess;
|
||||
/** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Response/json) */
|
||||
json: () => Promise<TSuccess>;
|
||||
}
|
||||
|
||||
/** @see https://developer.mozilla.org/en-US/docs/Web/API/Response */
|
||||
export interface TypedErrorResponse<TData, TStatusCode, THeaders>
|
||||
extends Omit<Response, "ok" | "status" | "json" | "headers"> {
|
||||
ok: false;
|
||||
status: TStatusCode;
|
||||
headers: never extends THeaders ? Headers : TypedHeaders<THeaders>;
|
||||
data: TData;
|
||||
/** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Response/json) */
|
||||
json: () => Promise<TData>;
|
||||
}
|
||||
|
||||
export type TypedApiResponse<TAllResponses extends Record<string | number, unknown> = {}, THeaders = {}> = {
|
||||
[K in keyof TAllResponses]: K extends string
|
||||
? K extends `${infer TStatusCode extends number}`
|
||||
? TStatusCode extends SuccessStatusCode
|
||||
? TypedSuccessResponse<TAllResponses[K], TStatusCode, K extends keyof THeaders ? THeaders[K] : never>
|
||||
: TypedErrorResponse<TAllResponses[K], TStatusCode, K extends keyof THeaders ? THeaders[K] : never>
|
||||
: never
|
||||
: K extends number
|
||||
? K extends SuccessStatusCode
|
||||
? TypedSuccessResponse<TAllResponses[K], K, K extends keyof THeaders ? THeaders[K] : never>
|
||||
: TypedErrorResponse<TAllResponses[K], K, K extends keyof THeaders ? THeaders[K] : never>
|
||||
: never;
|
||||
}[keyof TAllResponses];
|
||||
|
||||
export type SafeApiResponse<TEndpoint> = TEndpoint extends { responses: infer TResponses }
|
||||
? TResponses extends Record<string, unknown>
|
||||
? TypedApiResponse<TResponses, TEndpoint extends { responseHeaders: infer THeaders } ? THeaders : never>
|
||||
: never
|
||||
: never;
|
||||
|
||||
export type InferResponseByStatus<TEndpoint, TStatusCode> = Extract<
|
||||
SafeApiResponse<TEndpoint>,
|
||||
{ status: TStatusCode }
|
||||
>;
|
||||
|
||||
type RequiredKeys<T> = {
|
||||
[P in keyof T]-?: undefined extends T[P] ? never : P;
|
||||
}[keyof T];
|
||||
|
||||
type MaybeOptionalArg<T> = RequiredKeys<T> extends never ? [config?: T] : [config: T];
|
||||
type NotNever<T> = [T] extends [never] ? false : true;
|
||||
|
||||
// </ApiClientTypes>
|
||||
|
||||
// <TypedStatusError>
|
||||
export class TypedStatusError<TData = unknown> extends Error {
|
||||
response: TypedErrorResponse<TData, ErrorStatusCode, unknown>;
|
||||
status: number;
|
||||
constructor(response: TypedErrorResponse<TData, ErrorStatusCode, unknown>) {
|
||||
super(`HTTP ${response.status}: ${response.statusText}`);
|
||||
this.name = "TypedStatusError";
|
||||
this.response = response;
|
||||
this.status = response.status;
|
||||
}
|
||||
}
|
||||
// </TypedStatusError>
|
||||
|
||||
// <ApiClient>
|
||||
export class ApiClient {
|
||||
baseUrl: string = "";
|
||||
successStatusCodes = successStatusCodes;
|
||||
errorStatusCodes = errorStatusCodes;
|
||||
|
||||
constructor(public fetcher: Fetcher) {}
|
||||
|
||||
setBaseUrl(baseUrl: string) {
|
||||
this.baseUrl = baseUrl;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace path parameters in URL
|
||||
* Supports both OpenAPI format {param} and Express format :param
|
||||
*/
|
||||
defaultDecodePathParams = (url: string, params: Record<string, string>): string => {
|
||||
return url
|
||||
.replace(/{(\w+)}/g, (_, key: string) => params[key] || `{${key}}`)
|
||||
.replace(/:([a-zA-Z0-9_]+)/g, (_, key: string) => params[key] || `:${key}`);
|
||||
};
|
||||
|
||||
/** Uses URLSearchParams, skips null/undefined values */
|
||||
defaultEncodeSearchParams = (queryParams: Record<string, unknown> | undefined): URLSearchParams | undefined => {
|
||||
if (!queryParams) return;
|
||||
|
||||
const searchParams = new URLSearchParams();
|
||||
Object.entries(queryParams).forEach(([key, value]) => {
|
||||
if (value != null) {
|
||||
// Skip null/undefined values
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((val) => val != null && searchParams.append(key, String(val)));
|
||||
} else {
|
||||
searchParams.append(key, String(value));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return searchParams;
|
||||
};
|
||||
|
||||
defaultParseResponseData = async (response: Response): Promise<unknown> => {
|
||||
const contentType = response.headers.get("content-type") ?? "";
|
||||
if (contentType.startsWith("text/")) {
|
||||
return await response.text();
|
||||
}
|
||||
|
||||
if (contentType === "application/octet-stream") {
|
||||
return await response.arrayBuffer();
|
||||
}
|
||||
|
||||
if (
|
||||
contentType.includes("application/json") ||
|
||||
(contentType.includes("application/") && contentType.includes("json")) ||
|
||||
contentType === "*/*"
|
||||
) {
|
||||
try {
|
||||
return await response.json();
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
};
|
||||
|
||||
// <ApiClient.post>
|
||||
post<Path extends keyof PostEndpoints, TEndpoint extends PostEndpoints[Path]>(
|
||||
path: Path,
|
||||
...params: MaybeOptionalArg<
|
||||
TEndpoint extends { parameters: infer UParams }
|
||||
? NotNever<UParams> extends true
|
||||
? UParams & { overrides?: RequestInit; withResponse?: false; throwOnStatusError?: boolean }
|
||||
: { overrides?: RequestInit; withResponse?: false; throwOnStatusError?: boolean }
|
||||
: { overrides?: RequestInit; withResponse?: false; throwOnStatusError?: boolean }
|
||||
>
|
||||
): Promise<Extract<InferResponseByStatus<TEndpoint, SuccessStatusCode>, { data: {} }>["data"]>;
|
||||
|
||||
post<Path extends keyof PostEndpoints, TEndpoint extends PostEndpoints[Path]>(
|
||||
path: Path,
|
||||
...params: MaybeOptionalArg<
|
||||
TEndpoint extends { parameters: infer UParams }
|
||||
? NotNever<UParams> extends true
|
||||
? UParams & { overrides?: RequestInit; withResponse?: true; throwOnStatusError?: boolean }
|
||||
: { overrides?: RequestInit; withResponse?: true; throwOnStatusError?: boolean }
|
||||
: { overrides?: RequestInit; withResponse?: true; throwOnStatusError?: boolean }
|
||||
>
|
||||
): Promise<SafeApiResponse<TEndpoint>>;
|
||||
|
||||
post<Path extends keyof PostEndpoints, _TEndpoint extends PostEndpoints[Path]>(
|
||||
path: Path,
|
||||
...params: MaybeOptionalArg<any>
|
||||
): Promise<any> {
|
||||
return this.request("post", path, ...params);
|
||||
}
|
||||
// </ApiClient.post>
|
||||
|
||||
// <ApiClient.get>
|
||||
get<Path extends keyof GetEndpoints, TEndpoint extends GetEndpoints[Path]>(
|
||||
path: Path,
|
||||
...params: MaybeOptionalArg<
|
||||
TEndpoint extends { parameters: infer UParams }
|
||||
? NotNever<UParams> extends true
|
||||
? UParams & { overrides?: RequestInit; withResponse?: false; throwOnStatusError?: boolean }
|
||||
: { overrides?: RequestInit; withResponse?: false; throwOnStatusError?: boolean }
|
||||
: { overrides?: RequestInit; withResponse?: false; throwOnStatusError?: boolean }
|
||||
>
|
||||
): Promise<Extract<InferResponseByStatus<TEndpoint, SuccessStatusCode>, { data: {} }>["data"]>;
|
||||
|
||||
get<Path extends keyof GetEndpoints, TEndpoint extends GetEndpoints[Path]>(
|
||||
path: Path,
|
||||
...params: MaybeOptionalArg<
|
||||
TEndpoint extends { parameters: infer UParams }
|
||||
? NotNever<UParams> extends true
|
||||
? UParams & { overrides?: RequestInit; withResponse?: true; throwOnStatusError?: boolean }
|
||||
: { overrides?: RequestInit; withResponse?: true; throwOnStatusError?: boolean }
|
||||
: { overrides?: RequestInit; withResponse?: true; throwOnStatusError?: boolean }
|
||||
>
|
||||
): Promise<SafeApiResponse<TEndpoint>>;
|
||||
|
||||
get<Path extends keyof GetEndpoints, _TEndpoint extends GetEndpoints[Path]>(
|
||||
path: Path,
|
||||
...params: MaybeOptionalArg<any>
|
||||
): Promise<any> {
|
||||
return this.request("get", path, ...params);
|
||||
}
|
||||
// </ApiClient.get>
|
||||
|
||||
// <ApiClient.request>
|
||||
/**
|
||||
* Generic request method with full type-safety for any endpoint
|
||||
*/
|
||||
request<
|
||||
TMethod extends keyof EndpointByMethod,
|
||||
TPath extends keyof EndpointByMethod[TMethod],
|
||||
TEndpoint extends EndpointByMethod[TMethod][TPath],
|
||||
>(
|
||||
method: TMethod,
|
||||
path: TPath,
|
||||
...params: MaybeOptionalArg<
|
||||
TEndpoint extends { parameters: infer UParams }
|
||||
? NotNever<UParams> extends true
|
||||
? UParams & { overrides?: RequestInit; withResponse?: false; throwOnStatusError?: boolean }
|
||||
: { overrides?: RequestInit; withResponse?: false; throwOnStatusError?: boolean }
|
||||
: { overrides?: RequestInit; withResponse?: false; throwOnStatusError?: boolean }
|
||||
>
|
||||
): Promise<Extract<InferResponseByStatus<TEndpoint, SuccessStatusCode>, { data: {} }>["data"]>;
|
||||
|
||||
request<
|
||||
TMethod extends keyof EndpointByMethod,
|
||||
TPath extends keyof EndpointByMethod[TMethod],
|
||||
TEndpoint extends EndpointByMethod[TMethod][TPath],
|
||||
>(
|
||||
method: TMethod,
|
||||
path: TPath,
|
||||
...params: MaybeOptionalArg<
|
||||
TEndpoint extends { parameters: infer UParams }
|
||||
? NotNever<UParams> extends true
|
||||
? UParams & { overrides?: RequestInit; withResponse?: true; throwOnStatusError?: boolean }
|
||||
: { overrides?: RequestInit; withResponse?: true; throwOnStatusError?: boolean }
|
||||
: { overrides?: RequestInit; withResponse?: true; throwOnStatusError?: boolean }
|
||||
>
|
||||
): Promise<SafeApiResponse<TEndpoint>>;
|
||||
|
||||
request<
|
||||
TMethod extends keyof EndpointByMethod,
|
||||
TPath extends keyof EndpointByMethod[TMethod],
|
||||
TEndpoint extends EndpointByMethod[TMethod][TPath],
|
||||
>(method: TMethod, path: TPath, ...params: MaybeOptionalArg<any>): Promise<any> {
|
||||
const requestParams = params[0];
|
||||
const withResponse = requestParams?.withResponse;
|
||||
const {
|
||||
withResponse: _,
|
||||
throwOnStatusError = withResponse ? false : true,
|
||||
overrides,
|
||||
...fetchParams
|
||||
} = requestParams || {};
|
||||
|
||||
const parametersToSend: EndpointParameters = {};
|
||||
if (requestParams?.body !== undefined) (parametersToSend as any).body = requestParams.body;
|
||||
if (requestParams?.query !== undefined) (parametersToSend as any).query = requestParams.query;
|
||||
if (requestParams?.header !== undefined) (parametersToSend as any).header = requestParams.header;
|
||||
if (requestParams?.path !== undefined) (parametersToSend as any).path = requestParams.path;
|
||||
|
||||
const resolvedPath = (this.fetcher.decodePathParams ?? this.defaultDecodePathParams)(
|
||||
this.baseUrl + (path as string),
|
||||
(parametersToSend.path ?? {}) as Record<string, string>,
|
||||
);
|
||||
const url = new URL(resolvedPath);
|
||||
const urlSearchParams = (this.fetcher.encodeSearchParams ?? this.defaultEncodeSearchParams)(parametersToSend.query);
|
||||
|
||||
const promise = this.fetcher
|
||||
.fetch({
|
||||
method: method,
|
||||
path: path as string,
|
||||
url,
|
||||
urlSearchParams,
|
||||
parameters: Object.keys(fetchParams).length ? fetchParams : undefined,
|
||||
overrides,
|
||||
throwOnStatusError,
|
||||
})
|
||||
.then(async (response) => {
|
||||
const data = await (this.fetcher.parseResponseData ?? this.defaultParseResponseData)(response);
|
||||
const typedResponse = Object.assign(response, {
|
||||
data: data,
|
||||
json: () => Promise.resolve(data),
|
||||
}) as SafeApiResponse<TEndpoint>;
|
||||
|
||||
if (throwOnStatusError && errorStatusCodes.includes(response.status as never)) {
|
||||
throw new TypedStatusError(typedResponse as never);
|
||||
}
|
||||
|
||||
return withResponse ? typedResponse : data;
|
||||
});
|
||||
|
||||
return promise as Extract<InferResponseByStatus<TEndpoint, SuccessStatusCode>, { data: {} }>["data"];
|
||||
}
|
||||
// </ApiClient.request>
|
||||
}
|
||||
|
||||
export function createApiClient(fetcher: Fetcher, baseUrl?: string) {
|
||||
return new ApiClient(fetcher).setBaseUrl(baseUrl ?? "");
|
||||
}
|
||||
|
||||
/**
|
||||
Example usage:
|
||||
const api = createApiClient((method, url, params) =>
|
||||
fetch(url, { method, body: JSON.stringify(params) }).then((res) => res.json()),
|
||||
);
|
||||
api.get("/users").then((users) => console.log(users));
|
||||
api.post("/users", { body: { name: "John" } }).then((user) => console.log(user));
|
||||
api.put("/users/:id", { path: { id: 1 }, body: { name: "John" } }).then((user) => console.log(user));
|
||||
|
||||
// With error handling
|
||||
const result = await api.get("/users/{id}", { path: { id: "123" }, withResponse: true });
|
||||
if (result.ok) {
|
||||
// Access data directly
|
||||
const user = result.data;
|
||||
console.log(user);
|
||||
|
||||
// Or use the json() method for compatibility
|
||||
const userFromJson = await result.json();
|
||||
console.log(userFromJson);
|
||||
} else {
|
||||
const error = result.data;
|
||||
console.error(`Error ${result.status}:`, error);
|
||||
}
|
||||
*/
|
||||
|
||||
// </ApiClient>
|
||||
216
apps/frontend/app/generated/api-client/tanstack-client.ts
Normal file
216
apps/frontend/app/generated/api-client/tanstack-client.ts
Normal file
@@ -0,0 +1,216 @@
|
||||
import { queryOptions } from "@tanstack/react-query";
|
||||
import type {
|
||||
EndpointByMethod,
|
||||
ApiClient,
|
||||
SuccessStatusCode,
|
||||
ErrorStatusCode,
|
||||
InferResponseByStatus,
|
||||
TypedSuccessResponse,
|
||||
} from "./api-client.ts";
|
||||
import { errorStatusCodes, TypedStatusError } from "./api-client.ts";
|
||||
|
||||
type EndpointQueryKey<TOptions extends EndpointParameters> = [
|
||||
TOptions & {
|
||||
_id: string;
|
||||
_infinite?: boolean;
|
||||
},
|
||||
];
|
||||
|
||||
const createQueryKey = <TOptions extends EndpointParameters>(
|
||||
id: string,
|
||||
options?: TOptions,
|
||||
infinite?: boolean,
|
||||
): [EndpointQueryKey<TOptions>[0]] => {
|
||||
const params: EndpointQueryKey<TOptions>[0] = { _id: id } as EndpointQueryKey<TOptions>[0];
|
||||
if (infinite) {
|
||||
params._infinite = infinite;
|
||||
}
|
||||
if (options?.body) {
|
||||
params.body = options.body;
|
||||
}
|
||||
if (options?.header) {
|
||||
params.header = options.header;
|
||||
}
|
||||
if (options?.path) {
|
||||
params.path = options.path;
|
||||
}
|
||||
if (options?.query) {
|
||||
params.query = options.query;
|
||||
}
|
||||
return [params];
|
||||
};
|
||||
|
||||
// <EndpointByMethod.Shorthands>
|
||||
export type PostEndpoints = EndpointByMethod["post"];
|
||||
export type GetEndpoints = EndpointByMethod["get"];
|
||||
// </EndpointByMethod.Shorthands>
|
||||
|
||||
// <ApiClientTypes>
|
||||
export type EndpointParameters = {
|
||||
body?: unknown;
|
||||
query?: Record<string, unknown>;
|
||||
header?: Record<string, unknown>;
|
||||
path?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
type RequiredKeys<T> = {
|
||||
[P in keyof T]-?: undefined extends T[P] ? never : P;
|
||||
}[keyof T];
|
||||
|
||||
type MaybeOptionalArg<T> = RequiredKeys<T> extends never ? [config?: T] : [config: T];
|
||||
|
||||
type InferResponseData<TEndpoint, TStatusCode> =
|
||||
TypedSuccessResponse<any, any, any> extends InferResponseByStatus<TEndpoint, TStatusCode>
|
||||
? Extract<InferResponseByStatus<TEndpoint, TStatusCode>, { data: {} }>["data"]
|
||||
: Extract<InferResponseByStatus<TEndpoint, TStatusCode>["data"], {}>;
|
||||
|
||||
// </ApiClientTypes>
|
||||
|
||||
// <ApiClient>
|
||||
export class TanstackQueryApiClient {
|
||||
constructor(public client: ApiClient) {}
|
||||
|
||||
// <ApiClient.post>
|
||||
post<Path extends keyof PostEndpoints, TEndpoint extends PostEndpoints[Path]>(
|
||||
path: Path,
|
||||
...params: MaybeOptionalArg<TEndpoint["parameters"]>
|
||||
) {
|
||||
const queryKey = createQueryKey(path as string, params[0]);
|
||||
const query = {
|
||||
/** type-only property if you need easy access to the endpoint params */
|
||||
"~endpoint": {} as TEndpoint,
|
||||
queryKey,
|
||||
queryFn: {} as "You need to pass .queryOptions to the useQuery hook",
|
||||
queryOptions: queryOptions({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const requestParams = {
|
||||
...(params[0] || {}),
|
||||
...(queryKey[0] || {}),
|
||||
overrides: { signal },
|
||||
withResponse: false as const,
|
||||
};
|
||||
const res = await this.client.post(path, requestParams as never);
|
||||
return res as InferResponseData<TEndpoint, SuccessStatusCode>;
|
||||
},
|
||||
queryKey: queryKey,
|
||||
}),
|
||||
};
|
||||
|
||||
return query;
|
||||
}
|
||||
// </ApiClient.post>
|
||||
|
||||
// <ApiClient.get>
|
||||
get<Path extends keyof GetEndpoints, TEndpoint extends GetEndpoints[Path]>(
|
||||
path: Path,
|
||||
...params: MaybeOptionalArg<TEndpoint["parameters"]>
|
||||
) {
|
||||
const queryKey = createQueryKey(path as string, params[0]);
|
||||
const query = {
|
||||
/** type-only property if you need easy access to the endpoint params */
|
||||
"~endpoint": {} as TEndpoint,
|
||||
queryKey,
|
||||
queryFn: {} as "You need to pass .queryOptions to the useQuery hook",
|
||||
queryOptions: queryOptions({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const requestParams = {
|
||||
...(params[0] || {}),
|
||||
...(queryKey[0] || {}),
|
||||
overrides: { signal },
|
||||
withResponse: false as const,
|
||||
};
|
||||
const res = await this.client.get(path, requestParams as never);
|
||||
return res as InferResponseData<TEndpoint, SuccessStatusCode>;
|
||||
},
|
||||
queryKey: queryKey,
|
||||
}),
|
||||
};
|
||||
|
||||
return query;
|
||||
}
|
||||
// </ApiClient.get>
|
||||
|
||||
// <ApiClient.request>
|
||||
/**
|
||||
* Generic mutation method with full type-safety for any endpoint; it doesnt require parameters to be passed initially
|
||||
* but instead will require them to be passed when calling the mutation.mutate() method
|
||||
*/
|
||||
mutation<
|
||||
TMethod extends keyof EndpointByMethod,
|
||||
TPath extends keyof EndpointByMethod[TMethod],
|
||||
TEndpoint extends EndpointByMethod[TMethod][TPath],
|
||||
TWithResponse extends boolean = false,
|
||||
TSelection = TWithResponse extends true
|
||||
? InferResponseByStatus<TEndpoint, SuccessStatusCode>
|
||||
: InferResponseData<TEndpoint, SuccessStatusCode>,
|
||||
TError = TEndpoint extends { responses: infer TResponses }
|
||||
? TResponses extends Record<string | number, unknown>
|
||||
? TypedStatusError<InferResponseData<TEndpoint, ErrorStatusCode>>
|
||||
: Error
|
||||
: Error,
|
||||
>(
|
||||
method: TMethod,
|
||||
path: TPath,
|
||||
options?: {
|
||||
withResponse?: TWithResponse;
|
||||
selectFn?: (
|
||||
res: TWithResponse extends true
|
||||
? InferResponseByStatus<TEndpoint, SuccessStatusCode>
|
||||
: InferResponseData<TEndpoint, SuccessStatusCode>,
|
||||
) => TSelection;
|
||||
throwOnStatusError?: boolean;
|
||||
throwOnError?: boolean | ((error: TError) => boolean);
|
||||
},
|
||||
) {
|
||||
const mutationKey = [{ method, path }] as const;
|
||||
const mutationFn = async (
|
||||
params: (TEndpoint extends { parameters: infer Parameters } ? Parameters : {}) & {
|
||||
throwOnStatusError?: boolean;
|
||||
overrides?: RequestInit;
|
||||
},
|
||||
): Promise<TSelection> => {
|
||||
const withResponse = options?.withResponse ?? false;
|
||||
const throwOnStatusError =
|
||||
params.throwOnStatusError ?? options?.throwOnStatusError ?? (withResponse ? false : true);
|
||||
const selectFn = options?.selectFn;
|
||||
const response = await (this.client as any)[method](path, {
|
||||
...(params as any),
|
||||
withResponse: true,
|
||||
throwOnStatusError: false,
|
||||
});
|
||||
|
||||
if (throwOnStatusError && errorStatusCodes.includes(response.status as never)) {
|
||||
throw new TypedStatusError(response as never);
|
||||
}
|
||||
|
||||
// Return just the data if withResponse is false, otherwise return the full response
|
||||
const finalResponse = withResponse ? response : response.data;
|
||||
const res = selectFn ? selectFn(finalResponse as any) : finalResponse;
|
||||
return res as never;
|
||||
};
|
||||
return {
|
||||
/** type-only property if you need easy access to the endpoint params */
|
||||
"~endpoint": {} as TEndpoint,
|
||||
mutationKey: mutationKey,
|
||||
mutationFn: {} as "You need to pass .mutationOptions to the useMutation hook",
|
||||
mutationOptions: {
|
||||
throwOnError: options?.throwOnError as boolean | ((error: TError) => boolean),
|
||||
mutationKey: mutationKey,
|
||||
mutationFn: mutationFn,
|
||||
} as Omit<
|
||||
import("@tanstack/react-query").UseMutationOptions<
|
||||
TSelection,
|
||||
TError,
|
||||
(TEndpoint extends { parameters: infer Parameters } ? Parameters : {}) & {
|
||||
withResponse?: boolean;
|
||||
throwOnStatusError?: boolean;
|
||||
}
|
||||
>,
|
||||
"mutationFn"
|
||||
> & {
|
||||
mutationFn: typeof mutationFn;
|
||||
},
|
||||
};
|
||||
}
|
||||
// </ApiClient.request>
|
||||
}
|
||||
73
apps/frontend/app/hooks/ResponseHelper.tsx
Normal file
73
apps/frontend/app/hooks/ResponseHelper.tsx
Normal file
@@ -0,0 +1,73 @@
|
||||
import { AxiosError } from 'axios';
|
||||
import { useLocation, useNavigate } from 'react-router';
|
||||
import { SearchParamKeys } from '../lib/constants';
|
||||
import { useQueryMessage } from './useQueryMessage';
|
||||
import { QueryMessageCode, QueryMessageType } from '../lib/QueryMessages';
|
||||
import { useCallback } from 'react';
|
||||
import { displayForbiddenErrorToast, displayNetworkErrorToast, displayUnexpectedErrorToast } from '../lib/toasts';
|
||||
|
||||
export enum ResponseErrorToastId {
|
||||
NetworkError = 'network-error',
|
||||
}
|
||||
|
||||
export type DefaultResponseErrorHandlerOptions = {
|
||||
disableUnauthorizedHandling?: boolean;
|
||||
disableHandleUnexpectedErrors?: boolean;
|
||||
disableIgnoreCanceledRequests?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param err error value
|
||||
* @returns {boolean} true if the error was handled, false otherwise
|
||||
*/
|
||||
|
||||
export function useResponseErrorHandler(): {
|
||||
defaultResponseErrorHandler: typeof defaultResponseErrorHandler;
|
||||
} {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const { toSearchParamQueryMessage } = useQueryMessage();
|
||||
|
||||
const defaultResponseErrorHandler = useCallback(
|
||||
(err: unknown, options?: DefaultResponseErrorHandlerOptions): boolean => {
|
||||
if (!(err instanceof AxiosError) && !options?.disableHandleUnexpectedErrors) {
|
||||
displayUnexpectedErrorToast();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!(err instanceof AxiosError)) return false;
|
||||
|
||||
if (err.message === 'canceled') {
|
||||
// request was aborted, ignore but return true to indicate it was handled
|
||||
return !options?.disableIgnoreCanceledRequests;
|
||||
}
|
||||
|
||||
if (err.message === 'Network Error') {
|
||||
displayNetworkErrorToast();
|
||||
return true;
|
||||
}
|
||||
|
||||
// handle 401 Unauthorized globally
|
||||
if (err.status === 401 && !options?.disableUnauthorizedHandling) {
|
||||
// store current path for redirect after login
|
||||
const currentPath = location.pathname + location.search;
|
||||
const searchParam = new URLSearchParams();
|
||||
searchParam.set(SearchParamKeys.Redirect, currentPath);
|
||||
searchParam.set(SearchParamKeys.Message, toSearchParamQueryMessage(QueryMessageCode.SessionExpired, QueryMessageType.Info));
|
||||
navigate(`/login?${searchParam.toString()}`);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (err.status === 403) {
|
||||
displayForbiddenErrorToast();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
[location, navigate, toSearchParamQueryMessage]
|
||||
);
|
||||
|
||||
return { defaultResponseErrorHandler };
|
||||
}
|
||||
48
apps/frontend/app/hooks/ensureLoggedIn.tsx
Normal file
48
apps/frontend/app/hooks/ensureLoggedIn.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { useAuth } from '../providers/AuthProvider';
|
||||
import { useApi } from '../providers/ApiProvider';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useResponseErrorHandler } from './ResponseHelper';
|
||||
|
||||
export type EnsureLoggedInResult = {
|
||||
checking: boolean;
|
||||
loggedIn: boolean;
|
||||
};
|
||||
|
||||
export function useEnsureLoggedIn(): EnsureLoggedInResult {
|
||||
const { user, setUser } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const { tanstackApiClient } = useApi();
|
||||
const { defaultResponseErrorHandler } = useResponseErrorHandler();
|
||||
|
||||
const { queryOptions: currentUserQuery } = tanstackApiClient.get('/api/user/me');
|
||||
const { isFetched, isPending } = useQuery({
|
||||
...currentUserQuery,
|
||||
queryFn: async (...args) => {
|
||||
try {
|
||||
const data = await currentUserQuery.queryFn!(...args);
|
||||
setUser({
|
||||
id: data.id,
|
||||
name: data.username,
|
||||
});
|
||||
return data;
|
||||
} catch (error) {
|
||||
if (defaultResponseErrorHandler(error)) return {} as never;
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
navigate('/', { replace: true });
|
||||
return;
|
||||
}
|
||||
}, [user, setUser, navigate]);
|
||||
|
||||
return {
|
||||
checking: isPending,
|
||||
loggedIn: isFetched && !!user,
|
||||
};
|
||||
}
|
||||
111
apps/frontend/app/hooks/useQueryMessage.tsx
Normal file
111
apps/frontend/app/hooks/useQueryMessage.tsx
Normal file
@@ -0,0 +1,111 @@
|
||||
import { useCallback, useEffect, useRef, type ReactNode } from 'react';
|
||||
import { useLocation, useSearchParams } from 'react-router';
|
||||
import { toast } from 'react-toastify/unstyled';
|
||||
import { SearchParamKeys } from '../lib/constants';
|
||||
import { CODE_TO_MESSAGE_MAP, QueryMessageCode, QueryMessageType } from '../lib/QueryMessages';
|
||||
|
||||
type QueryMessageString = `${QueryMessageCode}__${QueryMessageType}`;
|
||||
|
||||
export type QueryMessage = {
|
||||
type: QueryMessageType;
|
||||
code: QueryMessageCode;
|
||||
message: ReactNode;
|
||||
};
|
||||
|
||||
export type UseQueryMessageOptions = {
|
||||
displayMessages?: boolean;
|
||||
};
|
||||
|
||||
export type UseQueryMessageReturn = {
|
||||
setQueryMessage: (messageCode: QueryMessageCode, messageType: QueryMessageType) => void;
|
||||
clearQueryMessage: () => void;
|
||||
toSearchParamQueryMessage: (message: QueryMessageCode, type: QueryMessageType) => QueryMessageString;
|
||||
};
|
||||
|
||||
export function useQueryMessage(
|
||||
{ displayMessages }: UseQueryMessageOptions = {
|
||||
displayMessages: true,
|
||||
}
|
||||
): UseQueryMessageReturn {
|
||||
const location = useLocation();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const messageStr = useRef<QueryMessageString | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
// Reset messageStr when location changes to allow re-displaying the same message on navigation
|
||||
messageStr.current = null;
|
||||
}, [location.pathname]);
|
||||
|
||||
useEffect(() => {
|
||||
const queryMessageStr = searchParams.get(SearchParamKeys.Message);
|
||||
if (!(queryMessageStr && queryMessageStr !== messageStr.current)) return;
|
||||
const [queryMessage, queryMessageString] = toQueryMessage(queryMessageStr) ?? [null, null];
|
||||
if (!queryMessage) return;
|
||||
|
||||
messageStr.current = queryMessageString;
|
||||
if (displayMessages) {
|
||||
toast[queryMessage.type](queryMessage.message, {
|
||||
position: 'top-center',
|
||||
autoClose: 5000,
|
||||
hideProgressBar: false,
|
||||
closeOnClick: true,
|
||||
pauseOnHover: true,
|
||||
draggable: false,
|
||||
progress: undefined,
|
||||
theme: 'colored',
|
||||
toastId: 'login-route-info-message',
|
||||
});
|
||||
}
|
||||
}, [displayMessages, searchParams]);
|
||||
|
||||
const setQueryMessage = useCallback(
|
||||
(messageCode: QueryMessageCode, messageType: QueryMessageType) => {
|
||||
const queryMessageString: QueryMessageString = `${messageCode}__${messageType}`;
|
||||
messageStr.current = queryMessageString;
|
||||
setSearchParams((prev) => {
|
||||
prev.set(SearchParamKeys.Message, queryMessageString);
|
||||
return prev;
|
||||
});
|
||||
},
|
||||
[setSearchParams]
|
||||
);
|
||||
|
||||
const clearQueryMessage = useCallback(() => {
|
||||
messageStr.current = null;
|
||||
setSearchParams((prev) => {
|
||||
prev.delete(SearchParamKeys.Message);
|
||||
return prev;
|
||||
});
|
||||
}, [setSearchParams]);
|
||||
|
||||
const toSearchParamQueryMessage = useCallback((message: QueryMessageCode, type: QueryMessageType): QueryMessageString => {
|
||||
return `${message}__${type}`;
|
||||
}, []);
|
||||
|
||||
return {
|
||||
setQueryMessage,
|
||||
clearQueryMessage,
|
||||
toSearchParamQueryMessage,
|
||||
};
|
||||
}
|
||||
|
||||
function isValidQueryMessageCode(code: string): code is QueryMessageCode {
|
||||
return Object.values(QueryMessageCode).includes(code as QueryMessageCode);
|
||||
}
|
||||
|
||||
function isValidQueryMessageType(type: string): type is QueryMessageType {
|
||||
return Object.values(QueryMessageType).includes(type as QueryMessageType);
|
||||
}
|
||||
|
||||
function toQueryMessage(value: string): [QueryMessage, QueryMessageString] | null {
|
||||
const [code, type] = value.split('__');
|
||||
if (!isValidQueryMessageCode(code) || !isValidQueryMessageType(type)) return null;
|
||||
return [
|
||||
{
|
||||
code: code,
|
||||
type: type,
|
||||
message: CODE_TO_MESSAGE_MAP[code],
|
||||
},
|
||||
`${code}__${type}`,
|
||||
];
|
||||
}
|
||||
20
apps/frontend/app/lib/QueryMessages.tsx
Normal file
20
apps/frontend/app/lib/QueryMessages.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
export enum QueryMessageType {
|
||||
Info = 'info',
|
||||
Success = 'success',
|
||||
Warning = 'warning',
|
||||
Error = 'error',
|
||||
}
|
||||
|
||||
export enum QueryMessageCode {
|
||||
SessionExpired = 'SESSION_EXPIRED',
|
||||
InitializationRequired = 'INITIALIZATION_REQUIRED',
|
||||
InitializationSuccessful = 'INITIALIZATION_SUCCESSFUL',
|
||||
}
|
||||
|
||||
export const CODE_TO_MESSAGE_MAP: Record<QueryMessageCode, ReactNode> = {
|
||||
[QueryMessageCode.SessionExpired]: 'Your session has expired. Please log in again.',
|
||||
[QueryMessageCode.InitializationRequired]: 'The application requires initialization. Please follow the setup instructions.',
|
||||
[QueryMessageCode.InitializationSuccessful]: 'Initialization successful. Please log in.',
|
||||
} as const;
|
||||
121
apps/frontend/app/lib/api.ts
Normal file
121
apps/frontend/app/lib/api.ts
Normal file
@@ -0,0 +1,121 @@
|
||||
import type { AxiosInstance, AxiosResponse } from 'axios';
|
||||
import { type Fetcher, type Method, createApiClient } from '../generated/api-client/api-client';
|
||||
import { TanstackQueryApiClient } from '../generated/api-client/tanstack-client';
|
||||
|
||||
const API_BASE_URL: string | undefined = import.meta.env.VITE_API_BASE_URL;
|
||||
|
||||
const get_fetch: (axios: AxiosInstance) => Fetcher['fetch'] =
|
||||
(axios) =>
|
||||
async ({ method, url: incomingUrl, parameters: params }) => {
|
||||
// Use a plain object for Axios headers
|
||||
const headers: Record<string, string> = {};
|
||||
|
||||
// Replace path parameters (supports both {param} and :param formats)
|
||||
const actualUrl = replacePathParams(incomingUrl.toString(), (params?.path ?? {}) as Record<string, string>);
|
||||
const url = new URL(actualUrl);
|
||||
|
||||
// Handle query parameters
|
||||
if (params?.query) {
|
||||
const searchParams = new URLSearchParams();
|
||||
Object.entries(params.query).forEach(([key, value]) => {
|
||||
if (value != null) {
|
||||
// Skip null/undefined values
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((val) => val != null && searchParams.append(key, String(val)));
|
||||
} else {
|
||||
searchParams.append(key, String(value));
|
||||
}
|
||||
}
|
||||
});
|
||||
url.search = searchParams.toString();
|
||||
}
|
||||
|
||||
// Handle request body for mutation methods (use Axios `data`)
|
||||
const data = (['post', 'put', 'patch', 'delete'] satisfies Method[] as string[]).includes(method.toLowerCase()) ? params?.body : undefined;
|
||||
|
||||
if (data != null) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
}
|
||||
|
||||
// Add custom headers
|
||||
if (params?.header) {
|
||||
Object.entries(params.header).forEach(([key, value]) => {
|
||||
if (value != null) {
|
||||
headers[key] = String(value);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const response = await axios(url.toString(), {
|
||||
method: method.toUpperCase(),
|
||||
...(data !== undefined && { data }),
|
||||
headers: headers,
|
||||
});
|
||||
|
||||
return axiosResponseToFetchResponse(response);
|
||||
};
|
||||
|
||||
function axiosResponseToFetchResponse(response: AxiosResponse): Response {
|
||||
const headers = new Headers();
|
||||
Object.entries(response.headers).forEach(([key, value]) => {
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((val) => headers.append(key, val));
|
||||
} else {
|
||||
headers.append(key, value);
|
||||
}
|
||||
});
|
||||
|
||||
// Normalize Axios response.data to a Fetch-compatible BodyInit
|
||||
let body: BodyInit | null = null;
|
||||
const data = response.data;
|
||||
|
||||
if (data == null) {
|
||||
body = null;
|
||||
} else if (
|
||||
typeof data === 'string' ||
|
||||
data instanceof Blob ||
|
||||
data instanceof ArrayBuffer ||
|
||||
ArrayBuffer.isView(data) ||
|
||||
data instanceof FormData ||
|
||||
data instanceof URLSearchParams
|
||||
) {
|
||||
body = data as BodyInit;
|
||||
} else {
|
||||
try {
|
||||
body = JSON.stringify(data);
|
||||
if (!headers.has('content-type')) {
|
||||
headers.set('content-type', 'application/json;charset=utf-8');
|
||||
}
|
||||
} catch {
|
||||
console.warn('Failed to stringify response data as JSON, falling back to string conversion.');
|
||||
body = String(data);
|
||||
}
|
||||
}
|
||||
|
||||
return new Response(body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: headers,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace path parameters in URL
|
||||
* Supports both OpenAPI format {param} and Express format :param
|
||||
*/
|
||||
function replacePathParams(url: string, params: Record<string, string>): string {
|
||||
return url.replace(/{(\w+)}/g, (_, key: string) => params[key] || `{${key}}`).replace(/:([a-zA-Z0-9_]+)/g, (_, key: string) => params[key] || `:${key}`);
|
||||
}
|
||||
|
||||
export function createApi(axios: AxiosInstance) {
|
||||
return createApiClient(
|
||||
{
|
||||
fetch: get_fetch(axios),
|
||||
},
|
||||
API_BASE_URL ?? window.location.origin
|
||||
);
|
||||
}
|
||||
|
||||
export function createTanstackApi(axios: AxiosInstance) {
|
||||
return new TanstackQueryApiClient(createApi(axios));
|
||||
}
|
||||
4
apps/frontend/app/lib/constants.ts
Normal file
4
apps/frontend/app/lib/constants.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export enum SearchParamKeys {
|
||||
Redirect = 'redirect',
|
||||
Message = 'message',
|
||||
}
|
||||
64
apps/frontend/app/lib/toasts.tsx
Normal file
64
apps/frontend/app/lib/toasts.tsx
Normal file
@@ -0,0 +1,64 @@
|
||||
import { toast, type ToastOptions } from 'react-toastify/unstyled';
|
||||
import { Text } from '@radix-ui/themes';
|
||||
import { ResponseErrorToastId } from '../hooks/ResponseHelper';
|
||||
|
||||
export const displayUnexpectedErrorToast = (options: ToastOptions = {}) => {
|
||||
toast.error(
|
||||
<div>
|
||||
<Text weight="bold">Unexpected Error:</Text>
|
||||
<br /> An unexpected error occurred. Please try again later.
|
||||
</div>,
|
||||
{
|
||||
position: 'top-center',
|
||||
autoClose: false,
|
||||
hideProgressBar: false,
|
||||
closeOnClick: true,
|
||||
pauseOnHover: true,
|
||||
draggable: false,
|
||||
progress: undefined,
|
||||
theme: 'colored',
|
||||
...options,
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
export const displayNetworkErrorToast = (options: ToastOptions = {}) => {
|
||||
toast.error(
|
||||
<div>
|
||||
<Text weight="bold">Network Error:</Text>
|
||||
<br /> Unable to reach the server. Please check your internet connection and try again.
|
||||
</div>,
|
||||
{
|
||||
toastId: ResponseErrorToastId.NetworkError,
|
||||
position: 'top-center',
|
||||
autoClose: false,
|
||||
hideProgressBar: false,
|
||||
closeOnClick: true,
|
||||
pauseOnHover: true,
|
||||
draggable: false,
|
||||
progress: undefined,
|
||||
theme: 'colored',
|
||||
...options,
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
export const displayForbiddenErrorToast = (options: ToastOptions = {}) => {
|
||||
toast.error(
|
||||
<div>
|
||||
<Text weight="bold">Forbidden:</Text>
|
||||
<br /> You do not have permission to perform this action.
|
||||
</div>,
|
||||
{
|
||||
position: 'top-center',
|
||||
autoClose: 5000,
|
||||
hideProgressBar: false,
|
||||
closeOnClick: true,
|
||||
pauseOnHover: true,
|
||||
draggable: false,
|
||||
progress: undefined,
|
||||
theme: 'colored',
|
||||
...options,
|
||||
}
|
||||
);
|
||||
};
|
||||
56
apps/frontend/app/providers/ApiHealthProvider.tsx
Normal file
56
apps/frontend/app/providers/ApiHealthProvider.tsx
Normal file
@@ -0,0 +1,56 @@
|
||||
import { useNavigate } from 'react-router';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { createContext, use, type PropsWithChildren } from 'react';
|
||||
import { useApi } from './ApiProvider';
|
||||
import { useResponseErrorHandler } from '../hooks/ResponseHelper';
|
||||
import type { Schemas } from '../generated/api-client/api-client';
|
||||
|
||||
export type HealthStatus = Schemas.HealthInfo;
|
||||
|
||||
export type ApiHealthProviderProps = PropsWithChildren<object>;
|
||||
export type ApiHealthContextType = {
|
||||
healthStatus: HealthStatus | undefined;
|
||||
};
|
||||
|
||||
const ApiHealthContext = createContext<ApiHealthContextType | null>(null);
|
||||
|
||||
export const ApiHealthProvider: React.FC<ApiHealthProviderProps> = ({ children }) => {
|
||||
const navigate = useNavigate();
|
||||
const { tanstackApiClient } = useApi();
|
||||
const { defaultResponseErrorHandler } = useResponseErrorHandler();
|
||||
|
||||
const { queryOptions: healthInfoQuery } = tanstackApiClient.get('/api/health/info');
|
||||
const { data } = useQuery({
|
||||
...healthInfoQuery,
|
||||
queryFn: async (...args) => {
|
||||
try {
|
||||
const data = await healthInfoQuery.queryFn!(...args);
|
||||
if (!data.is_initialized) {
|
||||
navigate('/init');
|
||||
}
|
||||
return data;
|
||||
} catch (error) {
|
||||
if (defaultResponseErrorHandler(error)) return {} as never;
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<ApiHealthContext
|
||||
value={{
|
||||
healthStatus: data,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</ApiHealthContext>
|
||||
);
|
||||
};
|
||||
|
||||
export const useApiHealth = (): ApiHealthContextType => {
|
||||
const context = use(ApiHealthContext);
|
||||
if (!context) {
|
||||
throw new Error('useApiHealth must be used within an ApiHealthProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
65
apps/frontend/app/providers/ApiProvider.tsx
Normal file
65
apps/frontend/app/providers/ApiProvider.tsx
Normal file
@@ -0,0 +1,65 @@
|
||||
import { createContext, use, type PropsWithChildren } from 'react';
|
||||
import { createTanstackApi, createApi } from '../lib/api';
|
||||
import axios from 'axios';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
|
||||
type ApiProviderProps = PropsWithChildren<object>;
|
||||
type ApiContextType = {
|
||||
apiClient: ReturnType<typeof createApi>;
|
||||
tanstackApiClient: ReturnType<typeof createTanstackApi>;
|
||||
};
|
||||
|
||||
const ApiContext = createContext<ApiContextType | null>(null);
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
/**
|
||||
* Example usage:
|
||||
* ```ts
|
||||
* const { tanstackApiClient } = useApi();
|
||||
* const { queryOptions } = tanstackApiClient.get('/api/health/info');
|
||||
* useQuery({
|
||||
* ...queryOptions,
|
||||
* queryFn: async (...args) => {
|
||||
* console.log('Fetching health info...');
|
||||
* const data = await queryOptions.queryFn!(...args);
|
||||
* console.log('Health Info:', data);
|
||||
* return data;
|
||||
* },
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
|
||||
export const ApiProvider: React.FC<ApiProviderProps> = ({ children }) => {
|
||||
const axiosInstance = axios.create({
|
||||
withCredentials: true,
|
||||
});
|
||||
|
||||
const internalAxiosInstance = axios.create({
|
||||
withCredentials: true,
|
||||
});
|
||||
|
||||
const apiClient = createApi(axiosInstance);
|
||||
const tanstackApiClient = createTanstackApi(internalAxiosInstance);
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ApiContext
|
||||
value={{
|
||||
apiClient,
|
||||
tanstackApiClient,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</ApiContext>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
};
|
||||
|
||||
export function useApi() {
|
||||
const context = use(ApiContext);
|
||||
if (!context) {
|
||||
throw new Error('useApi must be used within an ApiProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
47
apps/frontend/app/providers/AuthProvider.tsx
Normal file
47
apps/frontend/app/providers/AuthProvider.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
import { createContext, use, useCallback, useState, type PropsWithChildren } from 'react';
|
||||
|
||||
export type User = {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
export type AuthProviderProps = PropsWithChildren<object>;
|
||||
export type AuthContextType = {
|
||||
setUser: (user: User) => void;
|
||||
logOut: () => void;
|
||||
user: User | null;
|
||||
};
|
||||
|
||||
const AuthContext = createContext<AuthContextType | null>(null);
|
||||
|
||||
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
|
||||
const [user, setUserState] = useState<User | null>(null);
|
||||
|
||||
const setUser = useCallback((user: User) => {
|
||||
setUserState(user);
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
setUserState(null);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<AuthContext
|
||||
value={{
|
||||
user: user,
|
||||
logOut: logout,
|
||||
setUser: setUser,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</AuthContext>
|
||||
);
|
||||
};
|
||||
|
||||
export function useAuth() {
|
||||
const context = use(AuthContext);
|
||||
if (!context) {
|
||||
throw new Error('useAuth must be used within a AuthProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
18
apps/frontend/app/providers/FormProvider.tsx
Normal file
18
apps/frontend/app/providers/FormProvider.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import { createFormHook, createFormHookContexts } from '@tanstack/react-form';
|
||||
import { TextField, TextFieldErrorMessage } from '../components/Form/TextField';
|
||||
import { ResetButton, SubmitButton } from '../components/Form/Button';
|
||||
|
||||
const { fieldContext, formContext } = createFormHookContexts();
|
||||
|
||||
export const formHook = createFormHook({
|
||||
fieldComponents: {
|
||||
TextField,
|
||||
TextFieldErrorMessage,
|
||||
},
|
||||
formComponents: {
|
||||
SubmitButton,
|
||||
ResetButton,
|
||||
},
|
||||
fieldContext,
|
||||
formContext,
|
||||
});
|
||||
38
apps/frontend/app/providers/LayoutProvider.tsx
Normal file
38
apps/frontend/app/providers/LayoutProvider.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
import { createContext, use, useState, type PropsWithChildren } from 'react';
|
||||
import type { NavItem } from '../components/layout/types';
|
||||
|
||||
type LayoutProviderProps = PropsWithChildren<object>;
|
||||
type LayoutContextType = {
|
||||
activeTab: NavItem;
|
||||
setActiveTab: (tab: NavItem) => void;
|
||||
isMobileMenuOpen: boolean;
|
||||
setIsMobileMenuOpen: (open: boolean) => void;
|
||||
};
|
||||
|
||||
const LayoutContext = createContext<LayoutContextType | null>(null);
|
||||
|
||||
export const LayoutProvider: React.FC<LayoutProviderProps> = ({ children }) => {
|
||||
const [activeTab, setActiveTab] = useState<NavItem>('Dashboard');
|
||||
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<LayoutContext
|
||||
value={{
|
||||
activeTab,
|
||||
setActiveTab,
|
||||
isMobileMenuOpen,
|
||||
setIsMobileMenuOpen,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</LayoutContext>
|
||||
);
|
||||
};
|
||||
|
||||
export function useLayout() {
|
||||
const context = use(LayoutContext);
|
||||
if (!context) {
|
||||
throw new Error('useLayout must be used within a LayoutProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
83
apps/frontend/app/root.tsx
Normal file
83
apps/frontend/app/root.tsx
Normal file
@@ -0,0 +1,83 @@
|
||||
import { isRouteErrorResponse, Links, Meta, Outlet, Scripts, ScrollRestoration } from 'react-router';
|
||||
import type { Route } from './+types/root';
|
||||
import '@radix-ui/themes/styles.css';
|
||||
import './app.css';
|
||||
// start: react-toastify special import
|
||||
// ! MUST use unstyled version for dev server build, styled version for production build is handled in vite.config.ts
|
||||
import { ToastContainer } from 'react-toastify/unstyled';
|
||||
import 'react-toastify/ReactToastify.css';
|
||||
// end: react-toastify special import
|
||||
import AppTheme from './components/theme';
|
||||
import { ApiProvider } from './providers/ApiProvider';
|
||||
import { LayoutProvider } from './providers/LayoutProvider';
|
||||
import { Tooltip } from 'radix-ui';
|
||||
import { AuthProvider } from './providers/AuthProvider';
|
||||
import { ApiHealthProvider } from './providers/ApiHealthProvider';
|
||||
|
||||
export const links: Route.LinksFunction = () => [];
|
||||
|
||||
export function Layout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charSet="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<Meta />
|
||||
<Links />
|
||||
</head>
|
||||
<body>
|
||||
{children}
|
||||
<ScrollRestoration />
|
||||
<Scripts />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<>
|
||||
<AppTheme>
|
||||
<ApiProvider>
|
||||
<Tooltip.Provider delayDuration={250}>
|
||||
<LayoutProvider>
|
||||
<ApiHealthProvider>
|
||||
<AuthProvider>
|
||||
<Outlet />
|
||||
</AuthProvider>
|
||||
</ApiHealthProvider>
|
||||
</LayoutProvider>
|
||||
</Tooltip.Provider>
|
||||
</ApiProvider>
|
||||
</AppTheme>
|
||||
|
||||
<ToastContainer />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
|
||||
let message = 'Oops!';
|
||||
let details = 'An unexpected error occurred.';
|
||||
let stack: string | undefined;
|
||||
|
||||
if (isRouteErrorResponse(error)) {
|
||||
message = error.status === 404 ? '404' : 'Error';
|
||||
details = error.status === 404 ? 'The requested page could not be found.' : error.statusText || details;
|
||||
} else if (import.meta.env.DEV && error && error instanceof Error) {
|
||||
details = error.message;
|
||||
stack = error.stack;
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="pt-16 p-4 container mx-auto">
|
||||
<h1>{message}</h1>
|
||||
<p>{details}</p>
|
||||
{stack && (
|
||||
<pre className="w-full p-4 overflow-x-auto">
|
||||
<code>{stack}</code>
|
||||
</pre>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
9
apps/frontend/app/routes.ts
Normal file
9
apps/frontend/app/routes.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { type RouteConfig, index, layout, route } from '@react-router/dev/routes';
|
||||
|
||||
export default [
|
||||
route('login', 'routes/auth/login.tsx'),
|
||||
route('init', 'routes/init.tsx'),
|
||||
layout('routes/layout.tsx', [index('routes/home.tsx')]),
|
||||
// catch-all 404 route
|
||||
route('*', 'routes/404.tsx'),
|
||||
] satisfies RouteConfig;
|
||||
3
apps/frontend/app/routes/404.tsx
Normal file
3
apps/frontend/app/routes/404.tsx
Normal file
@@ -0,0 +1,3 @@
|
||||
export default function NotFound() {
|
||||
return <h1>404 - Not Found</h1>;
|
||||
}
|
||||
153
apps/frontend/app/routes/auth/login.tsx
Normal file
153
apps/frontend/app/routes/auth/login.tsx
Normal file
@@ -0,0 +1,153 @@
|
||||
import { Box, Container, Flex, Heading } from '@radix-ui/themes';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { useLocation, useNavigate } from 'react-router';
|
||||
import { toast } from 'react-toastify/unstyled';
|
||||
import * as v from 'valibot';
|
||||
import { useResponseErrorHandler } from '../../hooks/ResponseHelper';
|
||||
import { useApi } from '../../providers/ApiProvider';
|
||||
import { formHook } from '../../providers/FormProvider';
|
||||
import type { Route } from './+types/login';
|
||||
import { SearchParamKeys } from '../../lib/constants';
|
||||
import { AxiosError } from 'axios';
|
||||
import { useQueryMessage } from '../../hooks/useQueryMessage';
|
||||
|
||||
const loginFormSchema = v.object({
|
||||
username: v.pipe(v.string(), v.trim(), v.minLength(1, 'Username is required')),
|
||||
password: v.pipe(v.string(), v.minLength(1, 'Password is required')),
|
||||
});
|
||||
|
||||
// eslint-disable-next-line no-empty-pattern
|
||||
export function meta({}: Route.MetaArgs): Route.MetaDescriptors {
|
||||
return [{ title: 'Login | YANPM' }];
|
||||
}
|
||||
|
||||
// TODO: remember me
|
||||
export default function LoginRoute() {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const { tanstackApiClient } = useApi();
|
||||
const { defaultResponseErrorHandler } = useResponseErrorHandler();
|
||||
useQueryMessage();
|
||||
|
||||
const { mutateAsync: login, isPending } = useMutation({
|
||||
...tanstackApiClient.mutation('post', '/api/auth/login').mutationOptions,
|
||||
onSuccess: async () => {
|
||||
const searchParams = new URLSearchParams(location.search);
|
||||
const redirectTo = searchParams.get(SearchParamKeys.Redirect);
|
||||
if (redirectTo) {
|
||||
navigate(redirectTo);
|
||||
return;
|
||||
}
|
||||
navigate('/');
|
||||
},
|
||||
onError: (error) => {
|
||||
if (defaultResponseErrorHandler(error, { disableUnauthorizedHandling: true })) return;
|
||||
if (error instanceof AxiosError && error.status === 401) {
|
||||
toast.error('Invalid username or password.', {
|
||||
position: 'top-center',
|
||||
autoClose: 5000,
|
||||
hideProgressBar: false,
|
||||
closeOnClick: true,
|
||||
pauseOnHover: true,
|
||||
draggable: false,
|
||||
progress: undefined,
|
||||
theme: 'colored',
|
||||
});
|
||||
return;
|
||||
}
|
||||
console.error('Login failed:', error);
|
||||
},
|
||||
});
|
||||
|
||||
const form = formHook.useAppForm({
|
||||
defaultValues: {
|
||||
username: '',
|
||||
password: '',
|
||||
},
|
||||
validators: {
|
||||
onBlur: loginFormSchema,
|
||||
onSubmit: loginFormSchema,
|
||||
},
|
||||
|
||||
onSubmit: async ({ value }) => {
|
||||
toast.dismiss();
|
||||
return await login({ body: { password: value.password, username: value.username } }).catch(() => {});
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<Flex align="center" justify="center" style={{ minHeight: 'calc(100vh - 64px)' }}>
|
||||
<Container size="3" p="0">
|
||||
<Box
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
maxWidth: 420,
|
||||
margin: '40px auto',
|
||||
backgroundColor: 'white',
|
||||
padding: 24,
|
||||
borderRadius: 8,
|
||||
boxShadow: '0 6px 18px rgba(15,23,42,0.2)',
|
||||
}}
|
||||
>
|
||||
<Heading size="6" style={{ marginBottom: 16, alignSelf: 'center' }}>
|
||||
Sign In
|
||||
</Heading>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.handleSubmit();
|
||||
}}
|
||||
>
|
||||
<form.AppField
|
||||
name="username"
|
||||
children={(field) => (
|
||||
<>
|
||||
<field.TextField
|
||||
label={'Username'}
|
||||
value={field.state.value}
|
||||
autoComplete="username"
|
||||
spellCheck={false}
|
||||
required
|
||||
onChange={(e) => field.handleChange(e.target.value)}
|
||||
/>
|
||||
<field.TextFieldErrorMessage {...field.state.meta} />
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
|
||||
<form.AppField
|
||||
name="password"
|
||||
children={(field) => (
|
||||
<>
|
||||
<field.TextField
|
||||
label={'Password'}
|
||||
value={field.state.value}
|
||||
type="password"
|
||||
required
|
||||
autoComplete="current-password"
|
||||
onChange={(e) => field.handleChange(e.target.value)}
|
||||
showPasswordToggle
|
||||
/>
|
||||
<field.TextFieldErrorMessage {...field.state.meta} />
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div style={{ marginTop: 18, display: 'flex', gap: 8, justifySelf: 'center' }}>
|
||||
<form.SubmitButton
|
||||
loading={isPending}
|
||||
label={{
|
||||
default: 'Sign In',
|
||||
loading: 'Signing In…',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</form>
|
||||
</Box>
|
||||
</Container>
|
||||
</Flex>
|
||||
</>
|
||||
);
|
||||
}
|
||||
75
apps/frontend/app/routes/home.tsx
Normal file
75
apps/frontend/app/routes/home.tsx
Normal file
@@ -0,0 +1,75 @@
|
||||
import { Box, Button, Card, Flex, Grid, Heading, Text } from '@radix-ui/themes';
|
||||
import type { Route } from './+types/home';
|
||||
import TablePlaceholder from '../components/home/TablePlaceholder';
|
||||
import { useLayout } from '../providers/LayoutProvider';
|
||||
import { useEnsureLoggedIn } from '../hooks/ensureLoggedIn';
|
||||
|
||||
// eslint-disable-next-line no-empty-pattern
|
||||
export function meta({}: Route.MetaArgs) {
|
||||
return [{ title: 'Proxy Host Demo | YANPM' }, { name: 'description', content: 'Demo of the unified navigation paradigm.' }];
|
||||
}
|
||||
|
||||
export default function ProxyHostDemo() {
|
||||
useEnsureLoggedIn();
|
||||
const { activeTab } = useLayout();
|
||||
return (
|
||||
<Box>
|
||||
<Heading size="7" mb="1">
|
||||
{activeTab}
|
||||
</Heading>
|
||||
<Text color="gray" mb="4" as="p">
|
||||
This is the {activeTab.toLowerCase()} page demo.
|
||||
</Text>
|
||||
|
||||
<Grid columns={{ initial: '1', sm: '2', lg: '3' }} gap="4">
|
||||
<Card size="2">
|
||||
<Flex direction="column" gap="2">
|
||||
<Text size="2" weight="bold">
|
||||
Status Overview
|
||||
</Text>
|
||||
<Text size="2" color="gray">
|
||||
Everything is running smoothly in your {activeTab.toLowerCase()} section.
|
||||
</Text>
|
||||
<Button variant="surface" size="1" style={{ width: 'fit-content' }} mt="1">
|
||||
View Details
|
||||
</Button>
|
||||
</Flex>
|
||||
</Card>
|
||||
<Card size="2">
|
||||
<Flex direction="column" gap="2">
|
||||
<Text size="2" weight="bold">
|
||||
Recent Activity
|
||||
</Text>
|
||||
<Text size="2" color="gray">
|
||||
No recent changes detected in the last 24 hours.
|
||||
</Text>
|
||||
<Button variant="surface" size="1" style={{ width: 'fit-content' }} mt="1">
|
||||
Refresh
|
||||
</Button>
|
||||
</Flex>
|
||||
</Card>
|
||||
<Card size="2">
|
||||
<Flex direction="column" gap="2">
|
||||
<Text size="2" weight="bold">
|
||||
Quick Actions
|
||||
</Text>
|
||||
<Text size="2" color="gray">
|
||||
Common tasks related to {activeTab.toLowerCase()} are available here.
|
||||
</Text>
|
||||
<Button variant="solid" size="1" style={{ width: 'fit-content' }} mt="1">
|
||||
Get Started
|
||||
</Button>
|
||||
</Flex>
|
||||
</Card>
|
||||
</Grid>
|
||||
|
||||
{activeTab === 'Proxy Hosts' && (
|
||||
<Box mt="6">
|
||||
<Card variant="surface">
|
||||
<TablePlaceholder />
|
||||
</Card>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
161
apps/frontend/app/routes/init.tsx
Normal file
161
apps/frontend/app/routes/init.tsx
Normal file
@@ -0,0 +1,161 @@
|
||||
import { Box, Container, Flex, Heading, Text } from '@radix-ui/themes';
|
||||
import { useMutation, useQuery } from '@tanstack/react-query';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { toast } from 'react-toastify/unstyled';
|
||||
import * as v from 'valibot';
|
||||
import { useResponseErrorHandler } from '../hooks/ResponseHelper';
|
||||
import { useApi } from '../providers/ApiProvider';
|
||||
import { formHook } from '../providers/FormProvider';
|
||||
import { TooltipContentContainer } from '../components/info';
|
||||
import { SearchParamKeys } from '../lib/constants';
|
||||
import { useQueryMessage } from '../hooks/useQueryMessage';
|
||||
import { QueryMessageCode, QueryMessageType } from '../lib/QueryMessages';
|
||||
|
||||
const initFormSchema = v.object({
|
||||
username: v.pipe(v.string(), v.trim(), v.minLength(1, 'Username is required')),
|
||||
password: v.pipe(v.string(), v.minLength(1, 'Password is required')),
|
||||
setup_secret: v.pipe(v.string(), v.minLength(1, 'Setup secret is required')),
|
||||
});
|
||||
|
||||
export default function InitRoute() {
|
||||
const navigate = useNavigate();
|
||||
const { tanstackApiClient } = useApi();
|
||||
const { defaultResponseErrorHandler } = useResponseErrorHandler();
|
||||
const { toSearchParamQueryMessage } = useQueryMessage();
|
||||
|
||||
const { mutateAsync: initAdmin, isPending } = useMutation({
|
||||
...tanstackApiClient.mutation('post', '/api/auth/init_admin').mutationOptions,
|
||||
onSuccess: async () => {
|
||||
const searchParams = new URLSearchParams();
|
||||
searchParams.set(SearchParamKeys.Message, toSearchParamQueryMessage(QueryMessageCode.InitializationSuccessful, QueryMessageType.Success));
|
||||
navigate(`/login?${searchParams.toString()}`);
|
||||
},
|
||||
onError: (error) => {
|
||||
if (defaultResponseErrorHandler(error)) return;
|
||||
console.error('Init failed:', error);
|
||||
},
|
||||
});
|
||||
|
||||
const { queryOptions: healthInfoQuery } = tanstackApiClient.get('/api/health/info');
|
||||
useQuery({
|
||||
...healthInfoQuery,
|
||||
queryFn: async (...args) => {
|
||||
try {
|
||||
const data = await healthInfoQuery.queryFn!(...args);
|
||||
if (data.is_initialized) {
|
||||
navigate('/login', { replace: true });
|
||||
return data;
|
||||
}
|
||||
return data;
|
||||
} catch (error) {
|
||||
if (defaultResponseErrorHandler(error)) return {} as never;
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const form = formHook.useAppForm({
|
||||
defaultValues: { username: '', password: '', setup_secret: '' },
|
||||
validators: { onBlur: initFormSchema, onSubmit: initFormSchema },
|
||||
onSubmit: async ({ value }) => {
|
||||
toast.dismiss();
|
||||
return await initAdmin({ body: { username: value.username, password: value.password, setup_secret: value.setup_secret } });
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<Flex align="center" justify="center" style={{ minHeight: 'calc(100vh - 64px)' }}>
|
||||
<Container size="3" p="0">
|
||||
<Box
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
maxWidth: 480,
|
||||
margin: '40px auto',
|
||||
backgroundColor: 'white',
|
||||
padding: 24,
|
||||
borderRadius: 8,
|
||||
boxShadow: '0 6px 18px rgba(15,23,42,0.06)',
|
||||
}}
|
||||
>
|
||||
<Heading size="6" style={{ marginBottom: 12, alignSelf: 'center' }}>
|
||||
Initialize YANPM
|
||||
</Heading>
|
||||
|
||||
<Heading size="3" style={{ marginBottom: 24, color: 'var(--gray-11)', alignSelf: 'center' }}>
|
||||
Create the initial admin user
|
||||
</Heading>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.handleSubmit();
|
||||
}}
|
||||
>
|
||||
<form.AppField
|
||||
name="username"
|
||||
children={(field) => (
|
||||
<>
|
||||
<field.TextField
|
||||
label="Username"
|
||||
value={field.state.value}
|
||||
autoComplete="username"
|
||||
spellCheck={false}
|
||||
required
|
||||
onChange={(e) => field.handleChange(e.target.value)}
|
||||
/>
|
||||
<field.TextFieldErrorMessage {...field.state.meta} />
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
|
||||
<form.AppField
|
||||
name="password"
|
||||
children={(field) => (
|
||||
<>
|
||||
<field.TextField
|
||||
label="Password"
|
||||
value={field.state.value}
|
||||
type="password"
|
||||
required
|
||||
autoComplete="new-password"
|
||||
onChange={(e) => field.handleChange(e.target.value)}
|
||||
showPasswordToggle
|
||||
/>
|
||||
<field.TextFieldErrorMessage {...field.state.meta} />
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
|
||||
<form.AppField
|
||||
name="setup_secret"
|
||||
children={(field) => (
|
||||
<>
|
||||
<field.TextField
|
||||
label="Setup Secret"
|
||||
value={field.state.value}
|
||||
required
|
||||
onChange={(e) => field.handleChange(e.target.value)}
|
||||
infoIconProps={{
|
||||
children: (
|
||||
<TooltipContentContainer>
|
||||
<Text>This secret is provided when the API server is first started. Refer to your server logs to find it.</Text>
|
||||
</TooltipContentContainer>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
<field.TextFieldErrorMessage {...field.state.meta} />
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div style={{ marginTop: 18, display: 'flex', gap: 8, justifySelf: 'center' }}>
|
||||
<form.SubmitButton loading={isPending} label={{ default: 'Initialize' }} />
|
||||
</div>
|
||||
</form>
|
||||
</Box>
|
||||
</Container>
|
||||
</Flex>
|
||||
</>
|
||||
);
|
||||
}
|
||||
88
apps/frontend/app/routes/layout.tsx
Normal file
88
apps/frontend/app/routes/layout.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
import { Flex, Box, Container, Dialog, Heading, IconButton, TextField } from '@radix-ui/themes';
|
||||
import SidebarContent from '../components/layout/SidebarContent';
|
||||
import { useLayout } from '../providers/LayoutProvider';
|
||||
import { Menu, Search, Bell } from 'lucide-react';
|
||||
import { Outlet } from 'react-router';
|
||||
|
||||
export default function LayoutContainer() {
|
||||
const { activeTab, isMobileMenuOpen, setIsMobileMenuOpen } = useLayout();
|
||||
return (
|
||||
<Flex style={{ minHeight: '100vh', backgroundColor: 'var(--gray-2)' }}>
|
||||
{/* Desktop Sidebar */}
|
||||
<Box
|
||||
display={{ initial: 'none', md: 'block' }}
|
||||
style={{
|
||||
width: '260px',
|
||||
backgroundColor: 'white',
|
||||
borderRight: '1px solid var(--gray-4)',
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
minHeight: '100vh',
|
||||
overflowY: 'auto',
|
||||
}}
|
||||
>
|
||||
<SidebarContent />
|
||||
</Box>
|
||||
|
||||
{/* Main Content Area */}
|
||||
<Box style={{ flex: 1, minWidth: 0 }}>
|
||||
{' '}
|
||||
{/* Top Header (Mobile & Desktop) */}
|
||||
<Flex
|
||||
align="center"
|
||||
justify="between"
|
||||
px="4"
|
||||
style={{
|
||||
height: '64px',
|
||||
backgroundColor: 'white',
|
||||
borderBottom: '1px solid var(--gray-4)',
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 10,
|
||||
}}
|
||||
>
|
||||
<Flex align="center" gap="3">
|
||||
<Box display={{ md: 'none' }}>
|
||||
<Dialog.Root open={isMobileMenuOpen} onOpenChange={setIsMobileMenuOpen}>
|
||||
<Dialog.Trigger>
|
||||
<IconButton variant="ghost" color="gray">
|
||||
<Menu />
|
||||
</IconButton>
|
||||
</Dialog.Trigger>
|
||||
<Dialog.Content
|
||||
style={{
|
||||
position: 'fixed',
|
||||
left: 0,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
margin: 0,
|
||||
width: '280px',
|
||||
borderRadius: 0,
|
||||
padding: 0,
|
||||
}}
|
||||
>
|
||||
<SidebarContent />
|
||||
</Dialog.Content>
|
||||
</Dialog.Root>
|
||||
</Box>
|
||||
<Heading size="4">{activeTab}</Heading>
|
||||
</Flex>
|
||||
|
||||
<Flex align="center" gap="3">
|
||||
<TextField.Root placeholder="Search..." size="2">
|
||||
<TextField.Slot>
|
||||
<Search />
|
||||
</TextField.Slot>
|
||||
</TextField.Root>
|
||||
<IconButton variant="ghost" color="gray">
|
||||
<Bell />
|
||||
</IconButton>
|
||||
</Flex>
|
||||
</Flex>
|
||||
<Container size="4" p="5" style={{ paddingTop: 20 }}>
|
||||
<Outlet />
|
||||
</Container>
|
||||
</Box>
|
||||
</Flex>
|
||||
);
|
||||
}
|
||||
12
apps/frontend/app/vite-env.d.ts
vendored
Normal file
12
apps/frontend/app/vite-env.d.ts
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
interface ViteTypeOptions {
|
||||
// disallow unknown keys.
|
||||
strictImportMetaEnv: unknown;
|
||||
}
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_API_BASE_URL: string | undefined;
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv;
|
||||
}
|
||||
42
apps/frontend/eslint.config.ts
Normal file
42
apps/frontend/eslint.config.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import js from '@eslint/js';
|
||||
import globals from 'globals';
|
||||
import tseslint from 'typescript-eslint';
|
||||
import pluginReact from 'eslint-plugin-react';
|
||||
import pluginReactHooks from 'eslint-plugin-react-hooks';
|
||||
|
||||
export default tseslint.config(
|
||||
{
|
||||
// Ignore files and directories
|
||||
ignores: ['node_modules', 'app/generated', 'build', '.react-router'],
|
||||
},
|
||||
js.configs.recommended,
|
||||
...tseslint.configs.recommended,
|
||||
{
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: {
|
||||
...globals.browser,
|
||||
...globals.node,
|
||||
},
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.json', './tsconfig.node.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
},
|
||||
rules: {},
|
||||
},
|
||||
{
|
||||
...pluginReact.configs.flat.recommended, // Enables core React rules
|
||||
...pluginReactHooks.configs.flat.recommended, // Enables React Hooks rules
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
ecmaFeatures: {
|
||||
jsx: true,
|
||||
},
|
||||
},
|
||||
globals: {
|
||||
...globals.browser,
|
||||
},
|
||||
},
|
||||
}
|
||||
);
|
||||
51
apps/frontend/package.json
Normal file
51
apps/frontend/package.json
Normal file
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "react-router build",
|
||||
"dev": "react-router dev",
|
||||
"start": "react-router-serve ./build/server/index.js",
|
||||
"typecheck": "react-router typegen && tsc",
|
||||
"lint": "eslint .",
|
||||
"test": "echo \"No tests specified\" && exit 0",
|
||||
"generate:openapi": "typed-openapi ../api/swagger.json --tanstack tanstack-client.ts -o ./app/generated/api-client/api-client.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@radix-ui/react-tooltip": "^1.2.8",
|
||||
"@radix-ui/themes": "^3.2.1",
|
||||
"@react-router/node": "^7.9.2",
|
||||
"@react-router/serve": "^7.9.2",
|
||||
"@tanstack/react-form": "^1.27.5",
|
||||
"@tanstack/react-query": "^5.90.12",
|
||||
"axios": "^1.13.2",
|
||||
"globals": "^16.5.0",
|
||||
"isbot": "^5.1.31",
|
||||
"lucide-react": "^0.562.0",
|
||||
"radix-ui": "^1.4.3",
|
||||
"react": "^19.1.1",
|
||||
"react-dom": "^19.1.1",
|
||||
"react-router": "^7.9.2",
|
||||
"react-toastify": "^11.0.5",
|
||||
"valibot": "^1.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.2",
|
||||
"@react-router/dev": "^7.9.2",
|
||||
"@tailwindcss/vite": "^4.1.13",
|
||||
"@types/node": "^22",
|
||||
"@types/react": "^19.1.13",
|
||||
"@types/react-dom": "^19.1.9",
|
||||
"dotenv": "^17.2.3",
|
||||
"eslint": "^9.39.2",
|
||||
"eslint-plugin-react": "^7.37.5",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"tailwindcss": "^4.1.13",
|
||||
"typed-openapi": "^2.2.3",
|
||||
"typescript": "^5.9.2",
|
||||
"typescript-eslint": "^8.50.0",
|
||||
"vite": "^7.1.7",
|
||||
"vite-plugin-eslint": "^1.8.1",
|
||||
"vite-tsconfig-paths": "^5.1.4"
|
||||
}
|
||||
}
|
||||
7021
apps/frontend/pnpm-lock.yaml
generated
Normal file
7021
apps/frontend/pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
BIN
apps/frontend/public/favicon.ico
Normal file
BIN
apps/frontend/public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
5
apps/frontend/react-router.config.ts
Normal file
5
apps/frontend/react-router.config.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import type { Config } from '@react-router/dev/config';
|
||||
|
||||
export default {
|
||||
ssr: false,
|
||||
} satisfies Config;
|
||||
23
apps/frontend/tsconfig.json
Normal file
23
apps/frontend/tsconfig.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"include": ["**/*", "**/.server/**/*", "**/.client/**/*", ".react-router/types/**/*"],
|
||||
"compilerOptions": {
|
||||
"lib": ["DOM", "DOM.Iterable", "ES2022"],
|
||||
"types": ["node", "vite/client"],
|
||||
"target": "ES2022",
|
||||
"module": "ES2022",
|
||||
"moduleResolution": "bundler",
|
||||
"jsx": "react-jsx",
|
||||
"rootDirs": [".", "./.react-router/types"],
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"~/*": ["./app/*"]
|
||||
},
|
||||
"allowImportingTsExtensions": true,
|
||||
"esModuleInterop": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"noEmit": true,
|
||||
"resolveJsonModule": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true
|
||||
}
|
||||
}
|
||||
38
apps/frontend/vite.config.ts
Normal file
38
apps/frontend/vite.config.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { reactRouter } from '@react-router/dev/vite';
|
||||
import tailwindcss from '@tailwindcss/vite';
|
||||
import { defineConfig } from 'vite';
|
||||
import tsconfigPaths from 'vite-tsconfig-paths';
|
||||
// @ts-expect-error vite-plugin-eslint has no types
|
||||
import eslint from 'vite-plugin-eslint';
|
||||
|
||||
export default defineConfig(({ command }) => {
|
||||
const isBuild = command === 'build';
|
||||
|
||||
return {
|
||||
plugins: [
|
||||
tailwindcss(),
|
||||
reactRouter(),
|
||||
tsconfigPaths(),
|
||||
eslint({
|
||||
failOnError: false,
|
||||
}),
|
||||
],
|
||||
resolve: {
|
||||
alias: isBuild
|
||||
? [
|
||||
{
|
||||
// replace unstyled import with styled for SPA build
|
||||
find: 'react-toastify/unstyled',
|
||||
replacement: 'react-toastify',
|
||||
},
|
||||
{
|
||||
// point to the empty CSS file to stub out the import during build, SPA build does not require extra CSS imports
|
||||
find: 'react-toastify/ReactToastify.css',
|
||||
replacement: '~/empty-toastify.css',
|
||||
},
|
||||
]
|
||||
: [],
|
||||
},
|
||||
appType: 'spa',
|
||||
};
|
||||
});
|
||||
87
doc/development.md
Normal file
87
doc/development.md
Normal file
@@ -0,0 +1,87 @@
|
||||
# Development
|
||||
|
||||
## Dependency
|
||||
|
||||
YANPM requires the following dependencies to be installed on your development machine:
|
||||
|
||||
- Node.js (version 20.x or later)
|
||||
- pnpm (version 10.x or later)
|
||||
- Docker (for running backend dependencies like databases)
|
||||
- Rust-toolchain (for building the backend)
|
||||
- Just (for task automation) (optional but recommended)
|
||||
|
||||
## Setting Up the Development Environment
|
||||
|
||||
To set up the development environment for Yet Another Nginx Proxy Manager (YANPM), follow these steps:
|
||||
|
||||
1. **Clone the Repository**:
|
||||
|
||||
```bash
|
||||
git clone <repository-url>
|
||||
cd yet-another-nginx-proxy-manager
|
||||
```
|
||||
|
||||
2. **Install Dependencies**:
|
||||
Use pnpm to install the project dependencies:
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
cargo install sea-orm-cli
|
||||
```
|
||||
|
||||
3. **Set Up Environment Variables**:
|
||||
Create a `.env` file in the root directory and configure the necessary environment variables. You can use the provided `.env.example` as a template.
|
||||
|
||||
## Backend Development
|
||||
|
||||
1. **Run Backend Dependencies**:
|
||||
Use Docker to run any required backend services, such as databases. You can use the provided cli crate for initializing the dependencies:
|
||||
|
||||
```bash
|
||||
just simulate
|
||||
```
|
||||
|
||||
This command will start the necessary services in Docker containers using test-containers.
|
||||
|
||||
2. **Start the API Server**:
|
||||
In a separate terminal, navigate to the `apps/api` directory and start the backend server:
|
||||
|
||||
```bash
|
||||
cd apps/api
|
||||
cargo run
|
||||
```
|
||||
|
||||
## Frontend Development
|
||||
|
||||
If backend API interactions are required, ensure they are running before starting the frontend.
|
||||
|
||||
1. **Set Up Frontend Environment Variables**:
|
||||
Create a `.env` file in the `apps/frontend` directory and configure the necessary environment variables. You can follow the `.env.example` file as a guide.
|
||||
|
||||
2. **Start the Frontend Development Server**:
|
||||
In another terminal, navigate to the `apps/frontend` directory and start the frontend development server:
|
||||
|
||||
```bash
|
||||
cd apps/frontend
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
## Generate Artifacts After Modifications
|
||||
|
||||
After making changes to the below components, you need to regenerate the corresponding artifacts to keep the frontend and backend in sync.
|
||||
|
||||
### Database Entities
|
||||
|
||||
After modifying or adding new database entities, you need to regenerate the entity artifacts to keep the frontend in sync with the backend database schema.
|
||||
|
||||
```bash
|
||||
just generate-entity
|
||||
```
|
||||
|
||||
### Backend API routes
|
||||
|
||||
After modifying or adding new backend API routes, you need to regenerate the API client artifacts to ensure the frontend can interact with the updated backend.
|
||||
|
||||
```bash
|
||||
just generate-openapi
|
||||
```
|
||||
30
justfile
30
justfile
@@ -40,3 +40,33 @@ migrate *args:
|
||||
generate-entity:
|
||||
# delegate to cli
|
||||
just cli db:migrate_and_generate --output-path ../../public/database/src/generated/entities
|
||||
|
||||
generate-openapi:
|
||||
# Generate OpenAPI spec
|
||||
cd apps/api && \
|
||||
cargo run -- generate:openapi --output-path ./swagger.json
|
||||
# Generate API client for frontend
|
||||
cd apps/frontend && \
|
||||
pnpm generate:openapi
|
||||
|
||||
generate-all: generate-entity generate-openapi
|
||||
|
||||
build-frontend:
|
||||
# build frontend assets
|
||||
cd apps/frontend && \
|
||||
pnpm build
|
||||
|
||||
build-backend:
|
||||
# build backend server
|
||||
cd apps/api && \
|
||||
cargo build --release
|
||||
|
||||
build-apps: build-frontend build-backend
|
||||
|
||||
act *args:
|
||||
if [ -n "{{args}}" ]; then \
|
||||
act {{args}} --artifact-server-path /tmp/artifacts; \
|
||||
else \
|
||||
act; \
|
||||
fi
|
||||
|
||||
|
||||
@@ -4,3 +4,4 @@ pub mod prelude;
|
||||
|
||||
pub mod config;
|
||||
pub mod user;
|
||||
pub mod user_identity;
|
||||
|
||||
@@ -2,3 +2,4 @@
|
||||
|
||||
pub use super::config::Entity as Config;
|
||||
pub use super::user::Entity as User;
|
||||
pub use super::user_identity::Entity as UserIdentity;
|
||||
|
||||
29
public/database/src/generated/entities/session.rs
Normal file
29
public/database/src/generated/entities/session.rs
Normal file
@@ -0,0 +1,29 @@
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0.0-rc.18
|
||||
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[sea_orm::model]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "session")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub id: Uuid,
|
||||
pub user_id: Uuid,
|
||||
#[sea_orm(unique)]
|
||||
pub refresh_token_hash: Option<String>,
|
||||
pub expires_at: DateTimeUtc,
|
||||
pub revoked_at: Option<DateTimeUtc>,
|
||||
pub created_at: DateTimeUtc,
|
||||
pub updated_at: DateTimeUtc,
|
||||
#[sea_orm(
|
||||
belongs_to,
|
||||
from = "user_id",
|
||||
to = "id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
pub user: HasOne<super::user::Entity>,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
@@ -12,10 +12,13 @@ pub struct Model {
|
||||
#[sea_orm(unique)]
|
||||
pub name: String,
|
||||
pub is_admin: bool,
|
||||
pub password_hash: String,
|
||||
pub salt: String,
|
||||
pub is_active: bool,
|
||||
pub created_at: DateTimeUtc,
|
||||
pub updated_at: DateTimeUtc,
|
||||
pub last_login_at: Option<DateTimeUtc>,
|
||||
pub deleted_at: Option<DateTimeUtc>,
|
||||
#[sea_orm(has_many)]
|
||||
pub user_identities: HasMany<super::user_identity::Entity>,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
35
public/database/src/generated/entities/user_identity.rs
Normal file
35
public/database/src/generated/entities/user_identity.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0.0-rc.18
|
||||
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[sea_orm::model]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "user_identity")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub id: Uuid,
|
||||
#[sea_orm(unique_key = "provider")]
|
||||
pub user_id: Uuid,
|
||||
#[sea_orm(unique_key = "provider")]
|
||||
pub provider: String,
|
||||
pub email: Option<String>,
|
||||
pub password_hash: Option<String>,
|
||||
pub is_revoked: bool,
|
||||
#[sea_orm(column_type = "JsonBinary", nullable)]
|
||||
pub metadata: Option<Json>,
|
||||
pub password_changed_at: Option<DateTimeUtc>,
|
||||
pub revoked_at: Option<DateTimeUtc>,
|
||||
pub created_at: DateTimeUtc,
|
||||
pub updated_at: DateTimeUtc,
|
||||
#[sea_orm(
|
||||
belongs_to,
|
||||
from = "user_id",
|
||||
to = "id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
pub user: HasOne<super::user::Entity>,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
@@ -10,8 +10,9 @@ pub struct Migrator;
|
||||
impl MigratorTrait for Migrator {
|
||||
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
|
||||
vec![
|
||||
Box::new(m20251011_000001_create_user_table::Migration),
|
||||
Box::new(m20251011_000002_create_config_table::Migration),
|
||||
Box::new(m20251011_000001_create_config_table::Migration),
|
||||
Box::new(m20251011_000002_create_user_table::Migration),
|
||||
Box::new(m20251011_000003_create_user_identity_table::Migration),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
pub mod m20251011_000001_create_user_table;
|
||||
pub mod m20251011_000002_create_config_table;
|
||||
pub mod m20251011_000001_create_config_table;
|
||||
pub mod m20251011_000002_create_user_table;
|
||||
pub mod m20251011_000003_create_user_identity_table;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user