Compare commits

..

12 Commits

42 changed files with 1530 additions and 68 deletions

View File

@@ -1 +1,2 @@
DATABASE_URL="postgres://postgres:postgres@127.0.0.1:5432/persmgr"" [env]
DATABASE_URL="postgres://postgres:postgres@127.0.0.1:5432/persmgr"

4
.gitignore vendored
View File

@@ -1,4 +1,2 @@
/target /target
package-lock.json /persmgr_derive/target
node_modules/
build/

116
Cargo.lock generated
View File

@@ -83,7 +83,7 @@ dependencies = [
"rustc-hash", "rustc-hash",
"serde", "serde",
"serde_derive", "serde_derive",
"syn", "syn 2.0.106",
] ]
[[package]] [[package]]
@@ -122,7 +122,7 @@ checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.106",
] ]
[[package]] [[package]]
@@ -153,6 +153,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "021e862c184ae977658b36c4500f7feac3221ca5da43e3f25bd04ab6c79a29b5" checksum = "021e862c184ae977658b36c4500f7feac3221ca5da43e3f25bd04ab6c79a29b5"
dependencies = [ dependencies = [
"axum-core", "axum-core",
"axum-macros",
"bytes", "bytes",
"form_urlencoded", "form_urlencoded",
"futures-util", "futures-util",
@@ -200,6 +201,17 @@ dependencies = [
"tracing", "tracing",
] ]
[[package]]
name = "axum-macros"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "604fde5e028fea851ce1d8570bbdc034bec850d157f7569d10f347d06808c05c"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.106",
]
[[package]] [[package]]
name = "backtrace" name = "backtrace"
version = "0.3.75" version = "0.3.75"
@@ -404,6 +416,41 @@ dependencies = [
"typenum", "typenum",
] ]
[[package]]
name = "darling"
version = "0.13.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a01d95850c592940db9b8194bc39f4bc0e89dee5c4265e4b1807c34a9aba453c"
dependencies = [
"darling_core",
"darling_macro",
]
[[package]]
name = "darling_core"
version = "0.13.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "859d65a907b6852c9361e3185c862aae7fafd2887876799fa55f5f99dc40d610"
dependencies = [
"fnv",
"ident_case",
"proc-macro2",
"quote",
"strsim",
"syn 1.0.109",
]
[[package]]
name = "darling_macro"
version = "0.13.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c972679f83bdf9c42bd905396b6c3588a843a17f0f16dfcfa3e2c5d57441835"
dependencies = [
"darling_core",
"quote",
"syn 1.0.109",
]
[[package]] [[package]]
name = "der" name = "der"
version = "0.7.10" version = "0.7.10"
@@ -445,7 +492,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.106",
] ]
[[package]] [[package]]
@@ -605,7 +652,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.106",
] ]
[[package]] [[package]]
@@ -929,6 +976,12 @@ dependencies = [
"zerovec", "zerovec",
] ]
[[package]]
name = "ident_case"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]] [[package]]
name = "idna" name = "idna"
version = "1.1.0" version = "1.1.0"
@@ -1271,6 +1324,8 @@ dependencies = [
"askama", "askama",
"axum", "axum",
"base64", "base64",
"cfg-if",
"persmgr_derive",
"pulldown-cmark", "pulldown-cmark",
"rand 0.9.2", "rand 0.9.2",
"serde", "serde",
@@ -1288,6 +1343,16 @@ dependencies = [
"tracing-subscriber", "tracing-subscriber",
] ]
[[package]]
name = "persmgr_derive"
version = "0.1.0"
dependencies = [
"darling",
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]] [[package]]
name = "pin-project-lite" name = "pin-project-lite"
version = "0.2.16" version = "0.2.16"
@@ -1529,7 +1594,7 @@ checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.106",
] ]
[[package]] [[package]]
@@ -1732,7 +1797,7 @@ dependencies = [
"quote", "quote",
"sqlx-core", "sqlx-core",
"sqlx-macros-core", "sqlx-macros-core",
"syn", "syn 2.0.106",
] ]
[[package]] [[package]]
@@ -1755,7 +1820,7 @@ dependencies = [
"sqlx-mysql", "sqlx-mysql",
"sqlx-postgres", "sqlx-postgres",
"sqlx-sqlite", "sqlx-sqlite",
"syn", "syn 2.0.106",
"tokio", "tokio",
"url", "url",
] ]
@@ -1880,12 +1945,29 @@ dependencies = [
"unicode-properties", "unicode-properties",
] ]
[[package]]
name = "strsim"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]] [[package]]
name = "subtle" name = "subtle"
version = "2.6.1" version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "syn"
version = "1.0.109"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]] [[package]]
name = "syn" name = "syn"
version = "2.0.106" version = "2.0.106"
@@ -1911,7 +1993,7 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.106",
] ]
[[package]] [[package]]
@@ -1931,7 +2013,7 @@ checksum = "6c5e1be1c48b9172ee610da68fd9cd2770e7a4056cb3fc98710ee6906f0c7960"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.106",
] ]
[[package]] [[package]]
@@ -2026,7 +2108,7 @@ checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.106",
] ]
[[package]] [[package]]
@@ -2256,7 +2338,7 @@ checksum = "81383ab64e72a7a8b8e13130c49e3dab29def6d0c7d76a03087b3cf71c5c6903"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.106",
] ]
[[package]] [[package]]
@@ -2429,7 +2511,7 @@ dependencies = [
"log", "log",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.106",
"wasm-bindgen-shared", "wasm-bindgen-shared",
] ]
@@ -2451,7 +2533,7 @@ checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.106",
"wasm-bindgen-backend", "wasm-bindgen-backend",
"wasm-bindgen-shared", "wasm-bindgen-shared",
] ]
@@ -2664,7 +2746,7 @@ checksum = "38da3c9736e16c5d3c8c597a9aaa5d1fa565d0532ae05e27c24aa62fb32c0ab6"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.106",
"synstructure", "synstructure",
] ]
@@ -2685,7 +2767,7 @@ checksum = "9ecf5b4cc5364572d7f4c329661bcc82724222973f2cab6f050a4e5c22f75181"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.106",
] ]
[[package]] [[package]]
@@ -2705,7 +2787,7 @@ checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.106",
"synstructure", "synstructure",
] ]
@@ -2745,7 +2827,7 @@ checksum = "5b96237efa0c878c64bd89c436f661be4e46b2f3eff1ebb976f7ef2321d2f58f"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.106",
] ]
[[package]] [[package]]

View File

@@ -4,11 +4,14 @@ version = "0.1.0"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
persmgr_derive.path="./persmgr_derive"
anyhow = "1.0.99" anyhow = "1.0.99"
argon2 = { version = "0.5.3", features = ["simple", "std"] } argon2 = { version = "0.5.3", features = ["simple", "std"] }
askama = "0.14.0" askama = "0.14.0"
axum = "0.8.4" axum = { version = "0.8.4", features = ["macros"] }
base64 = "0.22.1" base64 = "0.22.1"
cfg-if = "1.0.3"
pulldown-cmark = "0.13.0" pulldown-cmark = "0.13.0"
rand = "0.9.2" rand = "0.9.2"
serde = { version = "1.0.219", features = ["derive"] } serde = { version = "1.0.219", features = ["derive"] }

View File

@@ -1,3 +0,0 @@
-- Add down migration script here
DROP TABLE IF EXISTS users;

View File

@@ -1,12 +0,0 @@
-- Add up migration script here
CREATE TABLE IF NOT EXISTS users (
id BIGSERIAL PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
verified_email BOOLEAN NOT NULL,
username TEXT NOT NULL UNIQUE,
pw_hash TEXT NOT NULL,
pw_salt TEXT NOT NULL,
pfp_id BIGINT NOT NULL
);

View File

@@ -1,3 +0,0 @@
-- Add down migration script here
DROP TABLE IF EXISTS sessions;

View File

@@ -1,7 +0,0 @@
-- Add up migration script here
CREATE TABLE IF NOT EXISTS sessions (
user_id BIGINT NOT NULL,
session_key TEXT NOT NULL UNIQUE,
expires BIGINT NOT NULL
)

View File

@@ -0,0 +1,14 @@
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS sessions;
DROP TABLE IF EXISTS ranks;
DROP TABLE IF EXISTS awards;
DROP TABLE IF EXISTS trainings;
DROP TABLE IF EXISTS missions;
DROP TABLE IF EXISTS qualifications;
DROP TABLE IF EXISTS record_ranks;
DROP TABLE IF EXISTS record_awards;
DROP TABLE IF EXISTS record_training;
DROP TABLE IF EXISTS record_qualifications;
DROP TABLE IF EXISTS records_missions;
DROP TABLE IF EXISTS attendance;
DROP TABLE IF EXISTS roster_groups;

View File

@@ -0,0 +1,148 @@
CREATE TABLE IF NOT EXISTS users (
id BIGSERIAL PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
verified_email BOOLEAN NOT NULL,
username TEXT NOT NULL UNIQUE,
pw_hash TEXT NOT NULL,
pw_salt TEXT NOT NULL,
pfp_id BIGINT NOT NULL,
rank_id BIGINT NOT NULL,
group_id BIGINT NOT NULL
-- NOTE: Constraint added later to deal with circular dependency
-- CONSTRAINT fk_group FOREIGN KEY (group_id) REFERENCES roster_group(id)
-- CONSTRAINT fk_rank FOREIGN KEY (rank_id) REFERENCES ranks(id)
);
CREATE TABLE IF NOT EXISTS sessions (
id BIGSERIAL NOT NULL PRIMARY KEY,
user_id BIGINT NOT NULL,
session_key TEXT NOT NULL UNIQUE,
expires BIGINT NOT NULL,
CONSTRAINT fk_user FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS ranks (
id BIGSERIAL PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
description TEXT NOT NULL,
created_at BIGINT NOT NULL,
modified_at BIGINT NOT NULL
);
CREATE TABLE IF NOT EXISTS awards (
id BIGSERIAL PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
description TEXT NOT NULL,
created_at BIGINT NOT NULL,
modified_at BIGINT NOT NULL
);
CREATE TABLE IF NOT EXISTS trainings (
id BIGSERIAL PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
description TEXT NOT NULL,
created_at BIGINT NOT NULL,
modified_at BIGINT NOT NULL
);
CREATE TABLE IF NOT EXISTS missions (
id BIGSERIAL PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
description TEXT NOT NULL,
starting_at BIGINT NOT NULL,
estimated_length BIGINT NOT NULL,
created_at BIGINT NOT NULL,
modified_at BIGINT NOT NULL
);
CREATE TABLE IF NOT EXISTS qualifications (
id BIGSERIAL PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
description TEXT NOT NULL,
created_at BIGINT NOT NULL,
modified_at BIGINT NOT NULL
);
CREATE TABLE IF NOT EXISTS attendance (
id BIGSERIAL PRIMARY KEY NOT NULL,
user_id BIGINT NOT NULL,
mission_id BIGINT NOT NULL,
confirmed_at BIGINT NOT NULL,
attending BOOL NOT NULL,
CONSTRAINT fk_user FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE SET NULL,
CONSTRAINT fk_mission FOREIGN KEY(mission_id) REFERENCES missions(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS roster_groups (
id BIGSERIAL NOT NULL PRIMARY KEY,
name TEXT NOT NULL,
sort_order BIGINT NOT NULL,
manager_id BIGINT NOT NULL,
CONSTRAINT fk_manager FOREIGN KEY(manager_id) REFERENCES users(id) ON DELETE SET NULL
);
-- NOTE: For table 'users'
ALTER TABLE users ADD FOREIGN KEY (group_id) REFERENCES roster_groups(id) ON DELETE SET NULL;
ALTER TABLE users ADD FOREIGN KEY (rank_id) REFERENCES ranks(id) ON DELETE SET NULL;
--------------------
-- NOTE: Records
--------------------
CREATE TABLE IF NOT EXISTS records_ranks (
id BIGSERIAL PRIMARY KEY NOT NULL,
user_id BIGINT NOT NULL,
rank_id BIGINT NOT NULL,
author_id BIGINT NOT NULL,
created_at BIGINT NOT NULL,
CONSTRAINT fk_user FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
CONSTRAINT fk_author FOREIGN KEY(author_id) REFERENCES users(id) ON DELETE SET NULL,
CONSTRAINT fk_rank FOREIGN KEY (rank_id) REFERENCES ranks(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS records_awards (
id BIGSERIAL PRIMARY KEY NOT NULL,
user_id BIGINT NOT NULL,
award_id BIGINT NOT NULL,
author_id BIGINT NOT NULL,
created_at BIGINT NOT NULL,
CONSTRAINT fk_user FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
CONSTRAINT fk_author FOREIGN KEY(author_id) REFERENCES users(id) ON DELETE SET NULL,
CONSTRAINT fk_award FOREIGN KEY (award_id) REFERENCES awards(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS records_trainings (
id BIGSERIAL PRIMARY KEY NOT NULL,
user_id BIGINT NOT NULL,
training_id BIGINT NOT NULL,
author_id BIGINT NOT NULL,
created_at BIGINT NOT NULL,
CONSTRAINT fk_user FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
CONSTRAINT fk_author FOREIGN KEY(author_id) REFERENCES users(id) ON DELETE SET NULL,
CONSTRAINT fk_training FOREIGN KEY (training_id) REFERENCES trainings(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS records_qualifications (
id BIGSERIAL PRIMARY KEY NOT NULL,
user_id BIGINT NOT NULL,
qualification_id BIGINT NOT NULL,
author_id BIGINT NOT NULL,
created_at BIGINT NOT NULL,
CONSTRAINT fk_user FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
CONSTRAINT fk_author FOREIGN KEY(author_id) REFERENCES users(id) ON DELETE SET NULL,
CONSTRAINT fk_qualification FOREIGN KEY (qualification_id) REFERENCES qualifications(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS records_missions (
id BIGSERIAL PRIMARY KEY NOT NULL,
user_id BIGINT NOT NULL,
mission_id BIGINT NOT NULL,
author_id BIGINT NOT NULL,
created_at BIGINT NOT NULL,
CONSTRAINT fk_user FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
CONSTRAINT fk_author FOREIGN KEY(author_id) REFERENCES users(id) ON DELETE SET NULL,
CONSTRAINT fk_mission FOREIGN KEY (mission_id) REFERENCES missions(id) ON DELETE CASCADE
);

101
persmgr_derive/Cargo.lock generated Normal file
View File

@@ -0,0 +1,101 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "darling"
version = "0.13.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a01d95850c592940db9b8194bc39f4bc0e89dee5c4265e4b1807c34a9aba453c"
dependencies = [
"darling_core",
"darling_macro",
]
[[package]]
name = "darling_core"
version = "0.13.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "859d65a907b6852c9361e3185c862aae7fafd2887876799fa55f5f99dc40d610"
dependencies = [
"fnv",
"ident_case",
"proc-macro2",
"quote",
"strsim",
"syn",
]
[[package]]
name = "darling_macro"
version = "0.13.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c972679f83bdf9c42bd905396b6c3588a843a17f0f16dfcfa3e2c5d57441835"
dependencies = [
"darling_core",
"quote",
"syn",
]
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "ident_case"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]]
name = "persmgr_derive"
version = "0.1.0"
dependencies = [
"darling",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "proc-macro2"
version = "1.0.101"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
dependencies = [
"proc-macro2",
]
[[package]]
name = "strsim"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]]
name = "syn"
version = "1.0.109"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d"

13
persmgr_derive/Cargo.toml Normal file
View File

@@ -0,0 +1,13 @@
[package]
name = "persmgr_derive"
version = "0.1.0"
edition = "2024"
[lib]
proc-macro = true
[dependencies]
quote = "1"
proc-macro2 = "1"
syn = { version = "1", features = ["full"] }
darling = "0.13"

106
persmgr_derive/src/lib.rs Normal file
View File

@@ -0,0 +1,106 @@
use darling::FromDeriveInput;
use proc_macro::{self, TokenStream};
use quote::quote;
use syn::{Data, Expr, Fields, Type, parse_macro_input};
#[derive(FromDeriveInput, Default)]
#[darling(default, attributes(meta))]
struct Opts {
table: String,
key_t: Option<Expr>,
}
#[proc_macro_derive(TableMeta, attributes(meta))]
pub fn derive_table_meta(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input);
let opts = Opts::from_derive_input(&input)
.expect("Expected attribute #[meta(table=\"users\", key_t=i32)]");
let mut struct_items = Vec::new();
if let Data::Struct(data) = &input.data {
if let Fields::Named(fields) = &data.fields {
for field in &fields.named {
let ident = field.ident.as_ref().unwrap();
let s = ident.to_string();
if s.as_str() == "id" || s.as_str() == "created_at" {
continue;
}
let mut should_deref = false;
if let Type::Path(tp) = &field.ty {
if tp.path.segments.first().unwrap().ident == "ForeignKey" {
should_deref = true;
}
}
struct_items.push((ident, should_deref));
}
}
}
let ident = input.ident;
let table_name = opts.table;
let key_t = opts
.key_t
.unwrap_or_else(|| syn::parse_str::<Expr>("i64").unwrap());
// dbg!(&table_name);
//dbg!(&key_t);
let mut query = format!("UPDATE {table_name} SET ");
let mut query_args = quote!(self.id);
let mut i = 2;
let mut modified_update = false;
for (item, should_deref) in &struct_items {
let s = item.to_string();
//dbg!(&s);
if s.as_str() == "modified_at" {
modified_update = true;
}
if i != 2 {
query.push_str(", ");
}
query.push_str(s.as_str());
query.push_str(&format!(" = ${i} "));
i += 1;
let deref = if *should_deref { quote!(*) } else { quote!() };
query_args = quote! {
#query_args, #deref self.#item
};
}
query.push_str("WHERE id = $1 RETURNING *");
let mut modified_at = quote! {};
if modified_update {
modified_at = quote! {
self.modified_at = time::OffsetDateTime::now_utc().unix_timestamp();
}
}
let output = quote! {
impl TableMeta for #ident {
type PrimaryKey = #key_t;
const TABLE: &'static str = #table_name;
async fn update(&mut self, pool: &crate::db::CurrPool) -> anyhow::Result<Self> {
#modified_at
let session = sqlx::query_as!(
#ident,
#query,
#query_args
)
.fetch_one(pool)
.await?;
Ok(session)
}
}
};
// eprintln!("{}", output.to_string());
output.into()
}

28
src/api/files/create.rs Normal file
View File

@@ -0,0 +1,28 @@
use axum::{
extract::State,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde::Deserialize;
use crate::db::Database;
#[derive(Debug, Deserialize)]
pub struct Data {
path: String,
}
#[axum::debug_handler]
pub async fn route(State(_db): State<Database>) -> impl IntoResponse {
if false {
return Response::builder()
.status(StatusCode::NOT_FOUND)
.body(String::new())
.unwrap();
}
Response::builder()
.status(StatusCode::OK)
.body(String::new())
.unwrap()
}

28
src/api/files/delete.rs Normal file
View File

@@ -0,0 +1,28 @@
use axum::{
extract::State,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde::Deserialize;
use crate::db::Database;
#[derive(Debug, Deserialize)]
pub struct Data {
id: String,
}
#[axum::debug_handler]
pub async fn route(State(db): State<Database>) -> impl IntoResponse {
if false {
return Response::builder()
.status(StatusCode::NOT_FOUND)
.body(String::new())
.unwrap();
}
Response::builder()
.status(StatusCode::OK)
.body(String::new())
.unwrap()
}

28
src/api/files/get_file.rs Normal file
View File

@@ -0,0 +1,28 @@
use axum::{
extract::State,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde::Deserialize;
use crate::db::Database;
#[derive(Debug, Deserialize)]
pub struct Data {
id: String,
}
#[axum::debug_handler]
pub async fn route(State(db): State<Database>) -> impl IntoResponse {
if false {
return Response::builder()
.status(StatusCode::NOT_FOUND)
.body(String::new())
.unwrap();
}
Response::builder()
.status(StatusCode::OK)
.body(String::new())
.unwrap()
}

28
src/api/files/mkdir.rs Normal file
View File

@@ -0,0 +1,28 @@
use axum::{
extract::State,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde::Deserialize;
use crate::db::Database;
#[derive(Debug, Deserialize)]
pub struct Data {
id: String,
}
#[axum::debug_handler]
pub async fn route(State(db): State<Database>) -> impl IntoResponse {
if false {
return Response::builder()
.status(StatusCode::NOT_FOUND)
.body(String::new())
.unwrap();
}
Response::builder()
.status(StatusCode::OK)
.body(String::new())
.unwrap()
}

21
src/api/files/mod.rs Normal file
View File

@@ -0,0 +1,21 @@
use axum::{
Router,
routing::{get, post},
};
use crate::db::Database;
mod create;
mod delete;
mod get_file;
mod mkdir;
mod rmdir;
pub fn register_routes() -> Router<Database> {
Router::new()
.route("/file/upload", post(create::route))
.route("/file/get", get(get_file::route))
.route("/file/delete", get(delete::route))
.route("/dir/create", get(mkdir::route))
.route("/dir/remove", get(rmdir::route))
}

28
src/api/files/rmdir.rs Normal file
View File

@@ -0,0 +1,28 @@
use axum::{
extract::State,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde::Deserialize;
use crate::db::Database;
#[derive(Debug, Deserialize)]
pub struct Data {
id: String,
}
#[axum::debug_handler]
pub async fn route(State(db): State<Database>) -> impl IntoResponse {
if false {
return Response::builder()
.status(StatusCode::NOT_FOUND)
.body(String::new())
.unwrap();
}
Response::builder()
.status(StatusCode::OK)
.body(String::new())
.unwrap()
}

View File

@@ -1,16 +1,18 @@
use crate::db::Database; use crate::db::Database;
use axum::{Router, extract::State, http::StatusCode, routing::get}; use axum::{Router, extract::State, http::StatusCode, routing::get};
pub mod files;
pub mod user; pub mod user;
async fn root(State(state): State<Database>) -> (StatusCode, &'static str) { async fn root(State(_state): State<Database>) -> (StatusCode, &'static str) {
(StatusCode::OK, "We Good twin :3c") (StatusCode::OK, "We Good twin :3c")
} }
pub fn register_routes() -> Router<Database> { pub fn register_routes() -> Router<Database> {
let router = Router::new() let router = Router::new()
.route("/", get(root)) .route("/", get(root))
.nest("/user", user::register_routes()); .nest("/user", user::register_routes())
.nest("/files", files::register_routes());
Router::new().nest("/api", router) Router::new().nest("/api", router)
} }

View File

@@ -1,9 +1,4 @@
use axum::{ use axum::{body::Body, extract::State, http::StatusCode, response::Response};
body::Body,
extract::State,
http::{HeaderMap, HeaderValue, StatusCode},
response::{IntoResponse, Response},
};
use crate::db::Database; use crate::db::Database;

View File

@@ -1,7 +1,4 @@
use axum::{ use axum::{Router, routing::post};
Router,
routing::{get, post},
};
use crate::db::Database; use crate::db::Database;
@@ -9,7 +6,10 @@ pub mod login;
pub mod register; pub mod register;
pub fn register_routes() -> Router<Database> { pub fn register_routes() -> Router<Database> {
let sub_methods = Router::new();
// .route("/awards", method_router);
Router::new() Router::new()
.route("/register", post(register::route)) .route("/register", post(register::route))
.route("/login", post(login::route)) .route("/login", post(login::route))
.nest("/{id}", sub_methods)
} }

82
src/db/auth.rs Normal file
View File

@@ -0,0 +1,82 @@
use anyhow::bail;
use axum::{
http::{Response, StatusCode},
response::{Html, IntoResponse},
};
use crate::db::{
Database,
tables::{sessions::Session, user::User},
};
pub enum AuthResultApi<R: Default> {
Ok(User),
Error(Response<R>),
}
pub enum AuthResultWeb {
Ok(User),
Error((StatusCode, Html<String>)),
}
#[derive(Debug)]
pub struct Auth;
impl Auth {
pub async fn check_auth(
db: &Database,
session: tower_sessions::Session,
token: &String,
) -> anyhow::Result<User> {
let mut user_session: crate::Session = session
.get(crate::Session::KEY)
.await
.unwrap()
.unwrap_or_default();
if let Some(uid) = user_session.user_id {
return Ok(User::get_by_id(db.pool(), uid).await?);
}
if let Ok(session_token) = Session::get_by_session_key(db.pool(), token).await {
user_session.user_id = Some(session_token.user_id);
session
.insert(crate::Session::KEY, user_session)
.await
.unwrap();
return Ok(User::get_by_id(db.pool(), session_token.user_id).await?);
}
bail!("Unable to find user by this token")
}
pub async fn check_auth_api<R: Default>(
db: &Database,
session: tower_sessions::Session,
token: &String,
) -> AuthResultApi<R> {
match Self::check_auth(db, session, token).await {
Ok(r) => AuthResultApi::Ok(r),
Err(_) => AuthResultApi::Error(
Response::builder()
.status(StatusCode::UNAUTHORIZED)
.header("Location", "/")
.body(R::default())
.unwrap(),
),
}
}
pub async fn check_auth_web<R: Default>(
db: &Database,
session: tower_sessions::Session,
token: &String,
) -> AuthResultWeb {
match Self::check_auth(db, session, token).await {
Ok(r) => AuthResultWeb::Ok(r),
Err(_) => {
AuthResultWeb::Error((StatusCode::UNAUTHORIZED, Html("UNAUTHORIZED".to_string())))
}
}
}
}

View File

@@ -1,9 +1,10 @@
use anyhow::Result; use anyhow::Result;
use sqlx::{Pool, Postgres, postgres::PgPoolOptions}; use sqlx::{Pool, Postgres, postgres::PgPoolOptions};
pub mod auth;
pub mod tables; pub mod tables;
pub type CurrDb = Postgres;
pub type CurrPool = Pool<Postgres>; pub type CurrPool = Pool<CurrDb>;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Database { pub struct Database {

View File

@@ -0,0 +1,42 @@
use anyhow::Result;
use persmgr_derive::TableMeta;
use sqlx::prelude::FromRow;
use crate::db::{CurrPool, tables::TableMeta};
#[derive(Debug, Default, Clone, FromRow, TableMeta)]
#[meta(table = "awards")]
pub struct Award {
pub id: i64,
pub name: String,
pub description: String,
pub created_at: i64,
pub modified_at: i64,
}
impl Award {
pub async fn insert_new(&self, pool: &CurrPool) -> Result<Self> {
let session = sqlx::query_as!(
Award,
r#"
INSERT INTO awards (name, description, created_at, modified_at)
VALUES ($1, $2, $3, $4)
RETURNING *
"#,
self.name,
self.description,
self.created_at,
self.modified_at
)
.fetch_one(pool)
.await?;
Ok(session)
}
pub async fn get_by_id(pool: &CurrPool, id: i64) -> anyhow::Result<Self> {
let session = sqlx::query_as!(Award, "SELECT * FROM awards WHERE id = $1", id)
.fetch_one(pool)
.await?;
Ok(session)
}
}

View File

@@ -0,0 +1,43 @@
use anyhow::Result;
use persmgr_derive::TableMeta;
use sqlx::prelude::FromRow;
use crate::db::{CurrPool, tables::TableMeta};
#[derive(Debug, Default, Clone, FromRow, TableMeta)]
#[meta(table = "missions")]
pub struct Mission {
pub id: i64,
pub name: String,
pub description: String,
pub starting_at: i64,
pub estimated_length: i64,
pub created_at: i64,
pub modified_at: i64,
}
impl Mission {
pub async fn insert_new(&self, pool: &CurrPool) -> Result<Self> {
let session = sqlx::query_as!(
Mission,
r#"
INSERT INTO missions (name, description, created_at, modified_at)
VALUES ($1, $2, $3, $4)
RETURNING *
"#,
self.name,
self.description,
self.created_at,
self.modified_at
)
.fetch_one(pool)
.await?;
Ok(session)
}
pub async fn get_by_id(pool: &CurrPool, id: i64) -> anyhow::Result<Self> {
let session = sqlx::query_as!(Mission, "SELECT * FROM missions WHERE id = $1", id)
.fetch_one(pool)
.await?;
Ok(session)
}
}

View File

@@ -0,0 +1,5 @@
pub mod awards;
pub mod missions;
pub mod qualifications;
pub mod ranks;
pub mod trainings;

View File

@@ -0,0 +1,46 @@
use anyhow::Result;
use persmgr_derive::TableMeta;
use sqlx::prelude::FromRow;
use crate::db::{CurrPool, tables::TableMeta};
#[derive(Debug, Default, Clone, FromRow, TableMeta)]
#[meta(table = "qualifications")]
pub struct Qualification {
pub id: i64,
pub name: String,
pub description: String,
pub created_at: i64,
pub modified_at: i64,
}
impl Qualification {
pub async fn insert_new(&self, pool: &CurrPool) -> Result<Self> {
let session = sqlx::query_as!(
Qualification,
r#"
INSERT INTO qualifications (name, description, created_at, modified_at)
VALUES ($1, $2, $3, $4)
RETURNING *
"#,
self.name,
self.description,
self.created_at,
self.modified_at
)
.fetch_one(pool)
.await?;
Ok(session)
}
pub async fn get_by_id(pool: &CurrPool, id: i64) -> anyhow::Result<Self> {
let session = sqlx::query_as!(
Qualification,
"SELECT * FROM qualifications WHERE id = $1",
id
)
.fetch_one(pool)
.await?;
Ok(session)
}
}

View File

@@ -0,0 +1,42 @@
use anyhow::Result;
use persmgr_derive::TableMeta;
use sqlx::prelude::FromRow;
use crate::db::{CurrPool, tables::TableMeta};
#[derive(Debug, Default, Clone, FromRow, TableMeta)]
#[meta(table = "ranks")]
pub struct Rank {
pub id: i64,
pub name: String,
pub description: String,
pub created_at: i64,
pub modified_at: i64,
}
impl Rank {
pub async fn insert_new(&self, pool: &CurrPool) -> Result<Self> {
let session = sqlx::query_as!(
Rank,
r#"
INSERT INTO ranks (name, description, created_at, modified_at)
VALUES ($1, $2, $3, $4)
RETURNING *
"#,
self.name,
self.description,
self.created_at,
self.modified_at
)
.fetch_one(pool)
.await?;
Ok(session)
}
pub async fn get_by_id(pool: &CurrPool, id: i64) -> anyhow::Result<Self> {
let session = sqlx::query_as!(Rank, "SELECT * FROM ranks WHERE id = $1", id)
.fetch_one(pool)
.await?;
Ok(session)
}
}

View File

@@ -0,0 +1,42 @@
use anyhow::Result;
use persmgr_derive::TableMeta;
use sqlx::prelude::FromRow;
use crate::db::{CurrPool, tables::TableMeta};
#[derive(Debug, Default, Clone, FromRow, TableMeta)]
#[meta(table = "trainings")]
pub struct Training {
pub id: i64,
pub name: String,
pub description: String,
pub created_at: i64,
pub modified_at: i64,
}
impl Training {
pub async fn insert_new(&self, pool: &CurrPool) -> Result<Self> {
let session = sqlx::query_as!(
Training,
r#"
INSERT INTO trainings (name, description, created_at, modified_at)
VALUES ($1, $2, $3, $4)
RETURNING *
"#,
self.name,
self.description,
self.created_at,
self.modified_at
)
.fetch_one(pool)
.await?;
Ok(session)
}
pub async fn get_by_id(pool: &CurrPool, id: i64) -> anyhow::Result<Self> {
let session = sqlx::query_as!(Training, "SELECT * FROM trainings WHERE id = $1", id)
.fetch_one(pool)
.await?;
Ok(session)
}
}

View File

53
src/db/tables/groups.rs Normal file
View File

@@ -0,0 +1,53 @@
use anyhow::Result;
use persmgr_derive::TableMeta;
use sqlx::prelude::FromRow;
use crate::db::{
CurrPool,
tables::{ForeignKey, TableMeta, user::User},
};
#[derive(Debug, Default, Clone, FromRow, TableMeta)]
#[meta(table = "roster_groups")]
pub struct Groups {
pub id: i64,
pub name: String,
pub manager_id: ForeignKey<User>,
pub sort_order: i64,
}
impl Groups {
pub async fn insert_new(&self, pool: &CurrPool) -> Result<Self> {
let session = sqlx::query_as!(
Groups,
r#"
INSERT INTO roster_groups (name, manager_id, sort_order)
VALUES ($1, $2, $3)
RETURNING *
"#,
self.name,
*self.manager_id,
self.sort_order,
)
.fetch_one(pool)
.await?;
Ok(session)
}
pub async fn get_by_id(pool: &CurrPool, id: i64) -> anyhow::Result<Self> {
let session = sqlx::query_as!(Groups, "SELECT * FROM roster_groups WHERE id = $1", id)
.fetch_one(pool)
.await?;
Ok(session)
}
pub async fn get_by_manager_id(pool: &CurrPool, id: i64) -> anyhow::Result<Vec<Self>> {
let session = sqlx::query_as!(
Groups,
"SELECT * FROM roster_groups WHERE manager_id = $1",
id
)
.fetch_all(pool)
.await?;
Ok(session)
}
}

View File

@@ -1,2 +1,90 @@
use std::{
error::Error,
marker::PhantomData,
ops::{Deref, DerefMut},
};
use sqlx::{Decode, QueryBuilder, Type, postgres::PgRow};
pub mod assignables;
pub mod attendance;
pub mod groups;
pub mod records;
pub mod sessions; pub mod sessions;
pub mod user; pub mod user;
pub trait TableMeta: for<'r> sqlx::FromRow<'r, PgRow> {
type PrimaryKey: Type<super::CurrDb> + Clone;
const TABLE: &'static str;
async fn update(&mut self, pool: &crate::db::CurrPool) -> anyhow::Result<Self>;
}
#[derive(Debug, Clone, Default)]
pub struct ForeignKey<FK: TableMeta> {
id: FK::PrimaryKey,
_ft: PhantomData<FK>,
}
impl<'a, FK: TableMeta + Send + for<'r> sqlx::FromRow<'r, PgRow> + Unpin + 'a> ForeignKey<FK> {
pub async fn extract(&self, db: &super::CurrPool) -> anyhow::Result<FK>
where
<FK as TableMeta>::PrimaryKey: for<'b> sqlx::Encode<'b, super::CurrDb>,
{
let id = self.id.clone();
let res = QueryBuilder::new("")
.push(format!("SELECT * FROM {} WHERE id = ", FK::TABLE))
.push_bind(id)
.build_query_as::<FK>()
.fetch_one(db)
.await?;
Ok(res)
}
}
impl<'a, TM: TableMeta> Type<super::CurrDb> for ForeignKey<TM> {
fn type_info() -> <super::CurrDb as sqlx::Database>::TypeInfo {
TM::PrimaryKey::type_info()
}
}
impl<'a, TM: TableMeta> Decode<'a, super::CurrDb> for ForeignKey<TM>
where
&'a str: Decode<'a, super::CurrDb>,
<TM as TableMeta>::PrimaryKey: sqlx::Decode<'a, super::CurrDb>,
{
fn decode(
value: <super::CurrDb as sqlx::Database>::ValueRef<'a>,
) -> Result<Self, Box<dyn Error + 'static + Send + Sync>> {
match <TM::PrimaryKey as Decode<super::CurrDb>>::decode(value) {
Ok(v) => Ok(Self {
id: v,
_ft: PhantomData,
}),
Err(e) => Err(e),
}
}
}
impl<TM: TableMeta> Deref for ForeignKey<TM> {
type Target = TM::PrimaryKey;
fn deref(&self) -> &Self::Target {
&self.id
}
}
impl<TM: TableMeta> DerefMut for ForeignKey<TM> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.id
}
}
impl<FK: TableMeta<PrimaryKey = i64>> From<i64> for ForeignKey<FK> {
fn from(value: FK::PrimaryKey) -> Self {
Self {
id: value,
_ft: PhantomData,
}
}
}

View File

@@ -0,0 +1,81 @@
use anyhow::Result;
use persmgr_derive::TableMeta;
use sqlx::prelude::FromRow;
use crate::db::{
CurrPool,
tables::{ForeignKey, TableMeta, assignables::awards::Award, user::User},
};
#[derive(Debug, Default, Clone, FromRow, TableMeta)]
#[meta(table = "records_awards")]
pub struct AwardRecord {
pub id: i64,
pub user_id: ForeignKey<User>,
pub award_id: ForeignKey<Award>,
pub author_id: ForeignKey<User>,
pub created_at: i64,
}
impl AwardRecord {
pub async fn insert_new(&self, pool: &CurrPool) -> Result<Self> {
let session = sqlx::query_as!(
AwardRecord,
r#"
INSERT INTO records_awards (user_id, award_id, author_id, created_at)
VALUES ($1, $2, $3, $4)
RETURNING *
"#,
*self.user_id,
*self.award_id,
*self.author_id,
self.created_at,
)
.fetch_one(pool)
.await?;
let user = self.author_id.extract(pool).await?;
Ok(session)
}
pub async fn get_by_id(pool: &CurrPool, id: i64) -> anyhow::Result<Self> {
let session = sqlx::query_as!(
AwardRecord,
"SELECT * FROM records_awards WHERE id = $1",
id
)
.fetch_one(pool)
.await?;
Ok(session)
}
pub async fn get_by_user_id(pool: &CurrPool, id: i64) -> anyhow::Result<Vec<Self>> {
let session = sqlx::query_as!(
AwardRecord,
"SELECT * FROM records_awards WHERE user_id = $1",
id
)
.fetch_all(pool)
.await?;
Ok(session)
}
pub async fn get_by_author_id(pool: &CurrPool, id: i64) -> anyhow::Result<Vec<Self>> {
let session = sqlx::query_as!(
AwardRecord,
"SELECT * FROM records_awards WHERE author_id = $1",
id
)
.fetch_all(pool)
.await?;
Ok(session)
}
pub async fn get_by_award_id(pool: &CurrPool, id: i64) -> anyhow::Result<Vec<Self>> {
let session = sqlx::query_as!(
AwardRecord,
"SELECT * FROM records_awards WHERE award_id = $1",
id
)
.fetch_all(pool)
.await?;
Ok(session)
}
}

View File

@@ -0,0 +1,79 @@
use anyhow::Result;
use persmgr_derive::TableMeta;
use sqlx::prelude::FromRow;
use crate::db::{
CurrPool,
tables::{ForeignKey, TableMeta, assignables::missions::Mission, user::User},
};
#[derive(Debug, Default, Clone, FromRow, TableMeta)]
#[meta(table = "records_missions")]
pub struct MissionRecord {
pub id: i64,
pub user_id: ForeignKey<User>,
pub mission_id: ForeignKey<Mission>,
pub author_id: ForeignKey<User>,
pub created_at: i64,
}
impl MissionRecord {
pub async fn insert_new(&self, pool: &CurrPool) -> Result<Self> {
let session = sqlx::query_as!(
MissionRecord,
r#"
INSERT INTO records_missions (user_id, mission_id, author_id, created_at)
VALUES ($1, $2, $3, $4)
RETURNING *
"#,
*self.user_id,
*self.mission_id,
*self.author_id,
self.created_at,
)
.fetch_one(pool)
.await?;
Ok(session)
}
pub async fn get_by_id(pool: &CurrPool, id: i64) -> anyhow::Result<Self> {
let session = sqlx::query_as!(
MissionRecord,
"SELECT * FROM records_missions WHERE id = $1",
id
)
.fetch_one(pool)
.await?;
Ok(session)
}
pub async fn get_by_user_id(pool: &CurrPool, id: i64) -> anyhow::Result<Vec<Self>> {
let session = sqlx::query_as!(
MissionRecord,
"SELECT * FROM records_missions WHERE user_id = $1",
id
)
.fetch_all(pool)
.await?;
Ok(session)
}
pub async fn get_by_author_id(pool: &CurrPool, id: i64) -> anyhow::Result<Vec<Self>> {
let session = sqlx::query_as!(
MissionRecord,
"SELECT * FROM records_missions WHERE author_id = $1",
id
)
.fetch_all(pool)
.await?;
Ok(session)
}
pub async fn get_by_mission_id(pool: &CurrPool, id: i64) -> anyhow::Result<Vec<Self>> {
let session = sqlx::query_as!(
MissionRecord,
"SELECT * FROM records_missions WHERE mission_id = $1",
id
)
.fetch_all(pool)
.await?;
Ok(session)
}
}

View File

@@ -0,0 +1,5 @@
pub mod awards;
pub mod missions;
pub mod qualifications;
pub mod ranks;
pub mod trainings;

View File

@@ -0,0 +1,79 @@
use anyhow::Result;
use persmgr_derive::TableMeta;
use sqlx::prelude::FromRow;
use crate::db::{
CurrPool,
tables::{ForeignKey, TableMeta, assignables::qualifications::Qualification, user::User},
};
#[derive(Debug, Default, Clone, FromRow, TableMeta)]
#[meta(table = "records_qualifications")]
pub struct QualificationRecord {
pub id: i64,
pub user_id: ForeignKey<User>,
pub author_id: ForeignKey<User>,
pub qualification_id: ForeignKey<Qualification>,
pub created_at: i64,
}
impl QualificationRecord {
pub async fn insert_new(&self, pool: &CurrPool) -> Result<Self> {
let session = sqlx::query_as!(
QualificationRecord,
r#"
INSERT INTO records_qualifications (user_id, qualification_id, author_id, created_at)
VALUES ($1, $2, $3, $4)
RETURNING *
"#,
*self.user_id,
*self.qualification_id,
*self.author_id,
self.created_at,
)
.fetch_one(pool)
.await?;
Ok(session)
}
pub async fn get_by_id(pool: &CurrPool, id: i64) -> anyhow::Result<Self> {
let session = sqlx::query_as!(
QualificationRecord,
"SELECT * FROM records_qualifications WHERE id = $1",
id
)
.fetch_one(pool)
.await?;
Ok(session)
}
pub async fn get_by_user_id(pool: &CurrPool, id: i64) -> anyhow::Result<Vec<Self>> {
let session = sqlx::query_as!(
QualificationRecord,
"SELECT * FROM records_qualifications WHERE user_id = $1",
id
)
.fetch_all(pool)
.await?;
Ok(session)
}
pub async fn get_by_author_id(pool: &CurrPool, id: i64) -> anyhow::Result<Vec<Self>> {
let session = sqlx::query_as!(
QualificationRecord,
"SELECT * FROM records_qualifications WHERE author_id = $1",
id
)
.fetch_all(pool)
.await?;
Ok(session)
}
pub async fn get_by_qualification_id(pool: &CurrPool, id: i64) -> anyhow::Result<Vec<Self>> {
let session = sqlx::query_as!(
QualificationRecord,
"SELECT * FROM records_qualifications WHERE qualification_id = $1",
id
)
.fetch_all(pool)
.await?;
Ok(session)
}
}

View File

@@ -0,0 +1,75 @@
use anyhow::Result;
use persmgr_derive::TableMeta;
use sqlx::prelude::FromRow;
use crate::db::{
CurrPool,
tables::{ForeignKey, TableMeta, assignables::ranks::Rank, user::User},
};
#[derive(Debug, Default, Clone, FromRow, TableMeta)]
#[meta(table = "records_ranks")]
pub struct RankRecord {
pub id: i64,
pub user_id: ForeignKey<User>,
pub rank_id: ForeignKey<Rank>,
pub author_id: ForeignKey<User>,
pub created_at: i64,
}
impl RankRecord {
pub async fn insert_new(&self, pool: &CurrPool) -> Result<Self> {
let session = sqlx::query_as!(
RankRecord,
r#"
INSERT INTO records_ranks (user_id, rank_id, author_id, created_at)
VALUES ($1, $2, $3, $4)
RETURNING *
"#,
*self.user_id,
*self.rank_id,
*self.author_id,
self.created_at,
)
.fetch_one(pool)
.await?;
Ok(session)
}
pub async fn get_by_id(pool: &CurrPool, id: i64) -> anyhow::Result<Self> {
let session = sqlx::query_as!(RankRecord, "SELECT * FROM records_ranks WHERE id = $1", id)
.fetch_one(pool)
.await?;
Ok(session)
}
pub async fn get_by_user_id(pool: &CurrPool, id: i64) -> anyhow::Result<Vec<Self>> {
let session = sqlx::query_as!(
RankRecord,
"SELECT * FROM records_ranks WHERE user_id = $1",
id
)
.fetch_all(pool)
.await?;
Ok(session)
}
pub async fn get_by_author_id(pool: &CurrPool, id: i64) -> anyhow::Result<Vec<Self>> {
let session = sqlx::query_as!(
RankRecord,
"SELECT * FROM records_ranks WHERE author_id = $1",
id
)
.fetch_all(pool)
.await?;
Ok(session)
}
pub async fn get_by_rank_id(pool: &CurrPool, id: i64) -> anyhow::Result<Vec<Self>> {
let session = sqlx::query_as!(
RankRecord,
"SELECT * FROM records_ranks WHERE rank_id = $1",
id
)
.fetch_all(pool)
.await?;
Ok(session)
}
}

View File

@@ -0,0 +1,79 @@
use anyhow::Result;
use persmgr_derive::TableMeta;
use sqlx::prelude::FromRow;
use crate::db::{
CurrPool,
tables::{ForeignKey, TableMeta, assignables::trainings::Training, user::User},
};
#[derive(Debug, Default, Clone, FromRow, TableMeta)]
#[meta(table = "records_trainings")]
pub struct TrainingRecord {
pub id: i64,
pub user_id: ForeignKey<User>,
pub training_id: ForeignKey<Training>,
pub author_id: ForeignKey<User>,
pub created_at: i64,
}
impl TrainingRecord {
pub async fn insert_new(&self, pool: &CurrPool) -> Result<Self> {
let session = sqlx::query_as!(
TrainingRecord,
r#"
INSERT INTO records_trainings (user_id, training_id, author_id, created_at)
VALUES ($1, $2, $3, $4)
RETURNING *
"#,
*self.user_id,
*self.training_id,
*self.author_id,
self.created_at,
)
.fetch_one(pool)
.await?;
Ok(session)
}
pub async fn get_by_id(pool: &CurrPool, id: i64) -> anyhow::Result<Self> {
let session = sqlx::query_as!(
TrainingRecord,
"SELECT * FROM records_trainings WHERE id = $1",
id
)
.fetch_one(pool)
.await?;
Ok(session)
}
pub async fn get_by_user_id(pool: &CurrPool, id: i64) -> anyhow::Result<Vec<Self>> {
let session = sqlx::query_as!(
TrainingRecord,
"SELECT * FROM records_trainings WHERE user_id = $1",
id
)
.fetch_all(pool)
.await?;
Ok(session)
}
pub async fn get_by_author_id(pool: &CurrPool, id: i64) -> anyhow::Result<Vec<Self>> {
let session = sqlx::query_as!(
TrainingRecord,
"SELECT * FROM records_trainings WHERE author_id = $1",
id
)
.fetch_all(pool)
.await?;
Ok(session)
}
pub async fn get_by_training_id(pool: &CurrPool, id: i64) -> anyhow::Result<Vec<Self>> {
let session = sqlx::query_as!(
TrainingRecord,
"SELECT * FROM records_trainings WHERE training_id = $1",
id
)
.fetch_all(pool)
.await?;
Ok(session)
}
}

View File

@@ -1,9 +1,13 @@
use anyhow::Result; use anyhow::Result;
use persmgr_derive::TableMeta;
use sqlx::prelude::FromRow;
use crate::db::CurrPool; use crate::db::{CurrPool, tables::TableMeta};
#[derive(Debug, Default, Clone)] #[derive(Debug, Default, Clone, FromRow, TableMeta)]
#[meta(table = "sessions")]
pub struct Session { pub struct Session {
pub id: i64,
pub user_id: i64, pub user_id: i64,
pub session_key: String, pub session_key: String,
pub expires: i64, pub expires: i64,
@@ -37,7 +41,7 @@ impl Session {
.await?; .await?;
Ok(session) Ok(session)
} }
pub async fn get_by_session_key(pool: &CurrPool, session_key: String) -> anyhow::Result<Self> { pub async fn get_by_session_key(pool: &CurrPool, session_key: &String) -> anyhow::Result<Self> {
let session = sqlx::query_as!( let session = sqlx::query_as!(
Session, Session,
"SELECT * FROM sessions WHERE session_key = $1", "SELECT * FROM sessions WHERE session_key = $1",

View File

@@ -1,8 +1,12 @@
use anyhow::bail; use persmgr_derive::TableMeta;
use sqlx::prelude::FromRow;
use crate::db::CurrPool; use crate::db::{
CurrPool,
#[derive(Debug, Default, Clone)] tables::{ForeignKey, TableMeta, assignables::ranks::Rank, groups::Groups},
};
#[derive(Debug, Default, Clone, FromRow, TableMeta)]
#[meta(table = "users")]
pub struct User { pub struct User {
pub id: i64, pub id: i64,
pub email: String, pub email: String,
@@ -11,6 +15,8 @@ pub struct User {
pub pw_hash: String, pub pw_hash: String,
pub pw_salt: String, pub pw_salt: String,
pub pfp_id: i64, pub pfp_id: i64,
pub rank_id: ForeignKey<Rank>,
pub group_id: ForeignKey<Groups>,
} }
impl User { impl User {

View File

@@ -1,4 +1,5 @@
use axum::Router; use axum::Router;
use serde::{Deserialize, Serialize};
use tower::ServiceBuilder; use tower::ServiceBuilder;
use tower_cookies::cookie::time::Duration; use tower_cookies::cookie::time::Duration;
use tower_http::{services::ServeDir, trace::TraceLayer}; use tower_http::{services::ServeDir, trace::TraceLayer};
@@ -10,6 +11,16 @@ mod api;
mod db; mod db;
mod pages; mod pages;
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct Session {
// None if unauthed yet
user_id: Option<i64>,
}
impl Session {
const KEY: &'static str = "user_session";
}
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
let sub = FmtSubscriber::builder() let sub = FmtSubscriber::builder()