Compare commits
33 Commits
4907055f3a
...
main
Author | SHA1 | Date | |
---|---|---|---|
9c331f7757
|
|||
923a42ada6
|
|||
e5aace6e68
|
|||
0b8d6e2cc2
|
|||
10297f9114
|
|||
972f744e73
|
|||
ea0a5a3ee2
|
|||
0924e3c3fa
|
|||
9eb92ffff1
|
|||
6395df6cec
|
|||
69259667bd
|
|||
349c1a24a4
|
|||
701d430742
|
|||
1e2247abe2
|
|||
8b7d2ad3f7
|
|||
fa843620ee
|
|||
8758491938
|
|||
06344541ae
|
|||
29bfa8c60e
|
|||
31aa9dc066
|
|||
07493b83a5
|
|||
cf379a1288
|
|||
f7b7ebbb1c
|
|||
35527cbeb7
|
|||
36c785e8f2
|
|||
30bf08986d
|
|||
6322736baf
|
|||
55395d279e
|
|||
d20d31d5f8 | |||
26f5195069 | |||
9cf9e5752f | |||
169e89cefb | |||
fe219d51e1 |
49
devenv.lock
49
devenv.lock
@@ -31,10 +31,31 @@
|
|||||||
"type": "github"
|
"type": "github"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"git-hooks": {
|
||||||
|
"inputs": {
|
||||||
|
"flake-compat": "flake-compat",
|
||||||
|
"gitignore": "gitignore",
|
||||||
|
"nixpkgs": [
|
||||||
|
"nixpkgs"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1737465171,
|
||||||
|
"owner": "cachix",
|
||||||
|
"repo": "git-hooks.nix",
|
||||||
|
"rev": "9364dc02281ce2d37a1f55b6e51f7c0f65a75f17",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "cachix",
|
||||||
|
"repo": "git-hooks.nix",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
"gitignore": {
|
"gitignore": {
|
||||||
"inputs": {
|
"inputs": {
|
||||||
"nixpkgs": [
|
"nixpkgs": [
|
||||||
"pre-commit-hooks",
|
"git-hooks",
|
||||||
"nixpkgs"
|
"nixpkgs"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -66,32 +87,14 @@
|
|||||||
"type": "github"
|
"type": "github"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"pre-commit-hooks": {
|
|
||||||
"inputs": {
|
|
||||||
"flake-compat": "flake-compat",
|
|
||||||
"gitignore": "gitignore",
|
|
||||||
"nixpkgs": [
|
|
||||||
"nixpkgs"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"locked": {
|
|
||||||
"lastModified": 1735882644,
|
|
||||||
"owner": "cachix",
|
|
||||||
"repo": "pre-commit-hooks.nix",
|
|
||||||
"rev": "a5a961387e75ae44cc20f0a57ae463da5e959656",
|
|
||||||
"type": "github"
|
|
||||||
},
|
|
||||||
"original": {
|
|
||||||
"owner": "cachix",
|
|
||||||
"repo": "pre-commit-hooks.nix",
|
|
||||||
"type": "github"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"root": {
|
"root": {
|
||||||
"inputs": {
|
"inputs": {
|
||||||
"devenv": "devenv",
|
"devenv": "devenv",
|
||||||
|
"git-hooks": "git-hooks",
|
||||||
"nixpkgs": "nixpkgs",
|
"nixpkgs": "nixpkgs",
|
||||||
"pre-commit-hooks": "pre-commit-hooks"
|
"pre-commit-hooks": [
|
||||||
|
"git-hooks"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
@@ -1,2 +0,0 @@
|
|||||||
DATABASE_URL="postgres://wrbapp:password@localhost/wrbapp"
|
|
||||||
API_TOKEN="SuperSecretToken"
|
|
2
server/.gitignore
vendored
2
server/.gitignore
vendored
@@ -1,2 +1,2 @@
|
|||||||
target
|
target/
|
||||||
.env
|
.env
|
||||||
|
222
server/Cargo.lock
generated
222
server/Cargo.lock
generated
@@ -47,6 +47,68 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstream"
|
||||||
|
version = "0.6.18"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8acc5369981196006228e28809f761875c0327210a891e941f4c683b3a99529b"
|
||||||
|
dependencies = [
|
||||||
|
"anstyle",
|
||||||
|
"anstyle-parse",
|
||||||
|
"anstyle-query",
|
||||||
|
"anstyle-wincon",
|
||||||
|
"colorchoice",
|
||||||
|
"is_terminal_polyfill",
|
||||||
|
"utf8parse",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstyle"
|
||||||
|
version = "1.0.10"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstyle-parse"
|
||||||
|
version = "0.2.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3b2d16507662817a6a20a9ea92df6652ee4f94f914589377d69f3b21bc5798a9"
|
||||||
|
dependencies = [
|
||||||
|
"utf8parse",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstyle-query"
|
||||||
|
version = "1.1.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "79947af37f4177cfead1110013d678905c37501914fba0efea834c3fe9a8d60c"
|
||||||
|
dependencies = [
|
||||||
|
"windows-sys 0.59.0",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstyle-wincon"
|
||||||
|
version = "3.0.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ca3534e77181a9cc07539ad51f2141fe32f6c3ffd4df76db8ad92346b003ae4e"
|
||||||
|
dependencies = [
|
||||||
|
"anstyle",
|
||||||
|
"once_cell",
|
||||||
|
"windows-sys 0.59.0",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[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]]
|
[[package]]
|
||||||
name = "atoi"
|
name = "atoi"
|
||||||
version = "2.0.0"
|
version = "2.0.0"
|
||||||
@@ -126,6 +188,7 @@ dependencies = [
|
|||||||
"axum",
|
"axum",
|
||||||
"axum-core",
|
"axum-core",
|
||||||
"bytes",
|
"bytes",
|
||||||
|
"cookie",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
"headers",
|
"headers",
|
||||||
"http",
|
"http",
|
||||||
@@ -192,6 +255,15 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "blake2"
|
||||||
|
version = "0.10.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
|
||||||
|
dependencies = [
|
||||||
|
"digest",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "block-buffer"
|
name = "block-buffer"
|
||||||
version = "0.10.4"
|
version = "0.10.4"
|
||||||
@@ -244,10 +316,57 @@ dependencies = [
|
|||||||
"iana-time-zone",
|
"iana-time-zone",
|
||||||
"js-sys",
|
"js-sys",
|
||||||
"num-traits",
|
"num-traits",
|
||||||
|
"serde",
|
||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
"windows-targets 0.52.6",
|
"windows-targets 0.52.6",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "clap"
|
||||||
|
version = "4.5.31"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "027bb0d98429ae334a8698531da7077bdf906419543a35a55c2cb1b66437d767"
|
||||||
|
dependencies = [
|
||||||
|
"clap_builder",
|
||||||
|
"clap_derive",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "clap_builder"
|
||||||
|
version = "4.5.31"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5589e0cba072e0f3d23791efac0fd8627b49c829c196a492e88168e6a669d863"
|
||||||
|
dependencies = [
|
||||||
|
"anstream",
|
||||||
|
"anstyle",
|
||||||
|
"clap_lex",
|
||||||
|
"strsim",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "clap_derive"
|
||||||
|
version = "4.5.28"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "bf4ced95c6f4a675af3da73304b9ac4ed991640c36374e4b46795c49e17cf1ed"
|
||||||
|
dependencies = [
|
||||||
|
"heck",
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "clap_lex"
|
||||||
|
version = "0.7.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "colorchoice"
|
||||||
|
version = "1.0.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "concurrent-queue"
|
name = "concurrent-queue"
|
||||||
version = "2.5.0"
|
version = "2.5.0"
|
||||||
@@ -263,6 +382,17 @@ version = "0.9.6"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
|
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
|
||||||
|
|
||||||
|
[[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]]
|
[[package]]
|
||||||
name = "core-foundation-sys"
|
name = "core-foundation-sys"
|
||||||
version = "0.8.7"
|
version = "0.8.7"
|
||||||
@@ -385,6 +515,15 @@ dependencies = [
|
|||||||
"zeroize",
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "deranged"
|
||||||
|
version = "0.3.11"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4"
|
||||||
|
dependencies = [
|
||||||
|
"powerfmt",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "digest"
|
name = "digest"
|
||||||
version = "0.10.7"
|
version = "0.10.7"
|
||||||
@@ -952,6 +1091,12 @@ dependencies = [
|
|||||||
"hashbrown",
|
"hashbrown",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "is_terminal_polyfill"
|
||||||
|
version = "1.70.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "itertools"
|
name = "itertools"
|
||||||
version = "0.14.0"
|
version = "0.14.0"
|
||||||
@@ -1111,6 +1256,12 @@ dependencies = [
|
|||||||
"zeroize",
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "num-conv"
|
||||||
|
version = "0.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "num-integer"
|
name = "num-integer"
|
||||||
version = "0.1.46"
|
version = "0.1.46"
|
||||||
@@ -1191,6 +1342,17 @@ dependencies = [
|
|||||||
"windows-targets 0.52.6",
|
"windows-targets 0.52.6",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[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]]
|
[[package]]
|
||||||
name = "pem-rfc7468"
|
name = "pem-rfc7468"
|
||||||
version = "0.7.0"
|
version = "0.7.0"
|
||||||
@@ -1245,6 +1407,12 @@ version = "0.3.31"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2"
|
checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "powerfmt"
|
||||||
|
version = "0.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ppv-lite86"
|
name = "ppv-lite86"
|
||||||
version = "0.2.20"
|
version = "0.2.20"
|
||||||
@@ -1618,6 +1786,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "6a007b6936676aa9ab40207cde35daab0a04b823be8ae004368c0793b96a61e0"
|
checksum = "6a007b6936676aa9ab40207cde35daab0a04b823be8ae004368c0793b96a61e0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bytes",
|
"bytes",
|
||||||
|
"chrono",
|
||||||
"crc",
|
"crc",
|
||||||
"crossbeam-queue",
|
"crossbeam-queue",
|
||||||
"either",
|
"either",
|
||||||
@@ -1642,6 +1811,7 @@ dependencies = [
|
|||||||
"tokio-stream",
|
"tokio-stream",
|
||||||
"tracing",
|
"tracing",
|
||||||
"url",
|
"url",
|
||||||
|
"uuid",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1694,6 +1864,7 @@ dependencies = [
|
|||||||
"bitflags",
|
"bitflags",
|
||||||
"byteorder",
|
"byteorder",
|
||||||
"bytes",
|
"bytes",
|
||||||
|
"chrono",
|
||||||
"crc",
|
"crc",
|
||||||
"digest",
|
"digest",
|
||||||
"dotenvy",
|
"dotenvy",
|
||||||
@@ -1722,6 +1893,7 @@ dependencies = [
|
|||||||
"stringprep",
|
"stringprep",
|
||||||
"thiserror",
|
"thiserror",
|
||||||
"tracing",
|
"tracing",
|
||||||
|
"uuid",
|
||||||
"whoami",
|
"whoami",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -1735,6 +1907,7 @@ dependencies = [
|
|||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
"bitflags",
|
"bitflags",
|
||||||
"byteorder",
|
"byteorder",
|
||||||
|
"chrono",
|
||||||
"crc",
|
"crc",
|
||||||
"dotenvy",
|
"dotenvy",
|
||||||
"etcetera",
|
"etcetera",
|
||||||
@@ -1759,6 +1932,7 @@ dependencies = [
|
|||||||
"stringprep",
|
"stringprep",
|
||||||
"thiserror",
|
"thiserror",
|
||||||
"tracing",
|
"tracing",
|
||||||
|
"uuid",
|
||||||
"whoami",
|
"whoami",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -1769,6 +1943,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "f85ca71d3a5b24e64e1d08dd8fe36c6c95c339a896cc33068148906784620540"
|
checksum = "f85ca71d3a5b24e64e1d08dd8fe36c6c95c339a896cc33068148906784620540"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"atoi",
|
"atoi",
|
||||||
|
"chrono",
|
||||||
"flume",
|
"flume",
|
||||||
"futures-channel",
|
"futures-channel",
|
||||||
"futures-core",
|
"futures-core",
|
||||||
@@ -1783,6 +1958,7 @@ dependencies = [
|
|||||||
"sqlx-core",
|
"sqlx-core",
|
||||||
"tracing",
|
"tracing",
|
||||||
"url",
|
"url",
|
||||||
|
"uuid",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1886,6 +2062,37 @@ dependencies = [
|
|||||||
"once_cell",
|
"once_cell",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "time"
|
||||||
|
version = "0.3.37"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "35e7868883861bd0e56d9ac6efcaaca0d6d5d82a2a7ec8209ff492c07cf37b21"
|
||||||
|
dependencies = [
|
||||||
|
"deranged",
|
||||||
|
"itoa",
|
||||||
|
"num-conv",
|
||||||
|
"powerfmt",
|
||||||
|
"serde",
|
||||||
|
"time-core",
|
||||||
|
"time-macros",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "time-core"
|
||||||
|
version = "0.1.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "time-macros"
|
||||||
|
version = "0.2.19"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2834e6017e3e5e4b9834939793b282bc03b37a3336245fa820e35e233e2a85de"
|
||||||
|
dependencies = [
|
||||||
|
"num-conv",
|
||||||
|
"time-core",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tinystr"
|
name = "tinystr"
|
||||||
version = "0.7.6"
|
version = "0.7.6"
|
||||||
@@ -2091,11 +2298,22 @@ version = "1.0.4"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "utf8parse"
|
||||||
|
version = "0.2.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "uuid"
|
name = "uuid"
|
||||||
version = "1.12.0"
|
version = "1.12.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "744018581f9a3454a9e15beb8a33b017183f1e7c0cd170232a2d1453b23a51c4"
|
checksum = "744018581f9a3454a9e15beb8a33b017183f1e7c0cd170232a2d1453b23a51c4"
|
||||||
|
dependencies = [
|
||||||
|
"getrandom 0.2.15",
|
||||||
|
"rand 0.8.5",
|
||||||
|
"serde",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "validator"
|
name = "validator"
|
||||||
@@ -2426,13 +2644,17 @@ dependencies = [
|
|||||||
name = "wrbapp_server"
|
name = "wrbapp_server"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"argon2",
|
||||||
"axum",
|
"axum",
|
||||||
"axum-extra",
|
"axum-extra",
|
||||||
|
"bitflags",
|
||||||
"chrono",
|
"chrono",
|
||||||
|
"clap",
|
||||||
"csv",
|
"csv",
|
||||||
"dotenvy",
|
"dotenvy",
|
||||||
"itertools",
|
"itertools",
|
||||||
"rand 0.9.0",
|
"rand 0.9.0",
|
||||||
|
"rand_chacha 0.9.0",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sqlx",
|
"sqlx",
|
||||||
|
@@ -6,24 +6,28 @@ edition = "2021"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
# Primary crates
|
# Primary crates
|
||||||
axum = { version = "0.8", features = [ "macros", "json" ] }
|
axum = { version = "0.8", features = [ "macros", "json" ] }
|
||||||
axum-extra = { version = "0.10.0", features = [ "typed-header" ] }
|
axum-extra = { version = "0.10.0", features = [ "typed-header", "cookie" ] }
|
||||||
tokio = { version = "1.43", features = [ "rt-multi-thread", "macros" ] }
|
tokio = { version = "1.43", features = [ "rt-multi-thread", "macros" ] }
|
||||||
sqlx = { version = "0.8", features = [ "runtime-tokio", "postgres" ] }
|
sqlx = { version = "0.8", features = [ "runtime-tokio", "postgres", "uuid", "chrono" ] }
|
||||||
|
|
||||||
# Secondary crates
|
# Secondary crates
|
||||||
csv = { version = "1.3" }
|
csv = { version = "1.3" }
|
||||||
serde = "1.0"
|
serde = "1.0"
|
||||||
dotenvy = "0.15.7"
|
dotenvy = "0.15.7"
|
||||||
validator = { version = "0.19.0", features = [ "derive" ] }
|
validator = { version = "0.19.0", features = [ "derive" ] }
|
||||||
|
argon2 = "0.5"
|
||||||
|
bitflags = { version = "2.8", features = [ "serde" ] }
|
||||||
|
clap = { version = "4.5.31", features = ["derive"] }
|
||||||
|
|
||||||
|
|
||||||
# Tertiary crates
|
# Tertiary crates
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
tracing-subscriber = "0.3"
|
tracing-subscriber = "0.3"
|
||||||
chrono = "0.4.39"
|
chrono = { version = "0.4", features = ["serde"] }
|
||||||
uuid = "1.12.0"
|
uuid = { version = "1.12", features = ["v4", "fast-rng", "serde"] }
|
||||||
serde_json = "1.0.137"
|
serde_json = "1.0.137"
|
||||||
rand = "0.9"
|
rand = "0.9"
|
||||||
|
rand_chacha = "0.9"
|
||||||
thiserror = { version = "2.0" }
|
thiserror = { version = "2.0" }
|
||||||
itertools = "0.14"
|
itertools = "0.14"
|
||||||
|
|
||||||
|
@@ -1,10 +1,10 @@
|
|||||||
create table "members" (
|
CREATE TABLE IF NOT EXISTS "members" (
|
||||||
id varchar(7) primary key,
|
member_id varchar(7) NOT NULL PRIMARY KEY,
|
||||||
first_name text not null,
|
first_name text NOT NULL,
|
||||||
full_name text not null,
|
full_name text NOT NULL,
|
||||||
registration_token text unique not null,
|
registration_token text NOT NULL UNIQUE,
|
||||||
diploma text,
|
diploma text,
|
||||||
hours text[] not null,
|
groups bigint NOT NULL,
|
||||||
groups text[] not null
|
roles bigint NOT NULL
|
||||||
);
|
);
|
||||||
|
|
||||||
|
13
server/migrations/002_create_users.sql
Normal file
13
server/migrations/002_create_users.sql
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS "users" (
|
||||||
|
user_id uuid NOT NULL PRIMARY KEY,
|
||||||
|
email text NOT NULL UNIQUE,
|
||||||
|
password text NOT NULL,
|
||||||
|
admin boolean NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS users_members (
|
||||||
|
user_id uuid NOT NULL REFERENCES users (user_id) ON UPDATE cascade ON DELETE cascade,
|
||||||
|
member_id varchar(7) NOT NULL REFERENCES members (member_id) ON UPDATE cascade ON DELETE cascade,
|
||||||
|
|
||||||
|
CONSTRAINT users_members_pkey PRIMARY KEY (user_id, member_id)
|
||||||
|
);
|
7
server/migrations/003_create_sessions.sql
Normal file
7
server/migrations/003_create_sessions.sql
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS "sessions" (
|
||||||
|
session_id uuid NOT NULL PRIMARY KEY,
|
||||||
|
user_id uuid NOT NULL REFERENCES users (user_id) ON UPDATE cascade ON DELETE cascade,
|
||||||
|
token text NOT NULL UNIQUE,
|
||||||
|
expires_at timestamptz NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL
|
||||||
|
);
|
2
server/migrations/004_unique_users_members.sql
Normal file
2
server/migrations/004_unique_users_members.sql
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
ALTER TABLE users_members
|
||||||
|
ADD UNIQUE (user_id, member_id);
|
20
server/migrations/005_create_news.sql
Normal file
20
server/migrations/005_create_news.sql
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
CREATE TYPE message_status AS ENUM ('pending', 'sent', 'canceled');
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS messages (
|
||||||
|
message_id uuid NOT NULL PRIMARY KEY,
|
||||||
|
created_at timestamptz NOT NULL,
|
||||||
|
scheduled_at timestamptz,
|
||||||
|
status message_status NOT NULL,
|
||||||
|
title text NOT NULL,
|
||||||
|
content text NOT NULL,
|
||||||
|
channel bigint NOT NULL,
|
||||||
|
thumbnail_url text
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS messages_users (
|
||||||
|
message_id uuid NOT NULL REFERENCES users (user_id) ON UPDATE cascade ON DELETE cascade,
|
||||||
|
user_id uuid NOT NULL REFERENCES users (user_id) ON UPDATE cascade ON DELETE cascade,
|
||||||
|
is_read boolean NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT messages_users_pkey PRIMARY KEY (message_id, user_id)
|
||||||
|
);
|
3
server/migrations/006_alter_messages.sql
Normal file
3
server/migrations/006_alter_messages.sql
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
ALTER TABLE messages
|
||||||
|
ADD COLUMN member_groups bigint NOT NULL,
|
||||||
|
ADD COLUMN member_roles bigint NOT NULL;
|
1
server/migrations/007_alter_messages.sql
Normal file
1
server/migrations/007_alter_messages.sql
Normal file
@@ -0,0 +1 @@
|
|||||||
|
ALTER TYPE message_status ADD VALUE 'draft';
|
@@ -1,48 +1,85 @@
|
|||||||
use std::collections::HashSet;
|
use argon2::{
|
||||||
|
password_hash::{rand_core::OsRng, PasswordHasher, SaltString},
|
||||||
use axum::{extract::FromRequestParts, http::request::Parts, RequestPartsExt};
|
Argon2, PasswordHash, PasswordVerifier,
|
||||||
use axum_extra::{
|
|
||||||
headers::{authorization::Bearer, Authorization},
|
|
||||||
typed_header::TypedHeaderRejectionReason,
|
|
||||||
TypedHeader,
|
|
||||||
};
|
};
|
||||||
use bearer::verify_bearer;
|
use axum::http::{header, HeaderMap};
|
||||||
|
use chrono::Utc;
|
||||||
pub use error::AuthError;
|
pub use error::AuthError;
|
||||||
|
use rand::distr::Alphanumeric;
|
||||||
|
use rand::prelude::*;
|
||||||
|
use rand_chacha::ChaCha20Rng;
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use tokio::task;
|
||||||
|
|
||||||
|
use crate::{database::model::Session, model::User};
|
||||||
|
|
||||||
mod bearer;
|
|
||||||
mod error;
|
mod error;
|
||||||
|
|
||||||
#[derive(Debug)]
|
pub async fn get_user_from_header(pool: &PgPool, headers: &HeaderMap) -> Result<User, AuthError> {
|
||||||
pub struct Permissions<'a>(pub HashSet<&'a str>);
|
let token = get_token_from_headers(headers)?;
|
||||||
|
|
||||||
// Middleware for getting permissions
|
let session = match Session::from_token(pool, &token).await {
|
||||||
impl<S> FromRequestParts<S> for Permissions<'_>
|
Ok(s) => s,
|
||||||
where
|
Err(_) => return Err(AuthError::InvalidToken),
|
||||||
S: Send + Sync,
|
|
||||||
{
|
|
||||||
type Rejection = crate::Error;
|
|
||||||
|
|
||||||
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
|
|
||||||
// First check if the request has a beaerer token to authenticate
|
|
||||||
match parts.extract::<TypedHeader<Authorization<Bearer>>>().await {
|
|
||||||
Ok(bearer) => {
|
|
||||||
verify_bearer(bearer.token().to_string()).map_err(|_| AuthError::InvalidToken)?;
|
|
||||||
|
|
||||||
let permissions = Permissions {
|
|
||||||
0: HashSet::from(["root"]),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return Ok(permissions);
|
if session.expires_at < Utc::now() {
|
||||||
|
return Err(AuthError::InvalidToken);
|
||||||
}
|
}
|
||||||
Err(err) => match err.reason() {
|
|
||||||
TypedHeaderRejectionReason::Missing => (),
|
let db_user = match crate::database::model::User::get(pool, session.user_id).await {
|
||||||
TypedHeaderRejectionReason::Error(_err) => {
|
Ok(u) => u,
|
||||||
return Err(AuthError::InvalidToken.into())
|
Err(_) => return Err(AuthError::InvalidToken),
|
||||||
}
|
|
||||||
_ => return Err(AuthError::Unexpected.into()),
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
Err(AuthError::Unexpected.into())
|
Ok(db_user.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_token_from_headers(headers: &HeaderMap) -> Result<String, AuthError> {
|
||||||
|
let bearer = headers.get(header::AUTHORIZATION);
|
||||||
|
let bearer = bearer
|
||||||
|
.ok_or(AuthError::InvalidToken)?
|
||||||
|
.to_str()
|
||||||
|
.map_err(|_| AuthError::InvalidToken)?;
|
||||||
|
|
||||||
|
match bearer.strip_prefix("Bearer ") {
|
||||||
|
Some(token) => Ok(token.to_string()),
|
||||||
|
None => Err(AuthError::InvalidToken),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn generate_password_hash(password: String) -> Result<String, AuthError> {
|
||||||
|
let password_hash: Result<String, argon2::password_hash::Error> =
|
||||||
|
task::spawn_blocking(move || {
|
||||||
|
let salt = SaltString::generate(&mut OsRng);
|
||||||
|
|
||||||
|
let argon2 = Argon2::default();
|
||||||
|
|
||||||
|
let password_hash = argon2
|
||||||
|
.hash_password(password.as_bytes(), &salt)?
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
Ok(password_hash)
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
password_hash.map_err(|e| e.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn verify_password_hash(password: &str, hash: &str) -> Result<(), AuthError> {
|
||||||
|
let parsed_hash = PasswordHash::new(hash)?;
|
||||||
|
Argon2::default()
|
||||||
|
.verify_password(password.as_bytes(), &parsed_hash)
|
||||||
|
.map_err(|_| AuthError::InvalidPassword)?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn generate_session_token() -> String {
|
||||||
|
ChaCha20Rng::from_os_rng()
|
||||||
|
.sample_iter(&Alphanumeric)
|
||||||
|
.take(60)
|
||||||
|
.map(char::from)
|
||||||
|
.collect::<String>()
|
||||||
|
}
|
||||||
|
@@ -1,8 +0,0 @@
|
|||||||
pub fn verify_bearer(token: String) -> Result<(), ()> {
|
|
||||||
let env_api_token = dotenvy::var("API_TOKEN").map_err(|_| ())?;
|
|
||||||
|
|
||||||
match env_api_token == token {
|
|
||||||
true => Ok(()),
|
|
||||||
false => Err(()),
|
|
||||||
}
|
|
||||||
}
|
|
@@ -5,16 +5,28 @@ pub enum AuthError {
|
|||||||
NoPermssions,
|
NoPermssions,
|
||||||
InvalidToken,
|
InvalidToken,
|
||||||
Unexpected,
|
Unexpected,
|
||||||
|
InvalidPassword,
|
||||||
|
Unauthorized,
|
||||||
|
HashingFailed(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for AuthError {
|
impl Display for AuthError {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
Self::NoPermssions => write!(f, "{}", "No permissions"),
|
Self::NoPermssions => write!(f, "No permissions"),
|
||||||
Self::InvalidToken => write!(f, "{}", "Invalid token"),
|
Self::InvalidToken => write!(f, "Invalid token"),
|
||||||
Self::Unexpected => write!(f, "{}", "Unexpected error"),
|
Self::Unexpected => write!(f, "Unexpected error"),
|
||||||
|
Self::InvalidPassword => write!(f, "Password is incorrect"),
|
||||||
|
Self::Unauthorized => write!(f, "Authentication is required"),
|
||||||
|
Self::HashingFailed(msg) => write!(f, "Password hashing failed: {}", msg),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::error::Error for AuthError {}
|
impl std::error::Error for AuthError {}
|
||||||
|
|
||||||
|
impl From<argon2::password_hash::Error> for AuthError {
|
||||||
|
fn from(value: argon2::password_hash::Error) -> Self {
|
||||||
|
AuthError::HashingFailed(value.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@@ -1,5 +1,10 @@
|
|||||||
pub mod member;
|
pub mod member;
|
||||||
|
pub mod message;
|
||||||
pub mod session;
|
pub mod session;
|
||||||
pub mod user;
|
pub mod user;
|
||||||
|
|
||||||
pub use member::Member;
|
pub use member::Member;
|
||||||
|
pub use message::Message;
|
||||||
|
pub use session::Session;
|
||||||
|
pub use user::User;
|
||||||
|
pub use user::UserMember;
|
||||||
|
@@ -2,21 +2,34 @@ use rand::distr::{Alphanumeric, SampleString};
|
|||||||
use sqlx::{PgPool, Postgres, QueryBuilder};
|
use sqlx::{PgPool, Postgres, QueryBuilder};
|
||||||
use validator::Validate;
|
use validator::Validate;
|
||||||
|
|
||||||
#[derive(Debug, Validate)]
|
use crate::model::member::{Groups, Roles};
|
||||||
|
|
||||||
|
#[derive(Debug, Validate, sqlx::FromRow)]
|
||||||
pub struct Member {
|
pub struct Member {
|
||||||
#[validate(length(equal = 7))]
|
#[validate(length(equal = 7))]
|
||||||
pub id: String,
|
pub member_id: String,
|
||||||
pub first_name: String,
|
pub first_name: String,
|
||||||
pub full_name: String,
|
pub full_name: String,
|
||||||
pub registration_token: Option<String>,
|
pub registration_token: Option<String>,
|
||||||
pub diploma: Option<String>,
|
pub diploma: Option<String>,
|
||||||
pub hours: Vec<String>,
|
pub groups: Groups,
|
||||||
pub groups: Vec<String>,
|
pub roles: Roles,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Member {
|
impl Member {
|
||||||
pub async fn get_many(transaction: &PgPool, members: Vec<Self>) -> Result<(), sqlx::Error> {
|
pub async fn get_many_from_registration_tokens(
|
||||||
Ok(())
|
pool: &PgPool,
|
||||||
|
registration_tokens: Vec<String>,
|
||||||
|
) -> Result<Vec<Self>, sqlx::Error> {
|
||||||
|
let members = sqlx::query_as!(
|
||||||
|
Member,
|
||||||
|
"SELECT * FROM members WHERE registration_token = ANY($1);",
|
||||||
|
®istration_tokens
|
||||||
|
)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(members)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_all(pool: &PgPool) -> Result<Vec<Self>, sqlx::Error> {
|
pub async fn get_all(pool: &PgPool) -> Result<Vec<Self>, sqlx::Error> {
|
||||||
@@ -31,24 +44,24 @@ impl Member {
|
|||||||
transaction: &mut sqlx::Transaction<'_, Postgres>,
|
transaction: &mut sqlx::Transaction<'_, Postgres>,
|
||||||
members: Vec<Self>,
|
members: Vec<Self>,
|
||||||
) -> Result<(), sqlx::Error> {
|
) -> Result<(), sqlx::Error> {
|
||||||
if members.len() == 0 {
|
if members.is_empty() {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut query_builder = QueryBuilder::new(
|
let mut query_builder = QueryBuilder::new(
|
||||||
"INSERT INTO members(id, first_name, full_name, registration_token, diploma, hours, groups) "
|
"INSERT INTO members(member_id, first_name, full_name, registration_token, diploma, groups, roles) "
|
||||||
);
|
);
|
||||||
|
|
||||||
query_builder.push_values(members.into_iter(), |mut b, member| {
|
query_builder.push_values(members.into_iter(), |mut b, member| {
|
||||||
let registration_token = Alphanumeric.sample_string(&mut rand::rng(), 16);
|
let registration_token = Alphanumeric.sample_string(&mut rand::rng(), 16);
|
||||||
|
|
||||||
b.push_bind(member.id);
|
b.push_bind(member.member_id);
|
||||||
b.push_bind(member.first_name);
|
b.push_bind(member.first_name);
|
||||||
b.push_bind(member.full_name);
|
b.push_bind(member.full_name);
|
||||||
b.push_bind(registration_token);
|
b.push_bind(registration_token);
|
||||||
b.push_bind(member.diploma);
|
b.push_bind(member.diploma);
|
||||||
b.push_bind(member.hours);
|
b.push_bind(member.groups.bits() as i64);
|
||||||
b.push_bind(member.groups);
|
b.push_bind(member.roles.bits() as i64);
|
||||||
});
|
});
|
||||||
|
|
||||||
let query = query_builder.build();
|
let query = query_builder.build();
|
||||||
@@ -61,12 +74,26 @@ impl Member {
|
|||||||
transaction: &mut sqlx::Transaction<'_, Postgres>,
|
transaction: &mut sqlx::Transaction<'_, Postgres>,
|
||||||
members: Vec<Self>,
|
members: Vec<Self>,
|
||||||
) -> Result<(), sqlx::Error> {
|
) -> Result<(), sqlx::Error> {
|
||||||
if members.len() == 0 {
|
if members.is_empty() {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
for member in members {
|
for member in members {
|
||||||
sqlx::query!("UPDATE ONLY members SET first_name = $1, full_name = $2, diploma = $3, hours = $4, groups = $5 WHERE id = $6", member.first_name, member.full_name, member.diploma, &member.hours, &member.groups, member.id).execute(&mut **transaction).await?;
|
sqlx::query!(
|
||||||
|
"
|
||||||
|
UPDATE ONLY members
|
||||||
|
SET first_name = $1, full_name = $2, diploma = $3, groups = $4, roles = $5
|
||||||
|
WHERE member_id = $6
|
||||||
|
",
|
||||||
|
member.first_name,
|
||||||
|
member.full_name,
|
||||||
|
member.diploma,
|
||||||
|
member.groups.bits() as i64,
|
||||||
|
member.roles.bits() as i64,
|
||||||
|
member.member_id
|
||||||
|
)
|
||||||
|
.execute(&mut **transaction)
|
||||||
|
.await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -78,7 +105,7 @@ impl Member {
|
|||||||
) -> Result<(), sqlx::Error> {
|
) -> Result<(), sqlx::Error> {
|
||||||
sqlx::query!(
|
sqlx::query!(
|
||||||
"
|
"
|
||||||
DELETE FROM members WHERE id = ANY($1)
|
DELETE FROM members WHERE member_id = ANY($1)
|
||||||
",
|
",
|
||||||
member_ids
|
member_ids
|
||||||
)
|
)
|
||||||
|
108
server/src/database/model/message.rs
Normal file
108
server/src/database/model/message.rs
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use sqlx::{PgPool, Postgres};
|
||||||
|
|
||||||
|
use crate::model::{
|
||||||
|
member::{Groups, Roles},
|
||||||
|
message::{Channel, MessageStatus},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Message {
|
||||||
|
pub message_id: uuid::Uuid,
|
||||||
|
pub created_at: DateTime<Utc>,
|
||||||
|
pub scheduled_at: Option<DateTime<Utc>>,
|
||||||
|
pub status: MessageStatus,
|
||||||
|
pub title: String,
|
||||||
|
pub content: String,
|
||||||
|
pub channel: Channel,
|
||||||
|
pub member_groups: Groups,
|
||||||
|
pub member_roles: Roles,
|
||||||
|
pub thumbnail_url: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Message {
|
||||||
|
pub async fn insert(
|
||||||
|
&self,
|
||||||
|
transaction: &mut sqlx::Transaction<'_, Postgres>,
|
||||||
|
) -> Result<(), sqlx::Error> {
|
||||||
|
sqlx::query!(
|
||||||
|
"
|
||||||
|
INSERT INTO messages (
|
||||||
|
message_id,
|
||||||
|
created_at, scheduled_at,
|
||||||
|
status,
|
||||||
|
title, content,
|
||||||
|
channel,
|
||||||
|
member_groups, member_roles,
|
||||||
|
thumbnail_url
|
||||||
|
) VALUES (
|
||||||
|
$1,
|
||||||
|
$2, $3,
|
||||||
|
$4,
|
||||||
|
$5, $6,
|
||||||
|
$7,
|
||||||
|
$8, $9,
|
||||||
|
$10
|
||||||
|
)
|
||||||
|
",
|
||||||
|
self.message_id,
|
||||||
|
self.created_at,
|
||||||
|
self.scheduled_at,
|
||||||
|
self.status as MessageStatus,
|
||||||
|
self.title,
|
||||||
|
self.content,
|
||||||
|
self.channel.bits() as i64,
|
||||||
|
self.member_groups.bits() as i64,
|
||||||
|
self.member_roles.bits() as i64,
|
||||||
|
self.thumbnail_url,
|
||||||
|
)
|
||||||
|
.execute(&mut **transaction)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get(
|
||||||
|
pool: &PgPool,
|
||||||
|
channel: Channel,
|
||||||
|
member_roles: Roles,
|
||||||
|
member_groups: Groups,
|
||||||
|
) -> Result<Vec<Self>, sqlx::Error> {
|
||||||
|
let messages = sqlx::query_as!(
|
||||||
|
Self,
|
||||||
|
"
|
||||||
|
SELECT message_id, created_at, scheduled_at, status as \"status:MessageStatus\", title, content, channel, member_groups, member_roles, thumbnail_url FROM messages
|
||||||
|
WHERE status = 'sent'
|
||||||
|
AND (channel & $1) > 0
|
||||||
|
AND ((member_roles & $2) > 0 AND (member_groups & $3) > 0);
|
||||||
|
",
|
||||||
|
channel.bits() as i64,
|
||||||
|
member_roles.bits() as i64,
|
||||||
|
member_groups.bits() as i64,
|
||||||
|
)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(messages)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update_status(
|
||||||
|
transaction: &mut sqlx::Transaction<'_, Postgres>,
|
||||||
|
message_id: &uuid::Uuid,
|
||||||
|
status: MessageStatus,
|
||||||
|
) -> Result<(), sqlx::Error> {
|
||||||
|
sqlx::query!(
|
||||||
|
"
|
||||||
|
UPDATE ONLY messages
|
||||||
|
SET status = $1
|
||||||
|
WHERE message_id = $2
|
||||||
|
",
|
||||||
|
status as MessageStatus,
|
||||||
|
message_id,
|
||||||
|
)
|
||||||
|
.execute(&mut **transaction)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
@@ -1,6 +1,96 @@
|
|||||||
struct Session {
|
use chrono::{DateTime, Utc};
|
||||||
id: u32,
|
use sqlx::{PgPool, Postgres};
|
||||||
user_id: u32,
|
|
||||||
token: String,
|
#[derive(Debug)]
|
||||||
expires: chrono::NaiveDateTime,
|
pub struct Session {
|
||||||
|
pub session_id: uuid::Uuid,
|
||||||
|
pub user_id: uuid::Uuid,
|
||||||
|
pub token: String,
|
||||||
|
pub expires_at: DateTime<Utc>,
|
||||||
|
pub created_at: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Session {
|
||||||
|
pub async fn insert(
|
||||||
|
&self,
|
||||||
|
transaction: &mut sqlx::Transaction<'_, Postgres>,
|
||||||
|
) -> Result<(), sqlx::Error> {
|
||||||
|
sqlx::query!(
|
||||||
|
"
|
||||||
|
INSERT INTO sessions (
|
||||||
|
session_id, user_id, token, expires_at, created_at
|
||||||
|
)
|
||||||
|
VALUES (
|
||||||
|
$1, $2, $3, $4, $5
|
||||||
|
)
|
||||||
|
",
|
||||||
|
&self.session_id,
|
||||||
|
&self.user_id,
|
||||||
|
&self.token,
|
||||||
|
&self.expires_at,
|
||||||
|
&self.created_at
|
||||||
|
)
|
||||||
|
.execute(&mut **transaction)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn from_token(pool: &PgPool, token: &str) -> Result<Self, sqlx::Error> {
|
||||||
|
let session = sqlx::query_as!(Self, "SELECT * FROM sessions WHERE token = $1;", token)
|
||||||
|
.fetch_one(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(session)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn remove_many(
|
||||||
|
session_ids: &[uuid::Uuid],
|
||||||
|
transaction: &mut sqlx::Transaction<'_, Postgres>,
|
||||||
|
) -> Result<(), sqlx::Error> {
|
||||||
|
let deleted_count = sqlx::query_scalar!(
|
||||||
|
"
|
||||||
|
WITH deleted AS (
|
||||||
|
DELETE FROM sessions
|
||||||
|
WHERE session_id = ANY($1)
|
||||||
|
RETURNING 1
|
||||||
|
)
|
||||||
|
SELECT COUNT(*) FROM deleted
|
||||||
|
",
|
||||||
|
session_ids
|
||||||
|
)
|
||||||
|
.fetch_one(&mut **transaction)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if !deleted_count.is_some_and(|c| c >= 1) {
|
||||||
|
return Err(sqlx::Error::RowNotFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn remove_many_from_token(
|
||||||
|
transaction: &mut sqlx::Transaction<'_, Postgres>,
|
||||||
|
session_tokens: &[String],
|
||||||
|
) -> Result<(), sqlx::Error> {
|
||||||
|
let deleted_count = sqlx::query_scalar!(
|
||||||
|
"
|
||||||
|
WITH deleted AS (
|
||||||
|
DELETE FROM sessions
|
||||||
|
WHERE token = ANY($1)
|
||||||
|
RETURNING 1
|
||||||
|
)
|
||||||
|
SELECT COUNT(*) FROM deleted
|
||||||
|
",
|
||||||
|
session_tokens
|
||||||
|
)
|
||||||
|
.fetch_one(&mut **transaction)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if !deleted_count.is_some_and(|c| c >= 1) {
|
||||||
|
return Err(sqlx::Error::RowNotFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,8 +1,217 @@
|
|||||||
|
use sqlx::{PgPool, Postgres};
|
||||||
|
|
||||||
|
use crate::model::member::{Groups, Roles};
|
||||||
|
|
||||||
|
use super::Member as DbMember;
|
||||||
|
|
||||||
#[derive(validator::Validate)]
|
#[derive(validator::Validate)]
|
||||||
struct User {
|
pub struct User {
|
||||||
pub id: uuid::Uuid,
|
pub user_id: uuid::Uuid,
|
||||||
#[validate(email)]
|
#[validate(email)]
|
||||||
pub email: String,
|
pub email: String,
|
||||||
pub password: String,
|
pub password: Option<String>,
|
||||||
pub admin: bool,
|
pub admin: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct UpdateUser {
|
||||||
|
pub email: Option<String>,
|
||||||
|
pub password: Option<String>,
|
||||||
|
pub admin: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl User {
|
||||||
|
pub async fn insert(
|
||||||
|
transaction: &mut sqlx::Transaction<'_, Postgres>,
|
||||||
|
email: &str,
|
||||||
|
password: &str,
|
||||||
|
) -> Result<uuid::Uuid, sqlx::Error> {
|
||||||
|
let user_id = uuid::Uuid::new_v4();
|
||||||
|
|
||||||
|
sqlx::query!(
|
||||||
|
"
|
||||||
|
INSERT INTO users (
|
||||||
|
user_id, email, password, admin
|
||||||
|
)
|
||||||
|
VALUES (
|
||||||
|
$1, $2, $3, $4
|
||||||
|
);
|
||||||
|
",
|
||||||
|
&user_id,
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
false
|
||||||
|
)
|
||||||
|
.execute(&mut **transaction)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(user_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_from_email(transaction: &PgPool, email: String) -> Result<Self, sqlx::Error> {
|
||||||
|
let user = sqlx::query_as!(Self, "SELECT * FROM users WHERE email = $1", email)
|
||||||
|
.fetch_one(transaction)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(user)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get(transaction: &PgPool, user_id: uuid::Uuid) -> Result<Self, sqlx::Error> {
|
||||||
|
let user = sqlx::query_as!(Self, "SELECT * FROM users WHERE user_id = $1", user_id)
|
||||||
|
.fetch_one(transaction)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(user)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_password(&self, pool: &PgPool) -> Result<String, sqlx::Error> {
|
||||||
|
let password = sqlx::query_scalar!(
|
||||||
|
"
|
||||||
|
SELECT password FROM users WHERE user_id = $1
|
||||||
|
",
|
||||||
|
self.user_id,
|
||||||
|
)
|
||||||
|
.fetch_one(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(password)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update(
|
||||||
|
&self,
|
||||||
|
transaction: &mut sqlx::Transaction<'_, Postgres>,
|
||||||
|
update_user: UpdateUser,
|
||||||
|
) -> Result<(), sqlx::Error> {
|
||||||
|
sqlx::query!(
|
||||||
|
"
|
||||||
|
UPDATE users
|
||||||
|
SET email = coalesce($1, email),
|
||||||
|
password = coalesce($2, password)
|
||||||
|
WHERE user_id = $3;
|
||||||
|
",
|
||||||
|
update_user.email,
|
||||||
|
update_user.password,
|
||||||
|
self.user_id
|
||||||
|
)
|
||||||
|
.execute(&mut **transaction)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct UserMember {
|
||||||
|
user_id: uuid::Uuid,
|
||||||
|
member_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UserMember {
|
||||||
|
pub async fn insert_many(
|
||||||
|
transaction: &mut sqlx::Transaction<'_, Postgres>,
|
||||||
|
user_ids: &[uuid::Uuid],
|
||||||
|
member_ids: &[String],
|
||||||
|
) -> Result<(), sqlx::Error> {
|
||||||
|
sqlx::query!(
|
||||||
|
"
|
||||||
|
INSERT INTO users_members (
|
||||||
|
user_id, member_id
|
||||||
|
)
|
||||||
|
SELECT * FROM UNNEST($1::uuid[], $2::varchar[])
|
||||||
|
",
|
||||||
|
&user_ids[..],
|
||||||
|
&member_ids[..]
|
||||||
|
)
|
||||||
|
.execute(&mut **transaction)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_roles(pool: &PgPool, user_id: &uuid::Uuid) -> Result<Roles, sqlx::Error> {
|
||||||
|
let roles = sqlx::query_scalar!(
|
||||||
|
"
|
||||||
|
SELECT roles FROM users_members INNER JOIN members ON users_members.member_id = members.member_id AND users_members.user_id = $1;
|
||||||
|
",
|
||||||
|
user_id
|
||||||
|
).fetch_all(pool).await?;
|
||||||
|
|
||||||
|
let roles: Vec<Roles> = roles.into_iter().map(|r| r.into()).collect();
|
||||||
|
let roles = roles
|
||||||
|
.into_iter()
|
||||||
|
.fold(Roles::empty(), |acc, flag| acc | flag);
|
||||||
|
|
||||||
|
Ok(roles)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_roles_groups(
|
||||||
|
pool: &PgPool,
|
||||||
|
user_id: &uuid::Uuid,
|
||||||
|
) -> Result<(Roles, Groups), sqlx::Error> {
|
||||||
|
struct RolesGroups {
|
||||||
|
roles: i64,
|
||||||
|
groups: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
let result = sqlx::query_as!(
|
||||||
|
RolesGroups,
|
||||||
|
"
|
||||||
|
SELECT roles, groups
|
||||||
|
FROM users_members
|
||||||
|
INNER JOIN members ON users_members.member_id = members.member_id
|
||||||
|
AND users_members.user_id = $1;
|
||||||
|
",
|
||||||
|
user_id,
|
||||||
|
)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let (roles, groups) = result.into_iter().fold(
|
||||||
|
(Roles::empty(), Groups::empty()),
|
||||||
|
|(acc_roles, acc_groups), r| (acc_roles | r.roles.into(), acc_groups | r.groups.into()),
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok((roles, groups))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_members_from_user(
|
||||||
|
pool: &PgPool,
|
||||||
|
user_id: &uuid::Uuid,
|
||||||
|
) -> Result<Vec<DbMember>, sqlx::Error> {
|
||||||
|
let members = sqlx::query_as!(DbMember,
|
||||||
|
"
|
||||||
|
SELECT members.* FROM users_members INNER JOIN members ON users_members.member_id = members.member_id AND users_members.user_id = $1;
|
||||||
|
",
|
||||||
|
user_id
|
||||||
|
).fetch_all(pool).await?;
|
||||||
|
|
||||||
|
Ok(members)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn remove_many(
|
||||||
|
transaction: &mut sqlx::Transaction<'_, Postgres>,
|
||||||
|
user_ids: &[uuid::Uuid],
|
||||||
|
member_ids: &[String],
|
||||||
|
) -> Result<(), sqlx::Error> {
|
||||||
|
let deleted_count = sqlx::query_scalar!(
|
||||||
|
"
|
||||||
|
WITH deleted AS (
|
||||||
|
DELETE FROM users_members
|
||||||
|
WHERE user_id = ANY($1) AND member_id = ANY($2)
|
||||||
|
RETURNING 1
|
||||||
|
)
|
||||||
|
SELECT COUNT(*) FROM deleted
|
||||||
|
",
|
||||||
|
&user_ids[..],
|
||||||
|
&member_ids[..]
|
||||||
|
)
|
||||||
|
.fetch_one(&mut **transaction)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if !deleted_count.is_some_and(|c| c >= 1) {
|
||||||
|
return Err(sqlx::Error::RowNotFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@@ -1,13 +1,7 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use axum::Router;
|
|
||||||
use tokio::{net::TcpListener, sync::Mutex};
|
|
||||||
use tracing::Level;
|
use tracing::Level;
|
||||||
use tracing_subscriber::FmtSubscriber;
|
use tracing_subscriber::FmtSubscriber;
|
||||||
|
|
||||||
use wrbapp_server::routes::member::migrate::MigrationStore;
|
use wrbapp_server::database;
|
||||||
use wrbapp_server::routes::routes;
|
|
||||||
use wrbapp_server::{database, AppState};
|
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() {
|
async fn main() {
|
||||||
@@ -30,23 +24,5 @@ async fn main() {
|
|||||||
.await
|
.await
|
||||||
.expect("Database connection failed");
|
.expect("Database connection failed");
|
||||||
|
|
||||||
let migration_store = Arc::new(Mutex::new(MigrationStore::default()));
|
wrbapp_server::util::cli::parse(pool).await;
|
||||||
|
|
||||||
let app_state = AppState {
|
|
||||||
pool,
|
|
||||||
migration_store,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Serve app
|
|
||||||
let app = Router::new().merge(routes()).with_state(app_state);
|
|
||||||
|
|
||||||
let listener = TcpListener::bind("127.0.0.1:3000")
|
|
||||||
.await
|
|
||||||
.expect("Error while initializing listener");
|
|
||||||
|
|
||||||
tracing::info!("Listening on {}", listener.local_addr().unwrap());
|
|
||||||
|
|
||||||
axum::serve(listener, app)
|
|
||||||
.await
|
|
||||||
.expect("Error while serving axum application");
|
|
||||||
}
|
}
|
||||||
|
@@ -1,6 +1,8 @@
|
|||||||
pub mod member;
|
pub mod member;
|
||||||
|
pub mod message;
|
||||||
pub mod session;
|
pub mod session;
|
||||||
pub mod user;
|
pub mod user;
|
||||||
|
|
||||||
pub use member::Member;
|
pub use member::Member;
|
||||||
|
pub use message::Message;
|
||||||
pub use user::User;
|
pub use user::User;
|
||||||
|
@@ -1,32 +1,146 @@
|
|||||||
#[derive(Debug, Clone, serde::Serialize)]
|
use bitflags::bitflags;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct Name {
|
pub struct Name {
|
||||||
pub first: String,
|
pub first: String,
|
||||||
pub full: String,
|
pub full: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, serde::Serialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct Member {
|
pub struct Member {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
pub name: Name,
|
pub name: Name,
|
||||||
pub registration_token: Option<String>,
|
pub registration_token: Option<String>,
|
||||||
pub diploma: Option<String>,
|
pub diploma: Option<String>,
|
||||||
pub hours: Vec<String>,
|
pub groups: Groups,
|
||||||
pub groups: Vec<String>,
|
pub roles: Roles,
|
||||||
|
}
|
||||||
|
|
||||||
|
bitflags! {
|
||||||
|
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
|
||||||
|
pub struct Roles: u64 {
|
||||||
|
const MEMBER = 1 << 0;
|
||||||
|
const KADER = 1 << 1;
|
||||||
|
const ZWEMZAKEN = 1 << 2;
|
||||||
|
const WEDSTRIJDEN = 1 << 3;
|
||||||
|
const ADMIN = 1 << 4;
|
||||||
|
const MESSAGES = 1 << 5;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
|
||||||
|
pub struct Groups: u64 {
|
||||||
|
const NONE = 1 << 0;
|
||||||
|
|
||||||
|
const A1 = 1 << 1;
|
||||||
|
const A2 = 1 << 2;
|
||||||
|
const A3 = 1 << 3;
|
||||||
|
const A4 = 1 << 4;
|
||||||
|
const A5 = 1 << 5;
|
||||||
|
const A6 = 1 << 6;
|
||||||
|
|
||||||
|
const B1 = 1 << 7;
|
||||||
|
const B2 = 1 << 8;
|
||||||
|
const B3 = 1 << 9;
|
||||||
|
const B4 = 1 << 10;
|
||||||
|
const B5 = 1 << 11;
|
||||||
|
const B6 = 1 << 12;
|
||||||
|
|
||||||
|
const C1 = 1 << 13;
|
||||||
|
const C2 = 1 << 14;
|
||||||
|
const C3 = 1 << 15;
|
||||||
|
const C4 = 1 << 16;
|
||||||
|
const C5 = 1 << 17;
|
||||||
|
const C6 = 1 << 18;
|
||||||
|
|
||||||
|
const D1 = 1 << 19;
|
||||||
|
const D2 = 1 << 20;
|
||||||
|
const D3 = 1 << 21;
|
||||||
|
const D4 = 1 << 22;
|
||||||
|
const D5 = 1 << 23;
|
||||||
|
const D6 = 1 << 24;
|
||||||
|
|
||||||
|
const E1 = 1 << 25;
|
||||||
|
const E2 = 1 << 26;
|
||||||
|
const E3 = 1 << 27;
|
||||||
|
const E4 = 1 << 28;
|
||||||
|
const E5 = 1 << 29;
|
||||||
|
const E6 = 1 << 30;
|
||||||
|
|
||||||
|
const Z1 = 1 << 31;
|
||||||
|
const Z2 = 1 << 32;
|
||||||
|
const Z3 = 1 << 33;
|
||||||
|
const Z4 = 1 << 34;
|
||||||
|
const Z5 = 1 << 35;
|
||||||
|
const Z6 = 1 << 36;
|
||||||
|
|
||||||
|
const WEDSTRIJD = 1 << 37;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<i64> for Groups {
|
||||||
|
fn from(value: i64) -> Self {
|
||||||
|
Self::from_bits(value as u64).unwrap_or(Groups::empty())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Option<Groups>> for Groups {
|
||||||
|
fn from(value: Option<Groups>) -> Self {
|
||||||
|
match value {
|
||||||
|
Some(groups) => groups,
|
||||||
|
None => Self::empty(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Groups {
|
||||||
|
pub fn to_option(self) -> Option<Self> {
|
||||||
|
if self.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<i64> for Roles {
|
||||||
|
fn from(value: i64) -> Self {
|
||||||
|
Self::from_bits(value as u64).unwrap_or(Roles::empty())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Option<Roles>> for Roles {
|
||||||
|
fn from(value: Option<Roles>) -> Self {
|
||||||
|
match value {
|
||||||
|
Some(roles) => roles,
|
||||||
|
None => Self::empty(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Roles {
|
||||||
|
pub fn to_option(self) -> Option<Self> {
|
||||||
|
if self.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
use crate::database::model::Member as DbMember;
|
use crate::database::model::Member as DbMember;
|
||||||
impl From<DbMember> for Member {
|
impl From<DbMember> for Member {
|
||||||
fn from(value: DbMember) -> Self {
|
fn from(value: DbMember) -> Self {
|
||||||
Member {
|
Member {
|
||||||
id: value.id,
|
id: value.member_id,
|
||||||
name: Name {
|
name: Name {
|
||||||
first: value.first_name,
|
first: value.first_name,
|
||||||
full: value.full_name,
|
full: value.full_name,
|
||||||
},
|
},
|
||||||
registration_token: value.registration_token,
|
registration_token: value.registration_token,
|
||||||
diploma: value.diploma,
|
diploma: value.diploma,
|
||||||
hours: value.hours,
|
|
||||||
groups: value.groups,
|
groups: value.groups,
|
||||||
|
roles: value.roles,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -34,13 +148,13 @@ impl From<DbMember> for Member {
|
|||||||
impl From<Member> for DbMember {
|
impl From<Member> for DbMember {
|
||||||
fn from(value: Member) -> Self {
|
fn from(value: Member) -> Self {
|
||||||
DbMember {
|
DbMember {
|
||||||
id: value.id,
|
member_id: value.id,
|
||||||
first_name: value.name.first,
|
first_name: value.name.first,
|
||||||
full_name: value.name.full,
|
full_name: value.name.full,
|
||||||
registration_token: None,
|
registration_token: None,
|
||||||
diploma: value.diploma,
|
diploma: value.diploma,
|
||||||
hours: value.hours,
|
|
||||||
groups: value.groups,
|
groups: value.groups,
|
||||||
|
roles: value.roles,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
136
server/src/model/message.rs
Normal file
136
server/src/model/message.rs
Normal file
@@ -0,0 +1,136 @@
|
|||||||
|
use bitflags::bitflags;
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct Message {
|
||||||
|
pub message_id: uuid::Uuid,
|
||||||
|
pub created_at: DateTime<Utc>,
|
||||||
|
pub scheduled_at: Option<DateTime<Utc>>,
|
||||||
|
pub status: MessageStatus,
|
||||||
|
pub title: String,
|
||||||
|
pub content: String,
|
||||||
|
pub channel: Channel,
|
||||||
|
pub member_groups: Groups,
|
||||||
|
pub member_roles: Roles,
|
||||||
|
pub thumbnail_url: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, sqlx::Type, Serialize)]
|
||||||
|
#[sqlx(type_name = "message_status", rename_all = "lowercase")]
|
||||||
|
pub enum MessageStatus {
|
||||||
|
Pending,
|
||||||
|
Sent,
|
||||||
|
Canceled,
|
||||||
|
Draft,
|
||||||
|
}
|
||||||
|
|
||||||
|
bitflags! {
|
||||||
|
#[derive(Clone, Copy, Debug, Serialize)]
|
||||||
|
pub struct Channel: u16 {
|
||||||
|
const ALGEMEEN = 1 << 0;
|
||||||
|
const BELANGRIJK = 1 << 1;
|
||||||
|
const WEDSTRIJDEN = 1 << 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<i64> for Channel {
|
||||||
|
fn from(value: i64) -> Self {
|
||||||
|
Self::from_bits(value as u16).unwrap_or(Channel::empty())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct MessageCreate {
|
||||||
|
pub scheduled_at: Option<DateTime<Utc>>,
|
||||||
|
pub title: String,
|
||||||
|
pub content: String,
|
||||||
|
pub channel: String,
|
||||||
|
pub member_groups: String,
|
||||||
|
pub member_roles: String,
|
||||||
|
pub thumbnail_url: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Message {
|
||||||
|
pub fn new(message_create: MessageCreate) -> Result<Self, crate::Error> {
|
||||||
|
let message_id = uuid::Uuid::new_v4();
|
||||||
|
|
||||||
|
let created_at = Utc::now();
|
||||||
|
|
||||||
|
let channel: Channel =
|
||||||
|
bitflags::parser::from_str_strict(&message_create.channel).map_err(|_| {
|
||||||
|
crate::Error::BadRequest {
|
||||||
|
expected: String::from("Error while parsing channel"),
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let member_groups = if message_create.member_groups.is_empty() {
|
||||||
|
Ok(Groups::all())
|
||||||
|
} else {
|
||||||
|
bitflags::parser::from_str_strict(&message_create.member_groups).map_err(|_| {
|
||||||
|
crate::Error::BadRequest {
|
||||||
|
expected: "Error while parsing groups".to_string(),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}?;
|
||||||
|
|
||||||
|
let member_roles = if message_create.member_roles.is_empty() {
|
||||||
|
Ok(Roles::all())
|
||||||
|
} else {
|
||||||
|
bitflags::parser::from_str_strict(&message_create.member_roles).map_err(|_| {
|
||||||
|
crate::Error::BadRequest {
|
||||||
|
expected: "Error while parsing groups".to_string(),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}?;
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
message_id,
|
||||||
|
created_at,
|
||||||
|
scheduled_at: message_create.scheduled_at,
|
||||||
|
title: message_create.title,
|
||||||
|
content: message_create.content,
|
||||||
|
channel,
|
||||||
|
thumbnail_url: message_create.thumbnail_url,
|
||||||
|
member_groups,
|
||||||
|
member_roles,
|
||||||
|
status: MessageStatus::Draft,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
use crate::database::model::Message as DbMessage;
|
||||||
|
|
||||||
|
use super::member::{Groups, Roles};
|
||||||
|
impl From<DbMessage> for Message {
|
||||||
|
fn from(value: DbMessage) -> Self {
|
||||||
|
Self {
|
||||||
|
message_id: value.message_id,
|
||||||
|
created_at: value.created_at,
|
||||||
|
scheduled_at: value.scheduled_at,
|
||||||
|
status: value.status,
|
||||||
|
title: value.title,
|
||||||
|
content: value.content,
|
||||||
|
channel: value.channel,
|
||||||
|
member_groups: value.member_groups,
|
||||||
|
member_roles: value.member_roles,
|
||||||
|
thumbnail_url: value.thumbnail_url,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Message> for DbMessage {
|
||||||
|
fn from(value: Message) -> Self {
|
||||||
|
Self {
|
||||||
|
message_id: value.message_id,
|
||||||
|
created_at: value.created_at,
|
||||||
|
scheduled_at: value.scheduled_at,
|
||||||
|
status: value.status,
|
||||||
|
title: value.title,
|
||||||
|
content: value.content,
|
||||||
|
channel: value.channel,
|
||||||
|
member_groups: value.member_groups,
|
||||||
|
member_roles: value.member_roles,
|
||||||
|
thumbnail_url: value.thumbnail_url,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@@ -0,0 +1,55 @@
|
|||||||
|
use chrono::{DateTime, Duration, Utc};
|
||||||
|
|
||||||
|
use crate::auth::generate_session_token;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Session {
|
||||||
|
pub session_id: uuid::Uuid,
|
||||||
|
pub user_id: uuid::Uuid,
|
||||||
|
pub token: String,
|
||||||
|
pub expires_at: DateTime<Utc>,
|
||||||
|
pub created_at: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Session {
|
||||||
|
pub fn new(user_id: uuid::Uuid) -> Self {
|
||||||
|
let session_id = uuid::Uuid::new_v4();
|
||||||
|
let token = generate_session_token();
|
||||||
|
|
||||||
|
let created_at = Utc::now();
|
||||||
|
let expires_at = Utc::now() + Duration::days(7);
|
||||||
|
|
||||||
|
Self {
|
||||||
|
session_id,
|
||||||
|
user_id,
|
||||||
|
token,
|
||||||
|
expires_at,
|
||||||
|
created_at,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
use crate::database::model::Session as DbSession;
|
||||||
|
impl From<DbSession> for Session {
|
||||||
|
fn from(db_session: DbSession) -> Self {
|
||||||
|
Self {
|
||||||
|
session_id: db_session.session_id,
|
||||||
|
user_id: db_session.user_id,
|
||||||
|
token: db_session.token,
|
||||||
|
expires_at: db_session.expires_at,
|
||||||
|
created_at: db_session.created_at,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Session> for DbSession {
|
||||||
|
fn from(session: Session) -> Self {
|
||||||
|
Self {
|
||||||
|
session_id: session.session_id,
|
||||||
|
user_id: session.user_id,
|
||||||
|
token: session.token,
|
||||||
|
expires_at: session.expires_at,
|
||||||
|
created_at: session.created_at,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@@ -1,5 +1,80 @@
|
|||||||
|
use serde::Serialize;
|
||||||
|
use sqlx::PgPool;
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
pub struct User {
|
pub struct User {
|
||||||
pub id: uuid::Uuid,
|
pub id: uuid::Uuid,
|
||||||
pub email: String,
|
pub email: String,
|
||||||
pub admin: bool,
|
pub admin: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
use crate::auth::AuthError;
|
||||||
|
use crate::database::model::User as DbUser;
|
||||||
|
use crate::database::model::UserMember as DbUserMember;
|
||||||
|
use crate::util::convert_vec;
|
||||||
|
|
||||||
|
use super::member::Groups;
|
||||||
|
use super::member::Roles;
|
||||||
|
use super::Member;
|
||||||
|
impl From<DbUser> for User {
|
||||||
|
fn from(db_user: DbUser) -> Self {
|
||||||
|
Self {
|
||||||
|
id: db_user.user_id,
|
||||||
|
email: db_user.email,
|
||||||
|
admin: db_user.admin,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<User> for DbUser {
|
||||||
|
fn from(user: User) -> Self {
|
||||||
|
Self {
|
||||||
|
user_id: user.id,
|
||||||
|
email: user.email,
|
||||||
|
admin: user.admin,
|
||||||
|
password: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl User {
|
||||||
|
pub async fn members(&self, pool: &PgPool) -> Result<Vec<Member>, sqlx::Error> {
|
||||||
|
let related_members = DbUserMember::get_members_from_user(pool, &self.id).await?;
|
||||||
|
|
||||||
|
Ok(convert_vec(related_members))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn authorize(
|
||||||
|
&self,
|
||||||
|
pool: &PgPool,
|
||||||
|
required_roles: Option<Roles>,
|
||||||
|
requested_user_id: Option<String>,
|
||||||
|
) -> Result<(), AuthError> {
|
||||||
|
if let Some(user_id) = requested_user_id {
|
||||||
|
let user_uuid = uuid::Uuid::parse_str(&user_id).map_err(|_| AuthError::NoPermssions)?;
|
||||||
|
|
||||||
|
if self.id != user_uuid {
|
||||||
|
return Err(AuthError::NoPermssions);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(roles) = required_roles {
|
||||||
|
let user_roles = DbUserMember::get_roles(pool, &self.id)
|
||||||
|
.await
|
||||||
|
.unwrap_or(Roles::MEMBER);
|
||||||
|
if !user_roles.intersects(roles) {
|
||||||
|
return Err(AuthError::NoPermssions);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_roles_groups(&self, pool: &PgPool) -> Result<(Roles, Groups), sqlx::Error> {
|
||||||
|
DbUserMember::get_roles_groups(pool, &self.id).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@@ -1,30 +1,25 @@
|
|||||||
use axum::{
|
use crate::{auth::get_user_from_header, model::User, AppState};
|
||||||
extract::State,
|
use axum::{extract::State, http::HeaderMap, routing::get, Json, Router};
|
||||||
http::StatusCode,
|
|
||||||
routing::{get, post},
|
|
||||||
Router,
|
|
||||||
};
|
|
||||||
use member::migrate::{migrate_confirm, migrate_request};
|
|
||||||
|
|
||||||
use crate::{auth::Permissions, AppState};
|
|
||||||
|
|
||||||
pub mod auth;
|
pub mod auth;
|
||||||
pub mod member;
|
pub mod member;
|
||||||
|
pub mod message;
|
||||||
pub mod user;
|
pub mod user;
|
||||||
|
|
||||||
pub fn routes() -> Router<AppState> {
|
pub fn routes() -> Router<AppState> {
|
||||||
Router::new()
|
Router::new()
|
||||||
.route("/", get(root))
|
.route("/", get(root))
|
||||||
// .route("/member/:id", get())
|
.merge(member::routes())
|
||||||
.route("/members/migrate_request", post(migrate_request))
|
.merge(auth::routes())
|
||||||
.route("/members/migrate_confirm", post(migrate_confirm))
|
.merge(user::routes())
|
||||||
|
.merge(message::routes())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn root(
|
async fn root(
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
permissions: Permissions<'_>,
|
headers: HeaderMap,
|
||||||
) -> Result<String, (StatusCode, String)> {
|
) -> Result<Json<User>, crate::Error> {
|
||||||
tracing::info!("{:?}", permissions);
|
let user = get_user_from_header(&state.pool, &headers).await?;
|
||||||
|
|
||||||
Ok("Hello world".to_string())
|
Ok(Json(user))
|
||||||
}
|
}
|
||||||
|
@@ -1 +1,181 @@
|
|||||||
|
use axum::http::HeaderMap;
|
||||||
|
use axum::{
|
||||||
|
extract::State,
|
||||||
|
routing::{get, post},
|
||||||
|
Json, Router,
|
||||||
|
};
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use crate::auth::{get_token_from_headers, verify_password_hash};
|
||||||
|
use crate::auth::{get_user_from_header, AuthError};
|
||||||
|
use crate::database::model::user::UpdateUser;
|
||||||
|
use crate::database::model::Member as DbMember;
|
||||||
|
use crate::database::model::Session as DbSession;
|
||||||
|
use crate::database::model::User as DbUser;
|
||||||
|
use crate::database::model::UserMember as DbUserMember;
|
||||||
|
use crate::model::session::Session;
|
||||||
|
use crate::{auth::generate_password_hash, AppState};
|
||||||
|
|
||||||
|
pub fn routes() -> Router<AppState> {
|
||||||
|
Router::new()
|
||||||
|
.route("/auth/login", post(login))
|
||||||
|
.route("/auth/register", post(register))
|
||||||
|
.route("/auth/logout", get(logout))
|
||||||
|
.route("/auth/change_password", post(change_password))
|
||||||
|
.route("/auth/change_email", post(change_email))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct LoginRequest {
|
||||||
|
email: String,
|
||||||
|
password: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn login(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Json(login_request): Json<LoginRequest>,
|
||||||
|
) -> Result<String, crate::Error> {
|
||||||
|
let db_user = DbUser::get_from_email(&state.pool, login_request.email).await?;
|
||||||
|
|
||||||
|
if let Some(pass) = db_user.password {
|
||||||
|
verify_password_hash(&login_request.password, &pass).await?;
|
||||||
|
} else {
|
||||||
|
return Err(AuthError::Unexpected.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create session
|
||||||
|
let mut transaction = state.pool.begin().await?;
|
||||||
|
|
||||||
|
let db_session: DbSession = Session::new(db_user.user_id).into();
|
||||||
|
db_session.insert(&mut transaction).await?;
|
||||||
|
|
||||||
|
transaction.commit().await?;
|
||||||
|
|
||||||
|
Ok(db_session.token)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct RegisterRequest {
|
||||||
|
email: String,
|
||||||
|
password: String,
|
||||||
|
registration_tokens: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn register(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Json(auth_request): Json<RegisterRequest>,
|
||||||
|
) -> Result<String, crate::Error> {
|
||||||
|
// Get all the members to link with the user
|
||||||
|
let members =
|
||||||
|
DbMember::get_many_from_registration_tokens(&state.pool, auth_request.registration_tokens)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let member_ids: Vec<String> = members.into_iter().map(|m| m.member_id).collect();
|
||||||
|
|
||||||
|
// Hash password
|
||||||
|
let password_hash = generate_password_hash(auth_request.password).await?;
|
||||||
|
|
||||||
|
let mut transaction = state.pool.begin().await?;
|
||||||
|
|
||||||
|
// Insert the user to the database
|
||||||
|
let user_id = DbUser::insert(&mut transaction, &auth_request.email, &password_hash).await?;
|
||||||
|
|
||||||
|
// Link the user to the members
|
||||||
|
let user_ids: Vec<uuid::Uuid> = vec![user_id; member_ids.len()];
|
||||||
|
DbUserMember::insert_many(&mut transaction, &user_ids, &member_ids).await?;
|
||||||
|
|
||||||
|
// Create a new session
|
||||||
|
let db_session: DbSession = Session::new(user_id).into();
|
||||||
|
db_session.insert(&mut transaction).await?;
|
||||||
|
|
||||||
|
transaction.commit().await?;
|
||||||
|
|
||||||
|
Ok(db_session.token)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn logout(State(state): State<AppState>, headers: HeaderMap) -> Result<(), crate::Error> {
|
||||||
|
let registration_token = get_token_from_headers(&headers)?;
|
||||||
|
|
||||||
|
let mut transaction = state.pool.begin().await?;
|
||||||
|
|
||||||
|
DbSession::remove_many_from_token(&mut transaction, &[registration_token]).await?;
|
||||||
|
|
||||||
|
transaction.commit().await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct ChangePasswordRequest {
|
||||||
|
pub old_password: String,
|
||||||
|
pub new_password: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn change_password(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Json(request): Json<ChangePasswordRequest>,
|
||||||
|
) -> Result<(), crate::Error> {
|
||||||
|
let user = get_user_from_header(&state.pool, &headers).await?;
|
||||||
|
|
||||||
|
// Verify that password is correct
|
||||||
|
let db_user: DbUser = user.into();
|
||||||
|
let old_password_hash = db_user.get_password(&state.pool).await?;
|
||||||
|
verify_password_hash(&request.old_password, &old_password_hash).await?;
|
||||||
|
|
||||||
|
// Generate password hash for new password
|
||||||
|
let new_password_hash = generate_password_hash(request.new_password).await?;
|
||||||
|
|
||||||
|
let mut transaction = state.pool.begin().await?;
|
||||||
|
|
||||||
|
db_user
|
||||||
|
.update(
|
||||||
|
&mut transaction,
|
||||||
|
UpdateUser {
|
||||||
|
email: None,
|
||||||
|
password: Some(new_password_hash),
|
||||||
|
admin: None,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
transaction.commit().await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct ChangeEmailRequest {
|
||||||
|
pub password: String,
|
||||||
|
pub new_email: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn change_email(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Json(request): Json<ChangeEmailRequest>,
|
||||||
|
) -> Result<(), crate::Error> {
|
||||||
|
let user = get_user_from_header(&state.pool, &headers).await?;
|
||||||
|
|
||||||
|
// Verify that password is correct
|
||||||
|
let db_user: DbUser = user.into();
|
||||||
|
let password_hash = db_user.get_password(&state.pool).await?;
|
||||||
|
verify_password_hash(&request.password, &password_hash).await?;
|
||||||
|
|
||||||
|
let mut transaction = state.pool.begin().await?;
|
||||||
|
|
||||||
|
db_user
|
||||||
|
.update(
|
||||||
|
&mut transaction,
|
||||||
|
UpdateUser {
|
||||||
|
email: Some(request.new_email),
|
||||||
|
password: None,
|
||||||
|
admin: None,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
transaction.commit().await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
@@ -1 +1,28 @@
|
|||||||
|
use axum::{
|
||||||
|
extract::State,
|
||||||
|
http::HeaderMap,
|
||||||
|
routing::{get, post},
|
||||||
|
Json, Router,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::{auth::get_user_from_header, model::Member, AppState};
|
||||||
|
|
||||||
pub mod migrate;
|
pub mod migrate;
|
||||||
|
|
||||||
|
pub fn routes() -> Router<AppState> {
|
||||||
|
Router::new()
|
||||||
|
.route("/members/migrate_request", post(migrate::migrate_request))
|
||||||
|
.route("/members/migrate_confirm", post(migrate::migrate_confirm))
|
||||||
|
.route("/member", get(get_current_members))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_current_members(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
) -> Result<Json<Vec<Member>>, crate::Error> {
|
||||||
|
let user = get_user_from_header(&state.pool, &headers).await?;
|
||||||
|
|
||||||
|
let members = user.members(&state.pool).await?;
|
||||||
|
|
||||||
|
Ok(Json(members))
|
||||||
|
}
|
||||||
|
@@ -1,25 +1,28 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use axum::{extract::State, Json};
|
use axum::{extract::State, http::HeaderMap, Json};
|
||||||
use itertools::Itertools;
|
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
auth::{AuthError, Permissions},
|
auth::get_user_from_header,
|
||||||
database::model::Member as DbMember,
|
database::model::Member as DbMember,
|
||||||
model::{member::Name, Member},
|
model::{
|
||||||
|
member::{Groups, Name, Roles},
|
||||||
|
Member,
|
||||||
|
},
|
||||||
util::convert_vec,
|
util::convert_vec,
|
||||||
AppState,
|
AppState,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub async fn migrate_request<'a>(
|
pub async fn migrate_request(
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
permissions: Permissions<'a>,
|
headers: HeaderMap,
|
||||||
body: String,
|
body: String,
|
||||||
) -> Result<Json<MigrationResponse>, crate::Error> {
|
) -> Result<Json<MigrationResponse>, crate::Error> {
|
||||||
if !permissions.0.contains("root") {
|
let user = get_user_from_header(&state.pool, &headers).await?;
|
||||||
return Err(AuthError::NoPermssions.into());
|
|
||||||
}
|
user.authorize(&state.pool, Some(Roles::ADMIN), None)
|
||||||
|
.await?;
|
||||||
|
|
||||||
tracing::info!("Migration is requested");
|
tracing::info!("Migration is requested");
|
||||||
|
|
||||||
@@ -42,21 +45,24 @@ pub async fn migrate_request<'a>(
|
|||||||
Ok(Json(MigrationResponse::from((count, members_diff))))
|
Ok(Json(MigrationResponse::from((count, members_diff))))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn migrate_confirm<'a>(
|
pub async fn migrate_confirm(
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
permissions: Permissions<'a>,
|
headers: HeaderMap,
|
||||||
body: String,
|
body: String,
|
||||||
) -> Result<(), crate::Error> {
|
) -> Result<(), crate::Error> {
|
||||||
if !permissions.0.contains("root") {
|
let user = get_user_from_header(&state.pool, &headers).await?;
|
||||||
return Err(AuthError::NoPermssions.into());
|
user.authorize(&state.pool, Some(Roles::ADMIN), None)
|
||||||
}
|
.await?;
|
||||||
|
|
||||||
tracing::info!("Migration is confirmed");
|
tracing::info!("Migration is confirmed");
|
||||||
|
|
||||||
// TODO: Implement better error naming
|
|
||||||
let count = match body.trim().parse::<u32>() {
|
let count = match body.trim().parse::<u32>() {
|
||||||
Ok(c) => c,
|
Ok(c) => c,
|
||||||
Err(_) => return Err(crate::Error::NotFound),
|
Err(_) => {
|
||||||
|
return Err(crate::Error::BadRequest {
|
||||||
|
expected: String::from("u32"),
|
||||||
|
})
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut store = state.migration_store.lock().await;
|
let mut store = state.migration_store.lock().await;
|
||||||
@@ -110,7 +116,7 @@ struct Row {
|
|||||||
#[serde(rename = "E-mail")]
|
#[serde(rename = "E-mail")]
|
||||||
email: String,
|
email: String,
|
||||||
#[serde(rename = "Verenigingssporten")]
|
#[serde(rename = "Verenigingssporten")]
|
||||||
hours: String,
|
groups: String,
|
||||||
#[serde(rename = "Diploma dropdown 1")]
|
#[serde(rename = "Diploma dropdown 1")]
|
||||||
diploma: Option<String>,
|
diploma: Option<String>,
|
||||||
}
|
}
|
||||||
@@ -130,20 +136,12 @@ pub struct MigrationResponse {
|
|||||||
remove: Vec<(String, Name)>,
|
remove: Vec<(String, Name)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
pub struct MigrationStore {
|
pub struct MigrationStore {
|
||||||
pub store: HashMap<u32, MembersDiff>,
|
pub store: HashMap<u32, MembersDiff>,
|
||||||
pub count: u32,
|
pub count: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for MigrationStore {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
count: 0,
|
|
||||||
store: HashMap::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Row {
|
impl Row {
|
||||||
fn from_csv_many(input: &str) -> Result<Vec<Self>, csv::Error> {
|
fn from_csv_many(input: &str) -> Result<Vec<Self>, csv::Error> {
|
||||||
let mut rdr = csv::ReaderBuilder::new()
|
let mut rdr = csv::ReaderBuilder::new()
|
||||||
@@ -155,45 +153,45 @@ impl Row {
|
|||||||
members
|
members
|
||||||
}
|
}
|
||||||
|
|
||||||
fn hours_parsed(&self) -> Vec<String> {
|
fn groups_parsed(&self) -> Groups {
|
||||||
let mut hours: Vec<String> = Vec::new();
|
let mut groups: Vec<String> = Vec::new();
|
||||||
|
|
||||||
let group_parts: Vec<&str> = self.hours.split(", ").collect();
|
let group_parts: Vec<&str> = self.groups.split(", ").collect();
|
||||||
|
|
||||||
for group in group_parts {
|
for group in group_parts {
|
||||||
let hour_parts: Vec<&str> = group.split(" - ").collect();
|
let hour_parts: Vec<&str> = group.split(" - ").collect();
|
||||||
|
|
||||||
for part in hour_parts {
|
if let Some(group) = hour_parts.get(1) {
|
||||||
if &*part != "Groep" {
|
groups.push(group.to_uppercase())
|
||||||
hours.push(part.to_string());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
hours.into_iter().unique().collect()
|
let groups_string = groups.join("|");
|
||||||
|
|
||||||
|
bitflags::parser::from_str(&groups_string).unwrap_or(Groups::empty())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Into<Name> for Row {
|
impl From<Row> for Name {
|
||||||
fn into(self) -> Name {
|
fn from(val: Row) -> Self {
|
||||||
Name {
|
Name {
|
||||||
first: self.first_name,
|
first: val.first_name,
|
||||||
full: "Temporarely full name".to_string(),
|
full: "Temporarely full name".to_string(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Into<Member> for Row {
|
impl From<Row> for Member {
|
||||||
fn into(self) -> Member {
|
fn from(val: Row) -> Self {
|
||||||
let name: Name = self.clone().into();
|
let name: Name = val.clone().into();
|
||||||
|
|
||||||
Member {
|
Member {
|
||||||
id: self.id.clone(),
|
id: val.id.clone(),
|
||||||
name,
|
name,
|
||||||
registration_token: None,
|
registration_token: None,
|
||||||
diploma: self.diploma.clone(),
|
diploma: val.diploma.clone(),
|
||||||
hours: self.hours_parsed(),
|
groups: val.groups_parsed(),
|
||||||
groups: Vec::new(),
|
roles: Roles::MEMBER,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -255,8 +253,8 @@ fn generate_diff(members_new: Vec<Member>, members_old: Vec<Member>) -> MembersD
|
|||||||
name: new_member.name.clone(),
|
name: new_member.name.clone(),
|
||||||
registration_token: old_member.registration_token,
|
registration_token: old_member.registration_token,
|
||||||
diploma: new_member.diploma.clone(),
|
diploma: new_member.diploma.clone(),
|
||||||
hours: new_member.hours.clone(),
|
groups: new_member.groups,
|
||||||
groups: old_member.groups,
|
roles: old_member.roles,
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
members_remove.push(old_member);
|
members_remove.push(old_member);
|
||||||
|
87
server/src/routes/message.rs
Normal file
87
server/src/routes/message.rs
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
use axum::{
|
||||||
|
extract::{Path, State},
|
||||||
|
http::HeaderMap,
|
||||||
|
routing::post,
|
||||||
|
Json, Router,
|
||||||
|
};
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
auth::get_user_from_header,
|
||||||
|
database::model::Message as DbMessage,
|
||||||
|
model::{
|
||||||
|
member::Roles,
|
||||||
|
message::{MessageCreate, MessageStatus},
|
||||||
|
Message,
|
||||||
|
},
|
||||||
|
AppState,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub fn routes() -> Router<AppState> {
|
||||||
|
Router::new()
|
||||||
|
.route("/messages", post(message_create))
|
||||||
|
.route("/messages/{message_id}/send", post(message_send))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct MessageCreateRequest {
|
||||||
|
title: String,
|
||||||
|
content: String,
|
||||||
|
channel: String,
|
||||||
|
member_groups: String,
|
||||||
|
member_roles: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn message_create(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Json(request): Json<MessageCreateRequest>,
|
||||||
|
) -> Result<String, crate::Error> {
|
||||||
|
let user = get_user_from_header(&state.pool, &headers).await?;
|
||||||
|
|
||||||
|
user.authorize(&state.pool, Some(Roles::ADMIN | Roles::MESSAGES), None)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let db_message: DbMessage = Message::new(MessageCreate {
|
||||||
|
title: request.title,
|
||||||
|
content: request.content,
|
||||||
|
channel: request.channel,
|
||||||
|
member_groups: request.member_groups,
|
||||||
|
member_roles: request.member_roles,
|
||||||
|
scheduled_at: None,
|
||||||
|
thumbnail_url: None,
|
||||||
|
})?
|
||||||
|
.into();
|
||||||
|
|
||||||
|
let mut transaction = state.pool.begin().await?;
|
||||||
|
|
||||||
|
db_message.insert(&mut transaction).await?;
|
||||||
|
|
||||||
|
transaction.commit().await?;
|
||||||
|
|
||||||
|
Ok(db_message.message_id.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn message_send(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Path(message_id): Path<String>,
|
||||||
|
) -> Result<(), crate::Error> {
|
||||||
|
let user = get_user_from_header(&state.pool, &headers).await?;
|
||||||
|
|
||||||
|
user.authorize(&state.pool, Some(Roles::ADMIN | Roles::MESSAGES), None)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let message_id: uuid::Uuid =
|
||||||
|
uuid::Uuid::parse_str(&message_id).map_err(|_| crate::Error::BadRequest {
|
||||||
|
expected: "Could not convert message id to uuid".to_string(),
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let mut transaction = state.pool.begin().await?;
|
||||||
|
|
||||||
|
DbMessage::update_status(&mut transaction, &message_id, MessageStatus::Sent).await?;
|
||||||
|
|
||||||
|
transaction.commit().await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
@@ -1 +1,91 @@
|
|||||||
|
use axum::{
|
||||||
|
extract::{Path, State},
|
||||||
|
http::HeaderMap,
|
||||||
|
routing::{delete, get, post},
|
||||||
|
Json, Router,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
auth::get_user_from_header,
|
||||||
|
database::model::{Member as DbMember, Message as DbMessage, UserMember as DbUserMember},
|
||||||
|
model::{member::Roles, message::Channel, Member, Message, User},
|
||||||
|
util::convert_vec,
|
||||||
|
AppState,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub fn routes() -> Router<AppState> {
|
||||||
|
Router::new()
|
||||||
|
.route("/user", get(get_current_user))
|
||||||
|
.route("/user/{user_id}/members", post(members_insert))
|
||||||
|
.route("/user/{user_id}/members", delete(members_remove))
|
||||||
|
.route("/user/{user_id}/messages", get(get_messages))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_current_user(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
) -> Result<Json<User>, crate::Error> {
|
||||||
|
let user = get_user_from_header(&state.pool, &headers).await?;
|
||||||
|
Ok(Json(user))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn members_insert(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(user_id): Path<String>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Json(registration_tokens): Json<Vec<String>>,
|
||||||
|
) -> Result<Json<Vec<Member>>, crate::Error> {
|
||||||
|
let user = get_user_from_header(&state.pool, &headers).await?;
|
||||||
|
user.authorize(&state.pool, Some(Roles::ADMIN), Some(user_id))
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let members =
|
||||||
|
DbMember::get_many_from_registration_tokens(&state.pool, registration_tokens).await?;
|
||||||
|
|
||||||
|
let member_ids: Vec<String> = members.iter().map(|m| m.member_id.to_owned()).collect();
|
||||||
|
|
||||||
|
let mut transaction = state.pool.begin().await?;
|
||||||
|
|
||||||
|
// Link the user to the members
|
||||||
|
let user_ids: Vec<uuid::Uuid> = vec![user.id; member_ids.len()];
|
||||||
|
DbUserMember::insert_many(&mut transaction, &user_ids, &member_ids).await?;
|
||||||
|
|
||||||
|
transaction.commit().await?;
|
||||||
|
|
||||||
|
Ok(Json(convert_vec(members)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn members_remove(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(user_id): Path<String>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Json(member_ids): Json<Vec<String>>,
|
||||||
|
) -> Result<(), crate::Error> {
|
||||||
|
let user = get_user_from_header(&state.pool, &headers).await?;
|
||||||
|
user.authorize(&state.pool, Some(Roles::ADMIN), Some(user_id))
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let mut transaction = state.pool.begin().await?;
|
||||||
|
|
||||||
|
// Link the user to the members
|
||||||
|
DbUserMember::remove_many(&mut transaction, &[user.id], &member_ids).await?;
|
||||||
|
|
||||||
|
transaction.commit().await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_messages(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(user_id): Path<String>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
) -> Result<Json<Vec<Message>>, crate::Error> {
|
||||||
|
let user = get_user_from_header(&state.pool, &headers).await?;
|
||||||
|
user.authorize(&state.pool, None, Some(user_id)).await?;
|
||||||
|
|
||||||
|
let (roles, groups) = user.get_roles_groups(&state.pool).await?;
|
||||||
|
|
||||||
|
let messages = DbMessage::get(&state.pool, Channel::ALGEMEEN, roles, groups).await?;
|
||||||
|
|
||||||
|
Ok(Json(convert_vec(messages)))
|
||||||
|
}
|
||||||
|
@@ -1,4 +1,7 @@
|
|||||||
|
mod bitflags;
|
||||||
|
pub mod cli;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
mod helpers;
|
mod helpers;
|
||||||
|
pub mod serve;
|
||||||
|
|
||||||
pub use helpers::convert_vec;
|
pub use helpers::convert_vec;
|
||||||
|
18
server/src/util/bitflags.rs
Normal file
18
server/src/util/bitflags.rs
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
#[macro_export]
|
||||||
|
macro_rules! bitflags_serde_impl {
|
||||||
|
($type:ident, $int_type:ident) => {
|
||||||
|
impl serde::Serialize for $type {
|
||||||
|
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||||
|
serializer.serialize_i64(self.bits() as i64)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'de> serde::Deserialize<'de> for $type {
|
||||||
|
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||||
|
let v: i64 = Deserialize::deserialize(deserializer)?;
|
||||||
|
|
||||||
|
Ok($type::from_bits_truncate(v as $int_type))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
73
server/src/util/cli.rs
Normal file
73
server/src/util/cli.rs
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
use clap::{Parser, Subcommand};
|
||||||
|
use sqlx::{Acquire, PgPool};
|
||||||
|
|
||||||
|
use crate::model::member::{Groups, Roles};
|
||||||
|
|
||||||
|
#[derive(Parser)]
|
||||||
|
#[command(version, about, long_about = None)]
|
||||||
|
struct Cli {
|
||||||
|
#[command(subcommand)]
|
||||||
|
command: Option<Commands>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Subcommand)]
|
||||||
|
enum Commands {
|
||||||
|
Serve,
|
||||||
|
CreateAdminMember,
|
||||||
|
SetMemberAdmin { relatiecode: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn parse(pool: PgPool) {
|
||||||
|
let cli = Cli::parse();
|
||||||
|
|
||||||
|
match &cli.command {
|
||||||
|
Some(Commands::Serve) => {
|
||||||
|
crate::util::serve::serve(pool).await;
|
||||||
|
}
|
||||||
|
Some(Commands::CreateAdminMember) => {
|
||||||
|
create_admin_member(&pool).await.unwrap();
|
||||||
|
}
|
||||||
|
Some(Commands::SetMemberAdmin {
|
||||||
|
relatiecode: member_id,
|
||||||
|
}) => {
|
||||||
|
set_member_admin(&pool, member_id).await.unwrap();
|
||||||
|
}
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_admin_member(pool: &PgPool) -> Result<(), sqlx::Error> {
|
||||||
|
use crate::database::model::Member as DbMember;
|
||||||
|
|
||||||
|
let member = DbMember {
|
||||||
|
member_id: "D000000".to_string(),
|
||||||
|
first_name: "Admin".to_string(),
|
||||||
|
full_name: "Admin Admin".to_string(),
|
||||||
|
registration_token: None,
|
||||||
|
diploma: None,
|
||||||
|
groups: Groups::empty(),
|
||||||
|
roles: Roles::ADMIN,
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut transaction = pool.begin().await?;
|
||||||
|
|
||||||
|
DbMember::insert_many(&mut transaction, vec![member]).await?;
|
||||||
|
|
||||||
|
transaction.commit().await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn set_member_admin(pool: &PgPool, id: &str) -> Result<(), sqlx::Error> {
|
||||||
|
sqlx::query!(
|
||||||
|
"
|
||||||
|
UPDATE ONLY members SET roles = $1 WHERE member_id = $2
|
||||||
|
",
|
||||||
|
Roles::ADMIN.bits() as i64,
|
||||||
|
id
|
||||||
|
)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
@@ -1,4 +1,3 @@
|
|||||||
use crate::auth::AuthError;
|
|
||||||
use axum::{
|
use axum::{
|
||||||
http::StatusCode,
|
http::StatusCode,
|
||||||
response::{IntoResponse, Response},
|
response::{IntoResponse, Response},
|
||||||
@@ -7,46 +6,77 @@ use axum::{
|
|||||||
|
|
||||||
#[derive(thiserror::Error, Debug)]
|
#[derive(thiserror::Error, Debug)]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
#[error("CSV error: {0}")]
|
#[error(transparent)]
|
||||||
Csv(#[from] csv::Error),
|
Csv(#[from] csv::Error),
|
||||||
|
|
||||||
#[error("Auth error: {0}")]
|
#[error(transparent)]
|
||||||
Auth(#[from] crate::auth::AuthError),
|
Auth(#[from] crate::auth::AuthError),
|
||||||
|
|
||||||
#[error("Database error: {0}")]
|
#[error(transparent)]
|
||||||
Database(#[from] sqlx::Error),
|
Sqlx(#[from] sqlx::Error),
|
||||||
|
|
||||||
#[error("Resource not found")]
|
#[error("resource not found")]
|
||||||
NotFound,
|
NotFound,
|
||||||
|
|
||||||
|
#[error("Invalid request, expected {expected:?}")]
|
||||||
|
BadRequest { expected: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
struct ErrorResponse {
|
||||||
|
code: &'static str,
|
||||||
|
description: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ErrorResponse {
|
||||||
|
fn new(code: &'static str, description: String) -> Self {
|
||||||
|
Self { code, description }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl IntoResponse for Error {
|
impl IntoResponse for Error {
|
||||||
fn into_response(self) -> Response {
|
fn into_response(self) -> Response {
|
||||||
tracing::error!("Error... {:?}", self);
|
let (status_code, code) = match self {
|
||||||
|
Self::Sqlx(ref err_kind) => match err_kind {
|
||||||
|
sqlx::Error::RowNotFound => (StatusCode::NOT_FOUND, "DATABASE_ROW_NOT_FOUND"),
|
||||||
|
sqlx::Error::Database(db_err) => match db_err.kind() {
|
||||||
|
sqlx::error::ErrorKind::UniqueViolation => {
|
||||||
|
(StatusCode::INTERNAL_SERVER_ERROR, "DATABASE_DUPLICATE")
|
||||||
|
}
|
||||||
|
_ => (StatusCode::INTERNAL_SERVER_ERROR, "DATABASE_ERROR"),
|
||||||
|
},
|
||||||
|
_ => (StatusCode::INTERNAL_SERVER_ERROR, "DATABASE_ERROR"),
|
||||||
|
},
|
||||||
|
|
||||||
let (status, error_message) = match self {
|
Self::Csv(ref err_kind) => match err_kind.kind() {
|
||||||
Error::Auth(AuthError::NoPermssions) => {
|
csv::ErrorKind::UnequalLengths { .. } => {
|
||||||
(StatusCode::UNAUTHORIZED, String::from("No permissions"))
|
(StatusCode::BAD_REQUEST, "CSV_INPUT_INVALID")
|
||||||
}
|
}
|
||||||
Error::Auth(AuthError::InvalidToken) => {
|
_ => (StatusCode::INTERNAL_SERVER_ERROR, "CSV_ERROR"),
|
||||||
(StatusCode::BAD_REQUEST, String::from("Invalid token"))
|
},
|
||||||
|
|
||||||
|
Self::Auth(ref err_kind) => match err_kind {
|
||||||
|
crate::auth::AuthError::NoPermssions => {
|
||||||
|
(StatusCode::FORBIDDEN, "AUTH_NO_PERMISSIONS")
|
||||||
}
|
}
|
||||||
Error::Auth(AuthError::Unexpected) => (
|
crate::auth::AuthError::Unauthorized => {
|
||||||
StatusCode::INTERNAL_SERVER_ERROR,
|
(StatusCode::UNAUTHORIZED, "AUTH_UNAUTHORIZED")
|
||||||
String::from("Unexpected error occured"),
|
}
|
||||||
),
|
crate::auth::AuthError::InvalidToken => {
|
||||||
Error::Csv(err) => (StatusCode::BAD_REQUEST, err.to_string()),
|
(StatusCode::BAD_REQUEST, "AUTH_INVALID_TOKEN")
|
||||||
Error::NotFound => (
|
}
|
||||||
StatusCode::BAD_REQUEST,
|
crate::auth::AuthError::InvalidPassword => {
|
||||||
String::from("Could not find resource"),
|
(StatusCode::BAD_REQUEST, "AUTH_INVALID_PASSWORD")
|
||||||
),
|
}
|
||||||
Error::Database(err) => (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()),
|
_ => (StatusCode::INTERNAL_SERVER_ERROR, "AUTH_ERROR"),
|
||||||
|
},
|
||||||
|
|
||||||
|
Self::BadRequest { .. } => (StatusCode::BAD_REQUEST, "INVALID_BODY"),
|
||||||
|
Self::NotFound => (StatusCode::NOT_FOUND, "NOT_FOUND"),
|
||||||
};
|
};
|
||||||
|
|
||||||
let body = Json(serde_json::json!({
|
let body = ErrorResponse::new(code, self.to_string());
|
||||||
"error": error_message
|
|
||||||
}));
|
|
||||||
|
|
||||||
(status, body).into_response()
|
(status_code, Json(body)).into_response()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
31
server/src/util/serve.rs
Normal file
31
server/src/util/serve.rs
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::Router;
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use tokio::{net::TcpListener, sync::Mutex};
|
||||||
|
|
||||||
|
use crate::routes::member::migrate::MigrationStore;
|
||||||
|
use crate::routes::routes;
|
||||||
|
use crate::AppState;
|
||||||
|
|
||||||
|
pub async fn serve(pool: PgPool) {
|
||||||
|
let migration_store = Arc::new(Mutex::new(MigrationStore::default()));
|
||||||
|
|
||||||
|
let app_state = AppState {
|
||||||
|
pool,
|
||||||
|
migration_store,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Serve app
|
||||||
|
let app = Router::new().nest("/v1", routes()).with_state(app_state);
|
||||||
|
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:3000")
|
||||||
|
.await
|
||||||
|
.expect("Error while initializing listener");
|
||||||
|
|
||||||
|
tracing::info!("Listening on {}", listener.local_addr().unwrap());
|
||||||
|
|
||||||
|
axum::serve(listener, app)
|
||||||
|
.await
|
||||||
|
.expect("Error while serving axum application");
|
||||||
|
}
|
Reference in New Issue
Block a user