Compare commits
5 Commits
main
...
4907055f3a
Author | SHA1 | Date | |
---|---|---|---|
4907055f3a
|
|||
b65ddacd37
|
|||
4e6943d3fd
|
|||
f2e7d9f431
|
|||
cd51cd539c
|
49
devenv.lock
49
devenv.lock
@@ -31,31 +31,10 @@
|
||||
"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": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
"git-hooks",
|
||||
"pre-commit-hooks",
|
||||
"nixpkgs"
|
||||
]
|
||||
},
|
||||
@@ -87,14 +66,32 @@
|
||||
"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": {
|
||||
"inputs": {
|
||||
"devenv": "devenv",
|
||||
"git-hooks": "git-hooks",
|
||||
"nixpkgs": "nixpkgs",
|
||||
"pre-commit-hooks": [
|
||||
"git-hooks"
|
||||
]
|
||||
"pre-commit-hooks": "pre-commit-hooks"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
2
server/.env
Normal file
2
server/.env
Normal file
@@ -0,0 +1,2 @@
|
||||
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
|
||||
|
222
server/Cargo.lock
generated
222
server/Cargo.lock
generated
@@ -47,68 +47,6 @@ dependencies = [
|
||||
"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]]
|
||||
name = "atoi"
|
||||
version = "2.0.0"
|
||||
@@ -188,7 +126,6 @@ dependencies = [
|
||||
"axum",
|
||||
"axum-core",
|
||||
"bytes",
|
||||
"cookie",
|
||||
"futures-util",
|
||||
"headers",
|
||||
"http",
|
||||
@@ -255,15 +192,6 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "blake2"
|
||||
version = "0.10.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
|
||||
dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
@@ -316,57 +244,10 @@ dependencies = [
|
||||
"iana-time-zone",
|
||||
"js-sys",
|
||||
"num-traits",
|
||||
"serde",
|
||||
"wasm-bindgen",
|
||||
"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]]
|
||||
name = "concurrent-queue"
|
||||
version = "2.5.0"
|
||||
@@ -382,17 +263,6 @@ version = "0.9.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
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]]
|
||||
name = "core-foundation-sys"
|
||||
version = "0.8.7"
|
||||
@@ -515,15 +385,6 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.3.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4"
|
||||
dependencies = [
|
||||
"powerfmt",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
@@ -1091,12 +952,6 @@ dependencies = [
|
||||
"hashbrown",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "is_terminal_polyfill"
|
||||
version = "1.70.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf"
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.14.0"
|
||||
@@ -1256,12 +1111,6 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-conv"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9"
|
||||
|
||||
[[package]]
|
||||
name = "num-integer"
|
||||
version = "0.1.46"
|
||||
@@ -1342,17 +1191,6 @@ dependencies = [
|
||||
"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]]
|
||||
name = "pem-rfc7468"
|
||||
version = "0.7.0"
|
||||
@@ -1407,12 +1245,6 @@ version = "0.3.31"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2"
|
||||
|
||||
[[package]]
|
||||
name = "powerfmt"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.20"
|
||||
@@ -1786,7 +1618,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6a007b6936676aa9ab40207cde35daab0a04b823be8ae004368c0793b96a61e0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"chrono",
|
||||
"crc",
|
||||
"crossbeam-queue",
|
||||
"either",
|
||||
@@ -1811,7 +1642,6 @@ dependencies = [
|
||||
"tokio-stream",
|
||||
"tracing",
|
||||
"url",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1864,7 +1694,6 @@ dependencies = [
|
||||
"bitflags",
|
||||
"byteorder",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"crc",
|
||||
"digest",
|
||||
"dotenvy",
|
||||
@@ -1893,7 +1722,6 @@ dependencies = [
|
||||
"stringprep",
|
||||
"thiserror",
|
||||
"tracing",
|
||||
"uuid",
|
||||
"whoami",
|
||||
]
|
||||
|
||||
@@ -1907,7 +1735,6 @@ dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bitflags",
|
||||
"byteorder",
|
||||
"chrono",
|
||||
"crc",
|
||||
"dotenvy",
|
||||
"etcetera",
|
||||
@@ -1932,7 +1759,6 @@ dependencies = [
|
||||
"stringprep",
|
||||
"thiserror",
|
||||
"tracing",
|
||||
"uuid",
|
||||
"whoami",
|
||||
]
|
||||
|
||||
@@ -1943,7 +1769,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f85ca71d3a5b24e64e1d08dd8fe36c6c95c339a896cc33068148906784620540"
|
||||
dependencies = [
|
||||
"atoi",
|
||||
"chrono",
|
||||
"flume",
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
@@ -1958,7 +1783,6 @@ dependencies = [
|
||||
"sqlx-core",
|
||||
"tracing",
|
||||
"url",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2062,37 +1886,6 @@ dependencies = [
|
||||
"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]]
|
||||
name = "tinystr"
|
||||
version = "0.7.6"
|
||||
@@ -2298,22 +2091,11 @@ version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
||||
|
||||
[[package]]
|
||||
name = "utf8parse"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "744018581f9a3454a9e15beb8a33b017183f1e7c0cd170232a2d1453b23a51c4"
|
||||
dependencies = [
|
||||
"getrandom 0.2.15",
|
||||
"rand 0.8.5",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "validator"
|
||||
@@ -2644,17 +2426,13 @@ dependencies = [
|
||||
name = "wrbapp_server"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"axum",
|
||||
"axum-extra",
|
||||
"bitflags",
|
||||
"chrono",
|
||||
"clap",
|
||||
"csv",
|
||||
"dotenvy",
|
||||
"itertools",
|
||||
"rand 0.9.0",
|
||||
"rand_chacha 0.9.0",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sqlx",
|
||||
|
@@ -6,28 +6,24 @@ edition = "2021"
|
||||
[dependencies]
|
||||
# Primary crates
|
||||
axum = { version = "0.8", features = [ "macros", "json" ] }
|
||||
axum-extra = { version = "0.10.0", features = [ "typed-header", "cookie" ] }
|
||||
axum-extra = { version = "0.10.0", features = [ "typed-header" ] }
|
||||
tokio = { version = "1.43", features = [ "rt-multi-thread", "macros" ] }
|
||||
sqlx = { version = "0.8", features = [ "runtime-tokio", "postgres", "uuid", "chrono" ] }
|
||||
sqlx = { version = "0.8", features = [ "runtime-tokio", "postgres" ] }
|
||||
|
||||
# Secondary crates
|
||||
csv = { version = "1.3" }
|
||||
serde = "1.0"
|
||||
dotenvy = "0.15.7"
|
||||
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
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = "0.3"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
uuid = { version = "1.12", features = ["v4", "fast-rng", "serde"] }
|
||||
chrono = "0.4.39"
|
||||
uuid = "1.12.0"
|
||||
serde_json = "1.0.137"
|
||||
rand = "0.9"
|
||||
rand_chacha = "0.9"
|
||||
thiserror = { version = "2.0" }
|
||||
itertools = "0.14"
|
||||
|
||||
|
@@ -1,10 +1,10 @@
|
||||
CREATE TABLE IF NOT EXISTS "members" (
|
||||
member_id varchar(7) NOT NULL PRIMARY KEY,
|
||||
first_name text NOT NULL,
|
||||
full_name text NOT NULL,
|
||||
registration_token text NOT NULL UNIQUE,
|
||||
create table "members" (
|
||||
id varchar(7) primary key,
|
||||
first_name text not null,
|
||||
full_name text not null,
|
||||
registration_token text unique not null,
|
||||
diploma text,
|
||||
groups bigint NOT NULL,
|
||||
roles bigint NOT NULL
|
||||
hours text[] not null,
|
||||
groups text[] not null
|
||||
);
|
||||
|
||||
|
@@ -1,13 +0,0 @@
|
||||
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)
|
||||
);
|
@@ -1,7 +0,0 @@
|
||||
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
|
||||
);
|
@@ -1,2 +0,0 @@
|
||||
ALTER TABLE users_members
|
||||
ADD UNIQUE (user_id, member_id);
|
@@ -1,20 +0,0 @@
|
||||
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)
|
||||
);
|
@@ -1,3 +0,0 @@
|
||||
ALTER TABLE messages
|
||||
ADD COLUMN member_groups bigint NOT NULL,
|
||||
ADD COLUMN member_roles bigint NOT NULL;
|
@@ -1 +0,0 @@
|
||||
ALTER TYPE message_status ADD VALUE 'draft';
|
@@ -1,85 +1,48 @@
|
||||
use argon2::{
|
||||
password_hash::{rand_core::OsRng, PasswordHasher, SaltString},
|
||||
Argon2, PasswordHash, PasswordVerifier,
|
||||
use std::collections::HashSet;
|
||||
|
||||
use axum::{extract::FromRequestParts, http::request::Parts, RequestPartsExt};
|
||||
use axum_extra::{
|
||||
headers::{authorization::Bearer, Authorization},
|
||||
typed_header::TypedHeaderRejectionReason,
|
||||
TypedHeader,
|
||||
};
|
||||
use axum::http::{header, HeaderMap};
|
||||
use chrono::Utc;
|
||||
use bearer::verify_bearer;
|
||||
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;
|
||||
|
||||
pub async fn get_user_from_header(pool: &PgPool, headers: &HeaderMap) -> Result<User, AuthError> {
|
||||
let token = get_token_from_headers(headers)?;
|
||||
#[derive(Debug)]
|
||||
pub struct Permissions<'a>(pub HashSet<&'a str>);
|
||||
|
||||
let session = match Session::from_token(pool, &token).await {
|
||||
Ok(s) => s,
|
||||
Err(_) => return Err(AuthError::InvalidToken),
|
||||
};
|
||||
// Middleware for getting permissions
|
||||
impl<S> FromRequestParts<S> for Permissions<'_>
|
||||
where
|
||||
S: Send + Sync,
|
||||
{
|
||||
type Rejection = crate::Error;
|
||||
|
||||
if session.expires_at < Utc::now() {
|
||||
return Err(AuthError::InvalidToken);
|
||||
}
|
||||
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 db_user = match crate::database::model::User::get(pool, session.user_id).await {
|
||||
Ok(u) => u,
|
||||
Err(_) => return Err(AuthError::InvalidToken),
|
||||
};
|
||||
let permissions = Permissions {
|
||||
0: HashSet::from(["root"]),
|
||||
};
|
||||
|
||||
Ok(db_user.into())
|
||||
}
|
||||
return Ok(permissions);
|
||||
}
|
||||
Err(err) => match err.reason() {
|
||||
TypedHeaderRejectionReason::Missing => (),
|
||||
TypedHeaderRejectionReason::Error(_err) => {
|
||||
return Err(AuthError::InvalidToken.into())
|
||||
}
|
||||
_ => return Err(AuthError::Unexpected.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),
|
||||
Err(AuthError::Unexpected.into())
|
||||
}
|
||||
}
|
||||
|
||||
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>()
|
||||
}
|
||||
|
8
server/src/auth/bearer.rs
Normal file
8
server/src/auth/bearer.rs
Normal file
@@ -0,0 +1,8 @@
|
||||
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,28 +5,16 @@ pub enum AuthError {
|
||||
NoPermssions,
|
||||
InvalidToken,
|
||||
Unexpected,
|
||||
InvalidPassword,
|
||||
Unauthorized,
|
||||
HashingFailed(String),
|
||||
}
|
||||
|
||||
impl Display for AuthError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::NoPermssions => write!(f, "No permissions"),
|
||||
Self::InvalidToken => write!(f, "Invalid token"),
|
||||
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),
|
||||
Self::NoPermssions => write!(f, "{}", "No permissions"),
|
||||
Self::InvalidToken => write!(f, "{}", "Invalid token"),
|
||||
Self::Unexpected => write!(f, "{}", "Unexpected error"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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,10 +1,5 @@
|
||||
pub mod member;
|
||||
pub mod message;
|
||||
pub mod session;
|
||||
pub mod user;
|
||||
|
||||
pub use member::Member;
|
||||
pub use message::Message;
|
||||
pub use session::Session;
|
||||
pub use user::User;
|
||||
pub use user::UserMember;
|
||||
|
@@ -2,34 +2,21 @@ use rand::distr::{Alphanumeric, SampleString};
|
||||
use sqlx::{PgPool, Postgres, QueryBuilder};
|
||||
use validator::Validate;
|
||||
|
||||
use crate::model::member::{Groups, Roles};
|
||||
|
||||
#[derive(Debug, Validate, sqlx::FromRow)]
|
||||
#[derive(Debug, Validate)]
|
||||
pub struct Member {
|
||||
#[validate(length(equal = 7))]
|
||||
pub member_id: String,
|
||||
pub id: String,
|
||||
pub first_name: String,
|
||||
pub full_name: String,
|
||||
pub registration_token: Option<String>,
|
||||
pub diploma: Option<String>,
|
||||
pub groups: Groups,
|
||||
pub roles: Roles,
|
||||
pub hours: Vec<String>,
|
||||
pub groups: Vec<String>,
|
||||
}
|
||||
|
||||
impl Member {
|
||||
pub async fn get_many_from_registration_tokens(
|
||||
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_many(transaction: &PgPool, members: Vec<Self>) -> Result<(), sqlx::Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_all(pool: &PgPool) -> Result<Vec<Self>, sqlx::Error> {
|
||||
@@ -44,24 +31,24 @@ impl Member {
|
||||
transaction: &mut sqlx::Transaction<'_, Postgres>,
|
||||
members: Vec<Self>,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
if members.is_empty() {
|
||||
if members.len() == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut query_builder = QueryBuilder::new(
|
||||
"INSERT INTO members(member_id, first_name, full_name, registration_token, diploma, groups, roles) "
|
||||
"INSERT INTO members(id, first_name, full_name, registration_token, diploma, hours, groups) "
|
||||
);
|
||||
|
||||
query_builder.push_values(members.into_iter(), |mut b, member| {
|
||||
let registration_token = Alphanumeric.sample_string(&mut rand::rng(), 16);
|
||||
|
||||
b.push_bind(member.member_id);
|
||||
b.push_bind(member.id);
|
||||
b.push_bind(member.first_name);
|
||||
b.push_bind(member.full_name);
|
||||
b.push_bind(registration_token);
|
||||
b.push_bind(member.diploma);
|
||||
b.push_bind(member.groups.bits() as i64);
|
||||
b.push_bind(member.roles.bits() as i64);
|
||||
b.push_bind(member.hours);
|
||||
b.push_bind(member.groups);
|
||||
});
|
||||
|
||||
let query = query_builder.build();
|
||||
@@ -74,26 +61,12 @@ impl Member {
|
||||
transaction: &mut sqlx::Transaction<'_, Postgres>,
|
||||
members: Vec<Self>,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
if members.is_empty() {
|
||||
if members.len() == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for member in members {
|
||||
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?;
|
||||
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?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -105,7 +78,7 @@ impl Member {
|
||||
) -> Result<(), sqlx::Error> {
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM members WHERE member_id = ANY($1)
|
||||
DELETE FROM members WHERE id = ANY($1)
|
||||
",
|
||||
member_ids
|
||||
)
|
||||
|
@@ -1,108 +0,0 @@
|
||||
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,96 +1,6 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use sqlx::{PgPool, Postgres};
|
||||
|
||||
#[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 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(())
|
||||
}
|
||||
struct Session {
|
||||
id: u32,
|
||||
user_id: u32,
|
||||
token: String,
|
||||
expires: chrono::NaiveDateTime,
|
||||
}
|
||||
|
@@ -1,217 +1,8 @@
|
||||
use sqlx::{PgPool, Postgres};
|
||||
|
||||
use crate::model::member::{Groups, Roles};
|
||||
|
||||
use super::Member as DbMember;
|
||||
|
||||
#[derive(validator::Validate)]
|
||||
pub struct User {
|
||||
pub user_id: uuid::Uuid,
|
||||
struct User {
|
||||
pub id: uuid::Uuid,
|
||||
#[validate(email)]
|
||||
pub email: String,
|
||||
pub password: Option<String>,
|
||||
pub password: String,
|
||||
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,7 +1,13 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::Router;
|
||||
use tokio::{net::TcpListener, sync::Mutex};
|
||||
use tracing::Level;
|
||||
use tracing_subscriber::FmtSubscriber;
|
||||
|
||||
use wrbapp_server::database;
|
||||
use wrbapp_server::routes::member::migrate::MigrationStore;
|
||||
use wrbapp_server::routes::routes;
|
||||
use wrbapp_server::{database, AppState};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
@@ -24,5 +30,23 @@ async fn main() {
|
||||
.await
|
||||
.expect("Database connection failed");
|
||||
|
||||
wrbapp_server::util::cli::parse(pool).await;
|
||||
let migration_store = Arc::new(Mutex::new(MigrationStore::default()));
|
||||
|
||||
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,8 +1,6 @@
|
||||
pub mod member;
|
||||
pub mod message;
|
||||
pub mod session;
|
||||
pub mod user;
|
||||
|
||||
pub use member::Member;
|
||||
pub use message::Message;
|
||||
pub use user::User;
|
||||
|
@@ -1,146 +1,32 @@
|
||||
use bitflags::bitflags;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct Name {
|
||||
pub first: String,
|
||||
pub full: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct Member {
|
||||
pub id: String,
|
||||
pub name: Name,
|
||||
pub registration_token: Option<String>,
|
||||
pub diploma: Option<String>,
|
||||
pub groups: Groups,
|
||||
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)
|
||||
}
|
||||
}
|
||||
pub hours: Vec<String>,
|
||||
pub groups: Vec<String>,
|
||||
}
|
||||
|
||||
use crate::database::model::Member as DbMember;
|
||||
impl From<DbMember> for Member {
|
||||
fn from(value: DbMember) -> Self {
|
||||
Member {
|
||||
id: value.member_id,
|
||||
id: value.id,
|
||||
name: Name {
|
||||
first: value.first_name,
|
||||
full: value.full_name,
|
||||
},
|
||||
registration_token: value.registration_token,
|
||||
diploma: value.diploma,
|
||||
hours: value.hours,
|
||||
groups: value.groups,
|
||||
roles: value.roles,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -148,13 +34,13 @@ impl From<DbMember> for Member {
|
||||
impl From<Member> for DbMember {
|
||||
fn from(value: Member) -> Self {
|
||||
DbMember {
|
||||
member_id: value.id,
|
||||
id: value.id,
|
||||
first_name: value.name.first,
|
||||
full_name: value.name.full,
|
||||
registration_token: None,
|
||||
diploma: value.diploma,
|
||||
hours: value.hours,
|
||||
groups: value.groups,
|
||||
roles: value.roles,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,136 +0,0 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,55 +0,0 @@
|
||||
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,80 +1,5 @@
|
||||
use serde::Serialize;
|
||||
use sqlx::PgPool;
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct User {
|
||||
pub id: uuid::Uuid,
|
||||
pub email: String,
|
||||
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,25 +1,30 @@
|
||||
use crate::{auth::get_user_from_header, model::User, AppState};
|
||||
use axum::{extract::State, http::HeaderMap, routing::get, Json, Router};
|
||||
use axum::{
|
||||
extract::State,
|
||||
http::StatusCode,
|
||||
routing::{get, post},
|
||||
Router,
|
||||
};
|
||||
use member::migrate::{migrate_confirm, migrate_request};
|
||||
|
||||
use crate::{auth::Permissions, AppState};
|
||||
|
||||
pub mod auth;
|
||||
pub mod member;
|
||||
pub mod message;
|
||||
pub mod user;
|
||||
|
||||
pub fn routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/", get(root))
|
||||
.merge(member::routes())
|
||||
.merge(auth::routes())
|
||||
.merge(user::routes())
|
||||
.merge(message::routes())
|
||||
// .route("/member/:id", get())
|
||||
.route("/members/migrate_request", post(migrate_request))
|
||||
.route("/members/migrate_confirm", post(migrate_confirm))
|
||||
}
|
||||
|
||||
async fn root(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<User>, crate::Error> {
|
||||
let user = get_user_from_header(&state.pool, &headers).await?;
|
||||
permissions: Permissions<'_>,
|
||||
) -> Result<String, (StatusCode, String)> {
|
||||
tracing::info!("{:?}", permissions);
|
||||
|
||||
Ok(Json(user))
|
||||
Ok("Hello world".to_string())
|
||||
}
|
||||
|
@@ -1,181 +1 @@
|
||||
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,28 +1 @@
|
||||
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 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,28 +1,25 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use axum::{extract::State, http::HeaderMap, Json};
|
||||
use axum::{extract::State, Json};
|
||||
use itertools::Itertools;
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::{
|
||||
auth::get_user_from_header,
|
||||
auth::{AuthError, Permissions},
|
||||
database::model::Member as DbMember,
|
||||
model::{
|
||||
member::{Groups, Name, Roles},
|
||||
Member,
|
||||
},
|
||||
model::{member::Name, Member},
|
||||
util::convert_vec,
|
||||
AppState,
|
||||
};
|
||||
|
||||
pub async fn migrate_request(
|
||||
pub async fn migrate_request<'a>(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
permissions: Permissions<'a>,
|
||||
body: String,
|
||||
) -> Result<Json<MigrationResponse>, crate::Error> {
|
||||
let user = get_user_from_header(&state.pool, &headers).await?;
|
||||
|
||||
user.authorize(&state.pool, Some(Roles::ADMIN), None)
|
||||
.await?;
|
||||
if !permissions.0.contains("root") {
|
||||
return Err(AuthError::NoPermssions.into());
|
||||
}
|
||||
|
||||
tracing::info!("Migration is requested");
|
||||
|
||||
@@ -45,24 +42,21 @@ pub async fn migrate_request(
|
||||
Ok(Json(MigrationResponse::from((count, members_diff))))
|
||||
}
|
||||
|
||||
pub async fn migrate_confirm(
|
||||
pub async fn migrate_confirm<'a>(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
permissions: Permissions<'a>,
|
||||
body: String,
|
||||
) -> Result<(), crate::Error> {
|
||||
let user = get_user_from_header(&state.pool, &headers).await?;
|
||||
user.authorize(&state.pool, Some(Roles::ADMIN), None)
|
||||
.await?;
|
||||
if !permissions.0.contains("root") {
|
||||
return Err(AuthError::NoPermssions.into());
|
||||
}
|
||||
|
||||
tracing::info!("Migration is confirmed");
|
||||
|
||||
// TODO: Implement better error naming
|
||||
let count = match body.trim().parse::<u32>() {
|
||||
Ok(c) => c,
|
||||
Err(_) => {
|
||||
return Err(crate::Error::BadRequest {
|
||||
expected: String::from("u32"),
|
||||
})
|
||||
}
|
||||
Err(_) => return Err(crate::Error::NotFound),
|
||||
};
|
||||
|
||||
let mut store = state.migration_store.lock().await;
|
||||
@@ -116,7 +110,7 @@ struct Row {
|
||||
#[serde(rename = "E-mail")]
|
||||
email: String,
|
||||
#[serde(rename = "Verenigingssporten")]
|
||||
groups: String,
|
||||
hours: String,
|
||||
#[serde(rename = "Diploma dropdown 1")]
|
||||
diploma: Option<String>,
|
||||
}
|
||||
@@ -136,12 +130,20 @@ pub struct MigrationResponse {
|
||||
remove: Vec<(String, Name)>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct MigrationStore {
|
||||
pub store: HashMap<u32, MembersDiff>,
|
||||
pub count: u32,
|
||||
}
|
||||
|
||||
impl Default for MigrationStore {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
count: 0,
|
||||
store: HashMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Row {
|
||||
fn from_csv_many(input: &str) -> Result<Vec<Self>, csv::Error> {
|
||||
let mut rdr = csv::ReaderBuilder::new()
|
||||
@@ -153,45 +155,45 @@ impl Row {
|
||||
members
|
||||
}
|
||||
|
||||
fn groups_parsed(&self) -> Groups {
|
||||
let mut groups: Vec<String> = Vec::new();
|
||||
fn hours_parsed(&self) -> Vec<String> {
|
||||
let mut hours: Vec<String> = Vec::new();
|
||||
|
||||
let group_parts: Vec<&str> = self.groups.split(", ").collect();
|
||||
let group_parts: Vec<&str> = self.hours.split(", ").collect();
|
||||
|
||||
for group in group_parts {
|
||||
let hour_parts: Vec<&str> = group.split(" - ").collect();
|
||||
|
||||
if let Some(group) = hour_parts.get(1) {
|
||||
groups.push(group.to_uppercase())
|
||||
for part in hour_parts {
|
||||
if &*part != "Groep" {
|
||||
hours.push(part.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let groups_string = groups.join("|");
|
||||
|
||||
bitflags::parser::from_str(&groups_string).unwrap_or(Groups::empty())
|
||||
hours.into_iter().unique().collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Row> for Name {
|
||||
fn from(val: Row) -> Self {
|
||||
impl Into<Name> for Row {
|
||||
fn into(self) -> Name {
|
||||
Name {
|
||||
first: val.first_name,
|
||||
first: self.first_name,
|
||||
full: "Temporarely full name".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Row> for Member {
|
||||
fn from(val: Row) -> Self {
|
||||
let name: Name = val.clone().into();
|
||||
impl Into<Member> for Row {
|
||||
fn into(self) -> Member {
|
||||
let name: Name = self.clone().into();
|
||||
|
||||
Member {
|
||||
id: val.id.clone(),
|
||||
id: self.id.clone(),
|
||||
name,
|
||||
registration_token: None,
|
||||
diploma: val.diploma.clone(),
|
||||
groups: val.groups_parsed(),
|
||||
roles: Roles::MEMBER,
|
||||
diploma: self.diploma.clone(),
|
||||
hours: self.hours_parsed(),
|
||||
groups: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -253,8 +255,8 @@ fn generate_diff(members_new: Vec<Member>, members_old: Vec<Member>) -> MembersD
|
||||
name: new_member.name.clone(),
|
||||
registration_token: old_member.registration_token,
|
||||
diploma: new_member.diploma.clone(),
|
||||
groups: new_member.groups,
|
||||
roles: old_member.roles,
|
||||
hours: new_member.hours.clone(),
|
||||
groups: old_member.groups,
|
||||
})
|
||||
} else {
|
||||
members_remove.push(old_member);
|
||||
|
@@ -1,87 +0,0 @@
|
||||
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,91 +1 @@
|
||||
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,7 +1,4 @@
|
||||
mod bitflags;
|
||||
pub mod cli;
|
||||
pub mod error;
|
||||
mod helpers;
|
||||
pub mod serve;
|
||||
|
||||
pub use helpers::convert_vec;
|
||||
|
@@ -1,18 +0,0 @@
|
||||
#[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))
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
@@ -1,73 +0,0 @@
|
||||
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,3 +1,4 @@
|
||||
use crate::auth::AuthError;
|
||||
use axum::{
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
@@ -6,77 +7,46 @@ use axum::{
|
||||
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
pub enum Error {
|
||||
#[error(transparent)]
|
||||
#[error("CSV error: {0}")]
|
||||
Csv(#[from] csv::Error),
|
||||
|
||||
#[error(transparent)]
|
||||
#[error("Auth error: {0}")]
|
||||
Auth(#[from] crate::auth::AuthError),
|
||||
|
||||
#[error(transparent)]
|
||||
Sqlx(#[from] sqlx::Error),
|
||||
#[error("Database error: {0}")]
|
||||
Database(#[from] sqlx::Error),
|
||||
|
||||
#[error("resource not found")]
|
||||
#[error("Resource not found")]
|
||||
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 {
|
||||
fn into_response(self) -> Response {
|
||||
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"),
|
||||
},
|
||||
tracing::error!("Error... {:?}", self);
|
||||
|
||||
Self::Csv(ref err_kind) => match err_kind.kind() {
|
||||
csv::ErrorKind::UnequalLengths { .. } => {
|
||||
(StatusCode::BAD_REQUEST, "CSV_INPUT_INVALID")
|
||||
}
|
||||
_ => (StatusCode::INTERNAL_SERVER_ERROR, "CSV_ERROR"),
|
||||
},
|
||||
|
||||
Self::Auth(ref err_kind) => match err_kind {
|
||||
crate::auth::AuthError::NoPermssions => {
|
||||
(StatusCode::FORBIDDEN, "AUTH_NO_PERMISSIONS")
|
||||
}
|
||||
crate::auth::AuthError::Unauthorized => {
|
||||
(StatusCode::UNAUTHORIZED, "AUTH_UNAUTHORIZED")
|
||||
}
|
||||
crate::auth::AuthError::InvalidToken => {
|
||||
(StatusCode::BAD_REQUEST, "AUTH_INVALID_TOKEN")
|
||||
}
|
||||
crate::auth::AuthError::InvalidPassword => {
|
||||
(StatusCode::BAD_REQUEST, "AUTH_INVALID_PASSWORD")
|
||||
}
|
||||
_ => (StatusCode::INTERNAL_SERVER_ERROR, "AUTH_ERROR"),
|
||||
},
|
||||
|
||||
Self::BadRequest { .. } => (StatusCode::BAD_REQUEST, "INVALID_BODY"),
|
||||
Self::NotFound => (StatusCode::NOT_FOUND, "NOT_FOUND"),
|
||||
let (status, error_message) = match self {
|
||||
Error::Auth(AuthError::NoPermssions) => {
|
||||
(StatusCode::UNAUTHORIZED, String::from("No permissions"))
|
||||
}
|
||||
Error::Auth(AuthError::InvalidToken) => {
|
||||
(StatusCode::BAD_REQUEST, String::from("Invalid token"))
|
||||
}
|
||||
Error::Auth(AuthError::Unexpected) => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
String::from("Unexpected error occured"),
|
||||
),
|
||||
Error::Csv(err) => (StatusCode::BAD_REQUEST, err.to_string()),
|
||||
Error::NotFound => (
|
||||
StatusCode::BAD_REQUEST,
|
||||
String::from("Could not find resource"),
|
||||
),
|
||||
Error::Database(err) => (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()),
|
||||
};
|
||||
|
||||
let body = ErrorResponse::new(code, self.to_string());
|
||||
let body = Json(serde_json::json!({
|
||||
"error": error_message
|
||||
}));
|
||||
|
||||
(status_code, Json(body)).into_response()
|
||||
(status, body).into_response()
|
||||
}
|
||||
}
|
||||
|
@@ -1,31 +0,0 @@
|
||||
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