From 0a197db93f203d45c5a60af15023b6f0d6553b6d Mon Sep 17 00:00:00 2001 From: "D. Scott Boggs" Date: Mon, 26 Jun 2023 07:55:12 -0400 Subject: [PATCH 01/11] Add user model --- server/Cargo.lock | 49 +++++++++++++++++ server/Cargo.toml | 1 + server/src/api/error.rs | 4 +- server/src/entities/mod.rs | 1 + server/src/entities/prelude.rs | 1 + server/src/entities/user.rs | 53 +++++++++++++++++++ server/src/error.rs | 3 ++ .../m20230626_083036_create_users_table.rs | 42 +++++++++++++++ server/src/migrator/mod.rs | 2 + 9 files changed, 154 insertions(+), 2 deletions(-) create mode 100644 server/src/entities/user.rs create mode 100644 server/src/migrator/m20230626_083036_create_users_table.rs diff --git a/server/Cargo.lock b/server/Cargo.lock index 59054fd..026a33f 100644 --- a/server/Cargo.lock +++ b/server/Cargo.lock @@ -142,6 +142,19 @@ version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d" +[[package]] +name = "bcrypt" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9df288bec72232f78c1ec5fe4e8f1d108aa0265476e93097593c803c8c02062a" +dependencies = [ + "base64 0.21.2", + "blowfish", + "getrandom", + "subtle", + "zeroize", +] + [[package]] name = "bigdecimal" version = "0.3.1" @@ -192,6 +205,16 @@ dependencies = [ "generic-array", ] +[[package]] +name = "blowfish" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e412e2cd0f2b2d93e02543ceae7917b3c70331573df19ee046bcbc35e45e87d7" +dependencies = [ + "byteorder", + "cipher", +] + [[package]] name = "borsh" version = "0.10.3" @@ -305,6 +328,16 @@ dependencies = [ "winapi", ] +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + [[package]] name = "clap" version = "3.2.25" @@ -989,6 +1022,15 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb" +[[package]] +name = "inout" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0c10553d664a4d0bcff9f4215d0aac67a639cc68ef660840afe309b807bc9f5" +dependencies = [ + "generic-array", +] + [[package]] name = "instant" version = "0.1.12" @@ -1049,6 +1091,7 @@ dependencies = [ name = "kalkutago-server" version = "0.1.0" dependencies = [ + "bcrypt", "chrono", "derive_builder", "either", @@ -3010,3 +3053,9 @@ name = "yansi" version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec" + +[[package]] +name = "zeroize" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a0956f1ba7c7909bfb66c2e9e4124ab6f6482560f6628b5aaeba39207c9aad9" diff --git a/server/Cargo.toml b/server/Cargo.toml index eddfb63..ec1cbdb 100644 --- a/server/Cargo.toml +++ b/server/Cargo.toml @@ -13,6 +13,7 @@ path = "src/main.rs" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +bcrypt = "0.14.0" chrono = "0.4.26" femme = "2.2.1" log = { version = "0.4.19", features = ["kv_unstable", "kv_unstable_serde"] } diff --git a/server/src/api/error.rs b/server/src/api/error.rs index 602ca1d..5689ed4 100644 --- a/server/src/api/error.rs +++ b/server/src/api/error.rs @@ -2,11 +2,11 @@ use crate::error::Error; #[derive(Responder)] #[response(status = 500, content_type = "json")] -pub(crate) struct ErrorResponder { +pub struct ErrorResponder { message: String, } -pub(crate) type ApiResult = Result; +pub type ApiResult = Result; // The following impl's are for easy conversion of error types. diff --git a/server/src/entities/mod.rs b/server/src/entities/mod.rs index 7a309af..e9e8598 100644 --- a/server/src/entities/mod.rs +++ b/server/src/entities/mod.rs @@ -6,3 +6,4 @@ pub mod groups; pub mod ticks; pub mod track2_groups; pub mod tracks; +pub mod user; diff --git a/server/src/entities/prelude.rs b/server/src/entities/prelude.rs index 796df22..419d754 100644 --- a/server/src/entities/prelude.rs +++ b/server/src/entities/prelude.rs @@ -4,3 +4,4 @@ pub use super::groups::Entity as Groups; pub use super::ticks::Entity as Ticks; pub use super::track2_groups::Entity as Track2Groups; pub use super::tracks::Entity as Tracks; +pub use super::user::Entity as User; diff --git a/server/src/entities/user.rs b/server/src/entities/user.rs new file mode 100644 index 0000000..d8ba976 --- /dev/null +++ b/server/src/entities/user.rs @@ -0,0 +1,53 @@ +//! `SeaORM` Entity. Generated by sea-orm-codegen 0.11.3 + +use std::default::default; + +use bcrypt::*; +use either::Either::{self, Left, Right}; +use rocket::response::status::Unauthorized; +use sea_orm::entity::prelude::*; + +use crate::{ + api::ErrorResponder, + error::{self, Error}, +}; + +#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)] +#[sea_orm(table_name = "user")] +pub struct Model { + #[sea_orm(primary_key)] + pub id: i32, + pub name: String, + pub password_hash: String, +} + +#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] +pub enum Relation {} + +impl ActiveModelBehavior for ActiveModel {} + +impl ActiveModel { + pub fn new(name: String, password: String) -> error::Result { + use sea_orm::ActiveValue::Set; + let name = Set(name); + let password_hash = Set(hash(password, DEFAULT_COST + 2)?); + Ok(Self { + name, + password_hash, + ..default() + }) + } +} + +impl Model { + pub fn check_password( + self, + password: String, + ) -> std::result::Result, ErrorResponder>> { + match verify(password, &self.password_hash) { + Ok(true) => Ok(self), + Ok(false) => Err(Left(Unauthorized(None))), + Err(err) => Err(Right(Error::from(err).into())), + } + } +} diff --git a/server/src/error.rs b/server/src/error.rs index fbf5c10..fa39e1f 100644 --- a/server/src/error.rs +++ b/server/src/error.rs @@ -1,5 +1,6 @@ use std::string; +use bcrypt::BcryptError; use derive_builder::UninitializedFieldError; #[derive(Debug, thiserror::Error)] @@ -18,6 +19,8 @@ pub enum Error { Utf8(#[from] string::FromUtf8Error), #[error(transparent)] ChannelSendError(#[from] tokio::sync::broadcast::error::SendError), + #[error(transparent)] + Bcrypt(#[from] BcryptError), } pub type Result = std::result::Result; diff --git a/server/src/migrator/m20230626_083036_create_users_table.rs b/server/src/migrator/m20230626_083036_create_users_table.rs new file mode 100644 index 0000000..50ab989 --- /dev/null +++ b/server/src/migrator/m20230626_083036_create_users_table.rs @@ -0,0 +1,42 @@ +use sea_orm_migration::prelude::*; + +#[derive(DeriveMigrationName)] +pub struct Migration; + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .create_table( + Table::create() + .table(User::Table) + .if_not_exists() + .col( + ColumnDef::new(User::Id) + .integer() + .not_null() + .auto_increment() + .primary_key(), + ) + .col(ColumnDef::new(User::Name).string().not_null()) + .col(ColumnDef::new(User::PasswordHash).string().not_null()) + .to_owned(), + ) + .await + } + + async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .drop_table(Table::drop().table(User::Table).to_owned()) + .await + } +} + +/// Learn more at https://docs.rs/sea-query#iden +#[derive(Iden)] +enum User { + Table, + Id, + Name, + PasswordHash, +} diff --git a/server/src/migrator/mod.rs b/server/src/migrator/mod.rs index 473e061..6d4f915 100644 --- a/server/src/migrator/mod.rs +++ b/server/src/migrator/mod.rs @@ -2,6 +2,7 @@ mod m20230606_000001_create_tracks_table; mod m20230606_000002_create_ticks_table; mod m20230606_000003_create_groups_table; mod m20230606_000004_create_track2groups_table; +mod m20230626_083036_create_users_table; use sea_orm_migration::prelude::*; @@ -15,6 +16,7 @@ impl MigratorTrait for Migrator { Box::new(m20230606_000002_create_ticks_table::Migration), Box::new(m20230606_000003_create_groups_table::Migration), Box::new(m20230606_000004_create_track2groups_table::Migration), + Box::new(m20230626_083036_create_users_table::Migration), ] } } From 792779a36ded503c07d8455be93b873f1ccd916d Mon Sep 17 00:00:00 2001 From: "D. Scott Boggs" Date: Mon, 26 Jun 2023 10:59:37 -0400 Subject: [PATCH 02/11] Add support for rocket's "secret cookies" --- docker-compose_dev.yml | 4 +- docker-compose_prod.yml | 2 + server/Cargo.lock | 89 +++++++++++++++++++++++++++++++++++++++++ server/Cargo.toml | 2 +- server/src/api/mod.rs | 13 ++++++ 5 files changed, 108 insertions(+), 2 deletions(-) diff --git a/docker-compose_dev.yml b/docker-compose_dev.yml index 93d4bf1..eee5b29 100644 --- a/docker-compose_dev.yml +++ b/docker-compose_dev.yml @@ -14,7 +14,7 @@ services: POSTGRES_USER: kalkutago POSTGRES_DB: kalkutago POSTGRES_HOST: database - secrets: [ postgres-password ] + secrets: [ postgres-password, cookie-secret ] depends_on: [ database ] expose: [ 8000 ] # ports: @@ -65,6 +65,8 @@ services: secrets: postgres-password: file: ./server/postgres.pw + cookie-secret: + file: ./server/cookie-secret.pw networks: internal: diff --git a/docker-compose_prod.yml b/docker-compose_prod.yml index cb57656..71405e1 100644 --- a/docker-compose_prod.yml +++ b/docker-compose_prod.yml @@ -32,6 +32,8 @@ services: secrets: postgres-password: file: ./server/postgres.pw + cookie-secret: + file: ./server/cookie-secret.pw networks: internal: diff --git a/server/Cargo.lock b/server/Cargo.lock index 026a33f..7f9f8e9 100644 --- a/server/Cargo.lock +++ b/server/Cargo.lock @@ -8,6 +8,41 @@ version = "0.11.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3" +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "433cfd6710c9986c576a25ca913c39d66a6474107b406f34f91d4a8923395241" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "aes-gcm" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "209b47e8954a928e1d72e86eca7000ebb6655fe1436d33eefc2201cad027e237" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + [[package]] name = "ahash" version = "0.7.6" @@ -380,7 +415,13 @@ version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7efb37c3e1ccb1ff97164ad95ac1606e8ccd35b3fa0a7d99a304c7f4a428cc24" dependencies = [ + "aes-gcm", + "base64 0.21.2", + "hkdf", "percent-encoding", + "rand", + "sha2", + "subtle", "time 0.3.22", "version_check", ] @@ -426,9 +467,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" dependencies = [ "generic-array", + "rand_core", "typenum", ] +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + [[package]] name = "darling" version = "0.14.4" @@ -789,6 +840,16 @@ dependencies = [ "wasi 0.11.0+wasi-snapshot-preview1", ] +[[package]] +name = "ghash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d930750de5717d2dd0b8c0d42c076c0e884c81a73e6cab859bbd2339c71e3e40" +dependencies = [ + "opaque-debug", + "polyval", +] + [[package]] name = "glob" version = "0.3.1" @@ -1292,6 +1353,12 @@ version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" +[[package]] +name = "opaque-debug" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" + [[package]] name = "os_str_bytes" version = "6.5.1" @@ -1422,6 +1489,18 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +[[package]] +name = "polyval" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef234e08c11dfcb2e56f79fd70f6f2eb7f025c0ce2333e82f4f0518ecad30c6" +dependencies = [ + "cfg-if", + "cpufeatures", + "opaque-debug", + "universal-hash", +] + [[package]] name = "ppv-lite86" version = "0.2.17" @@ -2742,6 +2821,16 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e" +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + [[package]] name = "untrusted" version = "0.7.1" diff --git a/server/Cargo.toml b/server/Cargo.toml index ec1cbdb..68e15ca 100644 --- a/server/Cargo.toml +++ b/server/Cargo.toml @@ -41,7 +41,7 @@ features = [ [dependencies.rocket] git = "https://github.com/SergioBenitez/Rocket" rev = "v0.5.0-rc.3" -features = ["json"] +features = ["json", "secrets"] [dependencies.serde] version = "1.0.163" diff --git a/server/src/api/mod.rs b/server/src/api/mod.rs index bec41f1..40fb19b 100644 --- a/server/src/api/mod.rs +++ b/server/src/api/mod.rs @@ -8,11 +8,13 @@ pub(crate) mod update; use std::{ default::default, + env, fs, net::{IpAddr, Ipv4Addr}, }; use crate::error::Error; use rocket::{ + config::SecretKey, fs::{FileServer, NamedFile}, response::stream::EventStream, routes, Build, Config, Rocket, State, @@ -61,6 +63,16 @@ async fn spa_index_redirect() -> ApiResult { .map_err(Error::from)?) } +fn get_secret() -> [u8; 32] { + let path = + env::var("COOKIE_SECRET_FILE").unwrap_or_else(|_| "/run/secrets/cookie-secret".into()); + let file_contents = + fs::read(&path).unwrap_or_else(|err| panic!("failed to read from {path:?}: {err:?}")); + let mut data = [0u8; 32]; + data.copy_from_slice(&file_contents); + data +} + pub(crate) fn start_server(db: DatabaseConnection) -> Rocket { use groups::*; use ticks::*; @@ -69,6 +81,7 @@ pub(crate) fn start_server(db: DatabaseConnection) -> Rocket { let it = rocket::build() .configure(Config { address: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), + secret_key: SecretKey::derive_from(&get_secret()), ..default() }) .register("/", catchers![spa_index_redirect]) From 2485740291977f8409ae3ffde4bf32c0b164c0dc Mon Sep 17 00:00:00 2001 From: "D. Scott Boggs" Date: Mon, 26 Jun 2023 10:59:56 -0400 Subject: [PATCH 03/11] Add login+sign_up routes and auth guard --- server/src/api/auth.rs | 73 +++++++++++++++++++++++++++++++++++++ server/src/api/mod.rs | 2 + server/src/entities/user.rs | 11 ++++-- 3 files changed, 82 insertions(+), 4 deletions(-) create mode 100644 server/src/api/auth.rs diff --git a/server/src/api/auth.rs b/server/src/api/auth.rs new file mode 100644 index 0000000..c9ab4a5 --- /dev/null +++ b/server/src/api/auth.rs @@ -0,0 +1,73 @@ +use log::warn; +use rocket::{ + http::{Cookie, CookieJar, Status}, + outcome::IntoOutcome, + request::{self, FromRequest}, + serde::json::Json, + Request, State, +}; +use sea_orm::{prelude::*, DatabaseConnection}; +use serde::Deserialize; + +use crate::{ + api::error::ApiResult, + entities::{prelude::*, *}, + error::Error, +}; + +#[derive(Clone, Deserialize)] +pub(super) struct LoginData { + name: String, + password: String, +} + +#[put("/", data = "", format = "application/json")] +pub(super) async fn login( + db: &State, + user_data: Json, + cookies: &CookieJar<'_>, +) -> ApiResult { + let users = User::find() + .filter(user::Column::Name.eq(&user_data.name)) + .all(db as &DatabaseConnection) + .await + .map_err(Error::from)?; + if users.len() > 1 { + warn!(count = users.len(), name = &user_data.name; "multiple entries found in database for user"); + } + let Some(user) = users.get(0) else { + return Ok(Status::Unauthorized); + }; + cookies.add_private(Cookie::new("user_id", user.id.to_string())); + Ok(Status::Ok) +} + +#[post("/", data = "", format = "application/json")] +pub(super) async fn sign_up( + db: &State, + user_data: Json, + cookies: &CookieJar<'_>, +) -> ApiResult<()> { + let user_data = user::ActiveModel::new(&user_data.name, &user_data.password)? + .insert(db as &DatabaseConnection) + .await + .map_err(Error::from)?; + cookies.add_private(Cookie::new("user_id", user_data.id.to_string())); + Ok(()) +} + +/// Authentication guard +struct Auth(i32); + +#[rocket::async_trait] +impl<'r> FromRequest<'r> for Auth { + type Error = (); + async fn from_request(request: &'r Request<'_>) -> request::Outcome { + request + .cookies() + .get_private("user_id") + .and_then(|val| val.value().parse().ok()) + .map(|id| Auth(id)) + .into_outcome((Status::Unauthorized, ())) + } +} diff --git a/server/src/api/mod.rs b/server/src/api/mod.rs index 40fb19b..f4386a8 100644 --- a/server/src/api/mod.rs +++ b/server/src/api/mod.rs @@ -1,3 +1,4 @@ +mod auth; mod error; mod groups; #[cfg(feature = "unsafe_import")] @@ -111,6 +112,7 @@ pub(crate) fn start_server(db: DatabaseConnection) -> Rocket { "/api/v1/groups", routes![all_groups, group, insert_group, update_group, delete_group], ) + .mount("/api/v1/auth", routes![auth::login, auth::sign_up]) .mount("/", FileServer::from("/src/public")); #[cfg(feature = "unsafe_import")] diff --git a/server/src/entities/user.rs b/server/src/entities/user.rs index d8ba976..0ddc95a 100644 --- a/server/src/entities/user.rs +++ b/server/src/entities/user.rs @@ -3,19 +3,22 @@ use std::default::default; use bcrypt::*; +// TODO Add option for argon2 https://docs.rs/argon2/latest/argon2/ use either::Either::{self, Left, Right}; use rocket::response::status::Unauthorized; use sea_orm::entity::prelude::*; +use serde::{Deserialize, Serialize}; use crate::{ api::ErrorResponder, error::{self, Error}, }; -#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)] +#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)] #[sea_orm(table_name = "user")] pub struct Model { #[sea_orm(primary_key)] + #[serde(skip_deserializing)] pub id: i32, pub name: String, pub password_hash: String, @@ -27,10 +30,10 @@ pub enum Relation {} impl ActiveModelBehavior for ActiveModel {} impl ActiveModel { - pub fn new(name: String, password: String) -> error::Result { + pub fn new(name: impl AsRef, password: impl AsRef) -> error::Result { use sea_orm::ActiveValue::Set; - let name = Set(name); - let password_hash = Set(hash(password, DEFAULT_COST + 2)?); + let name = Set(name.as_ref().to_string()); + let password_hash = Set(hash(password.as_ref(), DEFAULT_COST + 2)?); Ok(Self { name, password_hash, From 05bda8deb0dd2624fbd830b0d12d9ac7967df910 Mon Sep 17 00:00:00 2001 From: "D. Scott Boggs" Date: Mon, 26 Jun 2023 11:36:16 -0400 Subject: [PATCH 04/11] Add users-to-tracks many-to-many association --- .../m20230626_083036_create_users_table.rs | 2 +- ...30626_150551_associate_users_and_tracks.rs | 57 +++++++++++++++++++ server/src/migrator/mod.rs | 2 + 3 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 server/src/migrator/m20230626_150551_associate_users_and_tracks.rs diff --git a/server/src/migrator/m20230626_083036_create_users_table.rs b/server/src/migrator/m20230626_083036_create_users_table.rs index 50ab989..6c8e7b7 100644 --- a/server/src/migrator/m20230626_083036_create_users_table.rs +++ b/server/src/migrator/m20230626_083036_create_users_table.rs @@ -34,7 +34,7 @@ impl MigrationTrait for Migration { /// Learn more at https://docs.rs/sea-query#iden #[derive(Iden)] -enum User { +pub(crate) enum User { Table, Id, Name, diff --git a/server/src/migrator/m20230626_150551_associate_users_and_tracks.rs b/server/src/migrator/m20230626_150551_associate_users_and_tracks.rs new file mode 100644 index 0000000..186de49 --- /dev/null +++ b/server/src/migrator/m20230626_150551_associate_users_and_tracks.rs @@ -0,0 +1,57 @@ +use super::{ + m20230606_000001_create_tracks_table::Tracks, m20230626_083036_create_users_table::User, +}; +use sea_orm_migration::prelude::*; + +#[derive(DeriveMigrationName)] +pub struct Migration; + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .create_table( + Table::create() + .table(UserTracks::Table) + .if_not_exists() + .col( + ColumnDef::new(UserTracks::Id) + .integer() + .not_null() + .primary_key() + .auto_increment(), + ) + .col(ColumnDef::new(UserTracks::UserId).integer().not_null()) + .col(ColumnDef::new(UserTracks::TrackId).integer().not_null()) + .foreign_key( + ForeignKey::create() + .name("fk-user_tracks-user_id") + .from(UserTracks::Table, UserTracks::UserId) + .to(User::Table, User::Id), + ) + .foreign_key( + ForeignKey::create() + .name("fk-user_tracks-track_id") + .from(UserTracks::Table, UserTracks::TrackId) + .to(Tracks::Table, Tracks::Id), + ) + .to_owned(), + ) + .await + } + + async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .drop_table(Table::drop().table(UserTracks::Table).to_owned()) + .await + } +} + +/// Learn more at https://docs.rs/sea-query#iden +#[derive(Iden)] +enum UserTracks { + Table, + Id, + UserId, + TrackId, +} diff --git a/server/src/migrator/mod.rs b/server/src/migrator/mod.rs index 6d4f915..edf6a1f 100644 --- a/server/src/migrator/mod.rs +++ b/server/src/migrator/mod.rs @@ -3,6 +3,7 @@ mod m20230606_000002_create_ticks_table; mod m20230606_000003_create_groups_table; mod m20230606_000004_create_track2groups_table; mod m20230626_083036_create_users_table; +mod m20230626_150551_associate_users_and_tracks; use sea_orm_migration::prelude::*; @@ -17,6 +18,7 @@ impl MigratorTrait for Migrator { Box::new(m20230606_000003_create_groups_table::Migration), Box::new(m20230606_000004_create_track2groups_table::Migration), Box::new(m20230626_083036_create_users_table::Migration), + Box::new(m20230626_150551_associate_users_and_tracks::Migration), ] } } From 46a9374571954ed22b3123333fbc0b9c153cbbec Mon Sep 17 00:00:00 2001 From: "D. Scott Boggs" Date: Mon, 26 Jun 2023 11:58:05 -0400 Subject: [PATCH 05/11] Add entity and relations for user-tracks relationship --- docker-compose_dev.yml | 1 + server/src/entities/mod.rs | 1 + server/src/entities/prelude.rs | 1 + server/src/entities/tracks.rs | 17 +++++++++++ server/src/entities/user.rs | 20 ++++++++++++- server/src/entities/user_tracks.rs | 46 ++++++++++++++++++++++++++++++ 6 files changed, 85 insertions(+), 1 deletion(-) create mode 100644 server/src/entities/user_tracks.rs diff --git a/docker-compose_dev.yml b/docker-compose_dev.yml index eee5b29..ac3c228 100644 --- a/docker-compose_dev.yml +++ b/docker-compose_dev.yml @@ -25,6 +25,7 @@ services: labels: traefik.enable: true traefik.http.routers.kalkutago_server.rule: 'Host(`kalkutago`) && PathPrefix(`/api`)' + database: image: postgres environment: diff --git a/server/src/entities/mod.rs b/server/src/entities/mod.rs index e9e8598..2facb82 100644 --- a/server/src/entities/mod.rs +++ b/server/src/entities/mod.rs @@ -7,3 +7,4 @@ pub mod ticks; pub mod track2_groups; pub mod tracks; pub mod user; +pub mod user_tracks; diff --git a/server/src/entities/prelude.rs b/server/src/entities/prelude.rs index 419d754..ee9de0e 100644 --- a/server/src/entities/prelude.rs +++ b/server/src/entities/prelude.rs @@ -5,3 +5,4 @@ pub use super::ticks::Entity as Ticks; pub use super::track2_groups::Entity as Track2Groups; pub use super::tracks::Entity as Tracks; pub use super::user::Entity as User; +pub use super::user_tracks::Entity as UserTracks; diff --git a/server/src/entities/tracks.rs b/server/src/entities/tracks.rs index de4cef4..4b1b7f3 100644 --- a/server/src/entities/tracks.rs +++ b/server/src/entities/tracks.rs @@ -24,6 +24,8 @@ pub enum Relation { Ticks, #[sea_orm(has_many = "super::track2_groups::Entity")] Track2Groups, + #[sea_orm(has_many = "super::user_tracks::Entity")] + UserTracks, } impl Related for Entity { @@ -38,4 +40,19 @@ impl Related for Entity { } } +impl Related for Entity { + fn to() -> RelationDef { + Relation::UserTracks.def() + } +} + +impl Related for Entity { + fn to() -> RelationDef { + super::user_tracks::Relation::User.def() + } + fn via() -> Option { + Some(super::user_tracks::Relation::Tracks.def().rev()) + } +} + impl ActiveModelBehavior for ActiveModel {} diff --git a/server/src/entities/user.rs b/server/src/entities/user.rs index 0ddc95a..7ba561a 100644 --- a/server/src/entities/user.rs +++ b/server/src/entities/user.rs @@ -25,7 +25,25 @@ pub struct Model { } #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] -pub enum Relation {} +pub enum Relation { + #[sea_orm(has_many = "super::user_tracks::Entity")] + UserTracks, +} +impl Related for Entity { + fn to() -> RelationDef { + Relation::UserTracks.def() + } +} + +impl Related for Entity { + fn to() -> RelationDef { + super::user_tracks::Relation::Tracks.def() + } + + fn via() -> Option { + Some(super::user_tracks::Relation::User.def().rev()) + } +} impl ActiveModelBehavior for ActiveModel {} diff --git a/server/src/entities/user_tracks.rs b/server/src/entities/user_tracks.rs new file mode 100644 index 0000000..45214d7 --- /dev/null +++ b/server/src/entities/user_tracks.rs @@ -0,0 +1,46 @@ +//! `SeaORM` Entity. Generated by sea-orm-codegen 0.11.3 + +use sea_orm::entity::prelude::*; + +#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)] +#[sea_orm(table_name = "user_tracks")] +pub struct Model { + #[sea_orm(primary_key)] + pub id: i32, + pub user_id: i32, + pub track_id: i32, +} + +#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] +pub enum Relation { + #[sea_orm( + belongs_to = "super::tracks::Entity", + from = "Column::TrackId", + to = "super::tracks::Column::Id", + on_update = "NoAction", + on_delete = "NoAction" + )] + Tracks, + #[sea_orm( + belongs_to = "super::user::Entity", + from = "Column::UserId", + to = "super::user::Column::Id", + on_update = "NoAction", + on_delete = "NoAction" + )] + User, +} + +impl Related for Entity { + fn to() -> RelationDef { + Relation::Tracks.def() + } +} + +impl Related for Entity { + fn to() -> RelationDef { + Relation::User.def() + } +} + +impl ActiveModelBehavior for ActiveModel {} From f44f15d2b685e1fbbd71c7895484c2cc746250fc Mon Sep 17 00:00:00 2001 From: "D. Scott Boggs" Date: Mon, 26 Jun 2023 15:59:51 -0400 Subject: [PATCH 06/11] tracks are now relative to an authenticated user --- server/Cargo.lock | 12 +++ server/Cargo.toml | 1 + server/src/api/auth.rs | 28 ++++-- server/src/api/tracks.rs | 166 ++++++++++++++++++++++++++++-------- server/src/entities/user.rs | 25 ++++++ server/src/error.rs | 2 + server/src/main.rs | 2 +- 7 files changed, 189 insertions(+), 47 deletions(-) diff --git a/server/Cargo.lock b/server/Cargo.lock index 7f9f8e9..8aa8a7d 100644 --- a/server/Cargo.lock +++ b/server/Cargo.lock @@ -546,6 +546,17 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "derive_deref" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcdbcee2d9941369faba772587a565f4f534e42cb8d17e5295871de730163b2b" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "devise" version = "0.4.1" @@ -1155,6 +1166,7 @@ dependencies = [ "bcrypt", "chrono", "derive_builder", + "derive_deref", "either", "femme", "log", diff --git a/server/Cargo.toml b/server/Cargo.toml index 68e15ca..f34bc6b 100644 --- a/server/Cargo.toml +++ b/server/Cargo.toml @@ -15,6 +15,7 @@ path = "src/main.rs" [dependencies] bcrypt = "0.14.0" chrono = "0.4.26" +derive_deref = "1.1.1" femme = "2.2.1" log = { version = "0.4.19", features = ["kv_unstable", "kv_unstable_serde"] } sea-orm-migration = "0.11.3" diff --git a/server/src/api/auth.rs b/server/src/api/auth.rs index c9ab4a5..6bb75e9 100644 --- a/server/src/api/auth.rs +++ b/server/src/api/auth.rs @@ -1,3 +1,4 @@ +use derive_deref::Deref; use log::warn; use rocket::{ http::{Cookie, CookieJar, Status}, @@ -38,7 +39,10 @@ pub(super) async fn login( let Some(user) = users.get(0) else { return Ok(Status::Unauthorized); }; - cookies.add_private(Cookie::new("user_id", user.id.to_string())); + cookies.add_private(Cookie::new( + "user", + serde_json::to_string(&user).map_err(Error::from)?, + )); Ok(Status::Ok) } @@ -52,22 +56,28 @@ pub(super) async fn sign_up( .insert(db as &DatabaseConnection) .await .map_err(Error::from)?; - cookies.add_private(Cookie::new("user_id", user_data.id.to_string())); + cookies.add_private(Cookie::new( + "user", + serde_json::to_string(&user_data).map_err(Error::from)?, + )); Ok(()) } /// Authentication guard -struct Auth(i32); +#[derive(Deref)] +pub(super) struct Auth(user::Model); #[rocket::async_trait] impl<'r> FromRequest<'r> for Auth { type Error = (); async fn from_request(request: &'r Request<'_>) -> request::Outcome { - request - .cookies() - .get_private("user_id") - .and_then(|val| val.value().parse().ok()) - .map(|id| Auth(id)) - .into_outcome((Status::Unauthorized, ())) + let unauthorized = (Status::Unauthorized, ()); + let Some(user) = request.cookies().get_private("user") else { + return request::Outcome::Failure(unauthorized); + }; + serde_json::from_str(user.value()) + .ok() + .map(|user| Auth(user)) + .into_outcome(unauthorized) } } diff --git a/server/src/api/tracks.rs b/server/src/api/tracks.rs index edfa616..7c59ca2 100644 --- a/server/src/api/tracks.rs +++ b/server/src/api/tracks.rs @@ -1,51 +1,72 @@ +use std::convert::Infallible; +use std::default::default; + +use crate::api::auth::Auth; use crate::api::{self, error::ApiResult}; use crate::entities::{prelude::*, *}; use crate::error::Error; use either::Either::{self, Left, Right}; use rocket::http::Status; use rocket::{serde::json::Json, State}; -use sea_orm::{prelude::*, DatabaseConnection}; +use sea_orm::{prelude::*, DatabaseConnection, IntoActiveModel, Statement, TryIntoModel}; use tokio::sync::broadcast::Sender; use super::update::Update; +use super::ErrorResponder; #[get("/")] pub(super) async fn all_tracks( db: &State, + authorized_user: Auth, ) -> ApiResult>> { let db = db as &DatabaseConnection; - let tracks = Tracks::find().all(db).await.unwrap(); + let tracks = authorized_user + .find_related(Tracks) + .all(db) + .await + .map_err(Error::from)?; Ok(Json(tracks)) } +async fn get_track_check_user( + db: &DatabaseConnection, + track_id: i32, + user: &user::Model, +) -> Result, Either> { + if let Some(Some(user)) = user + .find_related(Tracks) + .filter(tracks::Column::Id.eq(track_id)) + .one(db) + .await + .transpose() + .map(|it| it.ok()) + { + Ok(Json(user)) + } else { + Err(Left(Status::NotFound)) + } +} + #[get("/")] pub(super) async fn track( db: &State, id: i32, + auth: Auth, ) -> Result, Either> { - let db = db as &DatabaseConnection; - match Tracks::find_by_id(id).one(db).await { - Ok(Some(track)) => Ok(Json(track)), - Ok(None) => Err(Left(Status::NotFound)), - Err(err) => Err(Right(Error::from(err).into())), - } + get_track_check_user(db, id, &*auth).await } #[get("//ticks")] pub(super) async fn ticks_for_track( db: &State, id: i32, + auth: Auth, ) -> Result>, Either> { let db = db as &DatabaseConnection; - match Tracks::find_by_id(id).one(db).await { - Ok(Some(track)) => { - let result = track.find_related(Ticks).all(db).await; - match result { - Ok(ticks) => Ok(Json(ticks)), - Err(err) => Err(Right(Error::from(err).into())), - } - } - Ok(None) => Err(Left(Status::NotFound)), + let track = get_track_check_user(db, id, &*auth).await?; + let result = track.find_related(Ticks).all(db).await; + match result { + Ok(ticks) => Ok(Json(ticks)), Err(err) => Err(Right(Error::from(err).into())), } } @@ -55,13 +76,59 @@ pub(super) async fn insert_track( db: &State, tx: &State>, track: Json, -) -> ApiResult> { - let track = track.0; - let db = db as &DatabaseConnection; - let model = tracks::ActiveModel::from_json(track).map_err(Error::from)?; - let track = model.insert(db).await.map_err(Error::from)?; + auth: Auth, +) -> Result, Either> { + fn bad() -> Either { + Left(Status::BadRequest) + } + let track = track.0.as_object().ok_or_else(bad)?; + let Some(track_id) = db + .query_one(Statement::from_sql_and_values( + sea_orm::DatabaseBackend::Postgres, + "insert into $1 (user_id, track_id) values ( + $2, ( + insert into $3 ( + name, description, icon, enabled, multiple_entries_per_day, + color, order + ) values ( + $4, $5, $6, $7, $8, $9, $10, + ) returning id + ) + ) returning track_id;", + [ + user_tracks::Entity::default().table_name().into(), + auth.id.into(), + tracks::Entity::default().table_name().into(), + track.get("name").ok_or_else(bad)?.as_str().ok_or_else(bad)?.into(), + track + .get("description") + .ok_or_else(bad)? + .as_str() + .ok_or_else(bad)? + .into(), + track.get("icon").ok_or_else(bad)?.as_str().ok_or_else(bad)?.into(), + track.get("enabled").ok_or_else(bad)?.as_i64().into(), + track + .get("multiple_entries_per_day") + .ok_or_else(bad)? + .as_i64() + .into(), + track.get("color").ok_or_else(bad)?.as_i64().into(), + track.get("order").ok_or_else(bad)?.as_i64().into(), + ], + )) + .await + .map_err(|err| Right(Error::from(err).into()))? else { + return Err(Right("no value returned from track insertion query".into())); + }; + let track_id = track_id + .try_get_by_index(0) + .map_err(|err| Right(Error::from(err).into()))?; + let track = auth.authorized_track(track_id, db).await.ok_or_else(|| { + Right(format!("failed to fetch freshly inserted track with id {track_id}").into()) + })?; tx.send(Update::track_added(track.clone())) - .map_err(Error::from)?; + .map_err(|err| Right(Error::from(err).into()))?; Ok(Json(track)) } @@ -69,16 +136,21 @@ pub(super) async fn insert_track( pub(super) async fn update_track( db: &State, tx: &State>, - track: Json, -) -> ApiResult> { + track: Json, + authorized_user: Auth, +) -> Result, Either> { let db = db as &DatabaseConnection; - let track = tracks::ActiveModel::from_json(track.0) - .map_err(Error::from)? + let track = track.0; + if !authorized_user.is_authorized_for(track.id, db).await { + return Err(Left(Status::Forbidden)); + } + let track = track + .into_active_model() .update(db) .await - .map_err(Error::from)?; + .map_err(|err| Right(Error::from(err).into()))?; tx.send(Update::track_changed(track.clone())) - .map_err(Error::from)?; + .map_err(|err| Right(Error::from(err).into()))?; Ok(Json(track)) } @@ -87,11 +159,13 @@ pub(super) async fn delete_track( db: &State, tx: &State>, id: i32, + authorized_user: Auth, ) -> ApiResult { let db = db as &DatabaseConnection; - let Some(track) = Tracks::find_by_id(id).one(db).await.map_err(Error::from)? else { + let Some(track) = authorized_user.authorized_track(id, db).await else { return Ok(Status::NotFound); }; + track.clone().delete(db).await.map_err(Error::from)?; tx.send(Update::track_removed(track)).map_err(Error::from)?; Ok(Status::Ok) } @@ -101,15 +175,20 @@ pub(super) async fn ticked( db: &State, tx: &State>, id: i32, -) -> ApiResult> { + authorized_user: Auth, +) -> Result, Either> { + if !authorized_user.is_authorized_for(id, db).await { + return Err(Left(Status::Forbidden)); + } + let tick = ticks::ActiveModel::now(id); let tick = tick .insert(db as &DatabaseConnection) .await - .map_err(Error::from)? + .map_err(|err| Right(Error::from(err).into()))? .to_owned(); tx.send(Update::tick_added(tick.clone())) - .map_err(Error::from)?; + .map_err(|err| Right(Error::from(err).into()))?; Ok(Json(tick)) } @@ -121,7 +200,12 @@ pub(super) async fn ticked_on_date( year: i32, month: u32, day: u32, + authorized_user: Auth, ) -> ApiResult, Status>> { + if !authorized_user.is_authorized_for(id, db).await { + return Ok(Right(Status::Forbidden)); + } + let Some(date) = Date::from_ymd_opt(year, month, day) else { return Ok(Right(Status::BadRequest)); }; @@ -141,10 +225,14 @@ pub(super) async fn clear_all_ticks( db: &State, tx: &State>, id: i32, + authorized_user: Auth, ) -> ApiResult>>> { let db = db as &DatabaseConnection; - let Some(track) = Tracks::find_by_id(id).one(db).await.map_err(Error::from)? else { - info!(track_id = id; "couldn't drop all ticks for track; track not found"); + let Some(track) = authorized_user.authorized_track(id, db).await else { + info!( + track_id = id, user_id = authorized_user.id; + "couldn't drop all ticks for track; track not found or user not authorized" + ); return Ok(Left(Status::NotFound)); }; let ticks = track @@ -167,8 +255,12 @@ pub(super) async fn clear_all_ticks_on_day( year: i32, month: u32, day: u32, -) -> ApiResult>> { + authorized_user: Auth, +) -> ApiResult>>> { let db = db as &DatabaseConnection; + if !authorized_user.is_authorized_for(id, db).await { + return Ok(Left(Status::Forbidden)); + } let ticks = Ticks::find() .filter(ticks::Column::TrackId.eq(id)) .filter(ticks::Column::Year.eq(year)) @@ -181,5 +273,5 @@ pub(super) async fn clear_all_ticks_on_day( tick.clone().delete(db).await.map_err(Error::from)?; Update::tick_cancelled(tick).send(&tx)?; } - Ok(Json(ticks)) + Ok(Right(Json(ticks))) } diff --git a/server/src/entities/user.rs b/server/src/entities/user.rs index 7ba561a..0eae7c1 100644 --- a/server/src/entities/user.rs +++ b/server/src/entities/user.rs @@ -14,6 +14,8 @@ use crate::{ error::{self, Error}, }; +use super::tracks; + #[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)] #[sea_orm(table_name = "user")] pub struct Model { @@ -71,4 +73,27 @@ impl Model { Err(err) => Err(Right(Error::from(err).into())), } } + + pub async fn authorized_track( + &self, + track_id: i32, + db: &DatabaseConnection, + ) -> Option { + self.find_related(super::prelude::Tracks) + .filter(tracks::Column::Id.eq(track_id)) + .one(db) + .await + .ok() + .flatten() + } + pub async fn is_authorized_for(&self, track_id: i32, db: &DatabaseConnection) -> bool { + self.authorized_track(track_id, db).await.is_some() + } + + pub async fn authorized_tracks(&self, db: &DatabaseConnection) -> Vec { + self.find_related(super::prelude::Tracks) + .all(db) + .await + .unwrap_or_default() + } } diff --git a/server/src/error.rs b/server/src/error.rs index fa39e1f..a908650 100644 --- a/server/src/error.rs +++ b/server/src/error.rs @@ -21,6 +21,8 @@ pub enum Error { ChannelSendError(#[from] tokio::sync::broadcast::error::SendError), #[error(transparent)] Bcrypt(#[from] BcryptError), + #[error(transparent)] + SerdeJson(#[from] serde_json::Error), } pub type Result = std::result::Result; diff --git a/server/src/main.rs b/server/src/main.rs index 8959895..d6aad4d 100644 --- a/server/src/main.rs +++ b/server/src/main.rs @@ -1,4 +1,4 @@ -#![feature(default_free_fn, proc_macro_hygiene, decl_macro)] +#![feature(default_free_fn, proc_macro_hygiene, decl_macro, never_type)] #[macro_use] extern crate rocket; mod api; From 205a3b165eb0d34bb50b9f5c495f67bafb9319eb Mon Sep 17 00:00:00 2001 From: "D. Scott Boggs" Date: Tue, 27 Jun 2023 14:18:07 -0400 Subject: [PATCH 07/11] Rename user -> users --- server/src/api/auth.rs | 2 +- server/src/api/tracks.rs | 2 +- server/src/entities/mod.rs | 2 +- server/src/entities/prelude.rs | 2 +- server/src/entities/tracks.rs | 4 ++-- server/src/entities/user_tracks.rs | 10 +++++----- server/src/entities/{user.rs => users.rs} | 9 +++------ .../migrator/m20230626_083036_create_users_table.rs | 12 ++++++------ .../m20230626_150551_associate_users_and_tracks.rs | 4 ++-- 9 files changed, 22 insertions(+), 25 deletions(-) rename server/src/entities/{user.rs => users.rs} (89%) diff --git a/server/src/api/auth.rs b/server/src/api/auth.rs index 6bb75e9..edf0d28 100644 --- a/server/src/api/auth.rs +++ b/server/src/api/auth.rs @@ -52,7 +52,7 @@ pub(super) async fn sign_up( user_data: Json, cookies: &CookieJar<'_>, ) -> ApiResult<()> { - let user_data = user::ActiveModel::new(&user_data.name, &user_data.password)? + let user_data = users::ActiveModel::new(&user_data.name, &user_data.password)? .insert(db as &DatabaseConnection) .await .map_err(Error::from)?; diff --git a/server/src/api/tracks.rs b/server/src/api/tracks.rs index 7c59ca2..e78904f 100644 --- a/server/src/api/tracks.rs +++ b/server/src/api/tracks.rs @@ -31,7 +31,7 @@ pub(super) async fn all_tracks( async fn get_track_check_user( db: &DatabaseConnection, track_id: i32, - user: &user::Model, + user: &users::Model, ) -> Result, Either> { if let Some(Some(user)) = user .find_related(Tracks) diff --git a/server/src/entities/mod.rs b/server/src/entities/mod.rs index 2facb82..c9107ae 100644 --- a/server/src/entities/mod.rs +++ b/server/src/entities/mod.rs @@ -6,5 +6,5 @@ pub mod groups; pub mod ticks; pub mod track2_groups; pub mod tracks; -pub mod user; pub mod user_tracks; +pub mod users; diff --git a/server/src/entities/prelude.rs b/server/src/entities/prelude.rs index ee9de0e..5b17141 100644 --- a/server/src/entities/prelude.rs +++ b/server/src/entities/prelude.rs @@ -4,5 +4,5 @@ pub use super::groups::Entity as Groups; pub use super::ticks::Entity as Ticks; pub use super::track2_groups::Entity as Track2Groups; pub use super::tracks::Entity as Tracks; -pub use super::user::Entity as User; pub use super::user_tracks::Entity as UserTracks; +pub use super::users::Entity as Users; diff --git a/server/src/entities/tracks.rs b/server/src/entities/tracks.rs index 4b1b7f3..b3dfde0 100644 --- a/server/src/entities/tracks.rs +++ b/server/src/entities/tracks.rs @@ -46,9 +46,9 @@ impl Related for Entity { } } -impl Related for Entity { +impl Related for Entity { fn to() -> RelationDef { - super::user_tracks::Relation::User.def() + super::user_tracks::Relation::Users.def() } fn via() -> Option { Some(super::user_tracks::Relation::Tracks.def().rev()) diff --git a/server/src/entities/user_tracks.rs b/server/src/entities/user_tracks.rs index 45214d7..a244d53 100644 --- a/server/src/entities/user_tracks.rs +++ b/server/src/entities/user_tracks.rs @@ -22,13 +22,13 @@ pub enum Relation { )] Tracks, #[sea_orm( - belongs_to = "super::user::Entity", + belongs_to = "super::users::Entity", from = "Column::UserId", - to = "super::user::Column::Id", + to = "super::users::Column::Id", on_update = "NoAction", on_delete = "NoAction" )] - User, + Users, } impl Related for Entity { @@ -37,9 +37,9 @@ impl Related for Entity { } } -impl Related for Entity { +impl Related for Entity { fn to() -> RelationDef { - Relation::User.def() + Relation::Users.def() } } diff --git a/server/src/entities/user.rs b/server/src/entities/users.rs similarity index 89% rename from server/src/entities/user.rs rename to server/src/entities/users.rs index 0eae7c1..c79c5de 100644 --- a/server/src/entities/user.rs +++ b/server/src/entities/users.rs @@ -5,7 +5,7 @@ use std::default::default; use bcrypt::*; // TODO Add option for argon2 https://docs.rs/argon2/latest/argon2/ use either::Either::{self, Left, Right}; -use rocket::response::status::Unauthorized; +use rocket::http::Status; use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; @@ -17,7 +17,7 @@ use crate::{ use super::tracks; #[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)] -#[sea_orm(table_name = "user")] +#[sea_orm(table_name = "users")] pub struct Model { #[sea_orm(primary_key)] #[serde(skip_deserializing)] @@ -43,7 +43,7 @@ impl Related for Entity { } fn via() -> Option { - Some(super::user_tracks::Relation::User.def().rev()) + Some(super::user_tracks::Relation::Users.def().rev()) } } @@ -65,11 +65,8 @@ impl ActiveModel { impl Model { pub fn check_password( self, - password: String, - ) -> std::result::Result, ErrorResponder>> { match verify(password, &self.password_hash) { Ok(true) => Ok(self), - Ok(false) => Err(Left(Unauthorized(None))), Err(err) => Err(Right(Error::from(err).into())), } } diff --git a/server/src/migrator/m20230626_083036_create_users_table.rs b/server/src/migrator/m20230626_083036_create_users_table.rs index 6c8e7b7..7e77a64 100644 --- a/server/src/migrator/m20230626_083036_create_users_table.rs +++ b/server/src/migrator/m20230626_083036_create_users_table.rs @@ -9,17 +9,17 @@ impl MigrationTrait for Migration { manager .create_table( Table::create() - .table(User::Table) + .table(Users::Table) .if_not_exists() .col( - ColumnDef::new(User::Id) + ColumnDef::new(Users::Id) .integer() .not_null() .auto_increment() .primary_key(), ) - .col(ColumnDef::new(User::Name).string().not_null()) - .col(ColumnDef::new(User::PasswordHash).string().not_null()) + .col(ColumnDef::new(Users::Name).string().unique_key().not_null()) + .col(ColumnDef::new(Users::PasswordHash).string().not_null()) .to_owned(), ) .await @@ -27,14 +27,14 @@ impl MigrationTrait for Migration { async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { manager - .drop_table(Table::drop().table(User::Table).to_owned()) + .drop_table(Table::drop().table(Users::Table).to_owned()) .await } } /// Learn more at https://docs.rs/sea-query#iden #[derive(Iden)] -pub(crate) enum User { +pub(crate) enum Users { Table, Id, Name, diff --git a/server/src/migrator/m20230626_150551_associate_users_and_tracks.rs b/server/src/migrator/m20230626_150551_associate_users_and_tracks.rs index 186de49..b2bfcfd 100644 --- a/server/src/migrator/m20230626_150551_associate_users_and_tracks.rs +++ b/server/src/migrator/m20230626_150551_associate_users_and_tracks.rs @@ -1,5 +1,5 @@ use super::{ - m20230606_000001_create_tracks_table::Tracks, m20230626_083036_create_users_table::User, + m20230606_000001_create_tracks_table::Tracks, m20230626_083036_create_users_table::Users, }; use sea_orm_migration::prelude::*; @@ -27,7 +27,7 @@ impl MigrationTrait for Migration { ForeignKey::create() .name("fk-user_tracks-user_id") .from(UserTracks::Table, UserTracks::UserId) - .to(User::Table, User::Id), + .to(Users::Table, Users::Id), ) .foreign_key( ForeignKey::create() From d7285a84bb0ab7ff02f2b7542ec0148dc35ecf75 Mon Sep 17 00:00:00 2001 From: "D. Scott Boggs" Date: Tue, 27 Jun 2023 14:20:43 -0400 Subject: [PATCH 08/11] Fix authenticated track insertion --- server/src/api/auth.rs | 32 ++++++++++-------- server/src/api/tracks.rs | 64 ++++++++++++++++++++---------------- server/src/entities/users.rs | 3 ++ 3 files changed, 58 insertions(+), 41 deletions(-) diff --git a/server/src/api/auth.rs b/server/src/api/auth.rs index edf0d28..e42fe66 100644 --- a/server/src/api/auth.rs +++ b/server/src/api/auth.rs @@ -1,5 +1,8 @@ + + use derive_deref::Deref; -use log::warn; +use either::Either::{self, Right}; + use rocket::{ http::{Cookie, CookieJar, Status}, outcome::IntoOutcome, @@ -16,6 +19,8 @@ use crate::{ error::Error, }; +use super::ErrorResponder; + #[derive(Clone, Deserialize)] pub(super) struct LoginData { name: String, @@ -27,22 +32,22 @@ pub(super) async fn login( db: &State, user_data: Json, cookies: &CookieJar<'_>, -) -> ApiResult { - let users = User::find() - .filter(user::Column::Name.eq(&user_data.name)) - .all(db as &DatabaseConnection) +) -> Result> { + let user = Users::find() + .filter(users::Column::Name.eq(&user_data.name)) + .one(db as &DatabaseConnection) .await - .map_err(Error::from)?; - if users.len() > 1 { - warn!(count = users.len(), name = &user_data.name; "multiple entries found in database for user"); - } - let Some(user) = users.get(0) else { + .map_err(|err| Right(Error::from(err).into()))?; + let Some(user) = user else { + info!(name = user_data.name; "no user found with the given name"); return Ok(Status::Unauthorized); }; + let user = user.check_password(&user_data.password)?; cookies.add_private(Cookie::new( "user", - serde_json::to_string(&user).map_err(Error::from)?, + serde_json::to_string(&user).map_err(|err| Right(Error::from(err).into()))?, )); + cookies.add(Cookie::new("name", user.name)); Ok(Status::Ok) } @@ -60,12 +65,13 @@ pub(super) async fn sign_up( "user", serde_json::to_string(&user_data).map_err(Error::from)?, )); + cookies.add(Cookie::new("name", user_data.name)); Ok(()) } /// Authentication guard #[derive(Deref)] -pub(super) struct Auth(user::Model); +pub(super) struct Auth(users::Model); #[rocket::async_trait] impl<'r> FromRequest<'r> for Auth { @@ -77,7 +83,7 @@ impl<'r> FromRequest<'r> for Auth { }; serde_json::from_str(user.value()) .ok() - .map(|user| Auth(user)) + .map(Auth) .into_outcome(unauthorized) } } diff --git a/server/src/api/tracks.rs b/server/src/api/tracks.rs index e78904f..5060686 100644 --- a/server/src/api/tracks.rs +++ b/server/src/api/tracks.rs @@ -1,5 +1,5 @@ -use std::convert::Infallible; -use std::default::default; + + use crate::api::auth::Auth; use crate::api::{self, error::ApiResult}; @@ -8,7 +8,7 @@ use crate::error::Error; use either::Either::{self, Left, Right}; use rocket::http::Status; use rocket::{serde::json::Json, State}; -use sea_orm::{prelude::*, DatabaseConnection, IntoActiveModel, Statement, TryIntoModel}; +use sea_orm::{prelude::*, DatabaseConnection, IntoActiveModel, Statement}; use tokio::sync::broadcast::Sender; use super::update::Update; @@ -53,7 +53,7 @@ pub(super) async fn track( id: i32, auth: Auth, ) -> Result, Either> { - get_track_check_user(db, id, &*auth).await + get_track_check_user(db, id, &auth).await } #[get("//ticks")] @@ -63,7 +63,7 @@ pub(super) async fn ticks_for_track( auth: Auth, ) -> Result>, Either> { let db = db as &DatabaseConnection; - let track = get_track_check_user(db, id, &*auth).await?; + let track = get_track_check_user(db, id, &auth).await?; let result = track.find_related(Ticks).all(db).await; match result { Ok(ticks) => Ok(Json(ticks)), @@ -81,40 +81,48 @@ pub(super) async fn insert_track( fn bad() -> Either { Left(Status::BadRequest) } - let track = track.0.as_object().ok_or_else(bad)?; + fn bad_value_for(key: &'static str) -> impl Fn() -> Either { + move || { + warn!(key = key; "bad value"); + bad() + } + } + let track = track.0.as_object().ok_or_else(|| { + warn!("received value was not an object"); + bad() + })?; let Some(track_id) = db .query_one(Statement::from_sql_and_values( sea_orm::DatabaseBackend::Postgres, - "insert into $1 (user_id, track_id) values ( - $2, ( - insert into $3 ( - name, description, icon, enabled, multiple_entries_per_day, - color, order + r#"with track_insertion as ( + insert into tracks (name, description, icon, enabled, + multiple_entries_per_day, color, "order" ) values ( - $4, $5, $6, $7, $8, $9, $10, + $2, $3, $4, $5, $6, $7, $8 ) returning id ) - ) returning track_id;", + insert into user_tracks ( + user_id, track_id + ) select $1, ti.id + from track_insertion ti + join track_insertion using (id);"#, [ - user_tracks::Entity::default().table_name().into(), auth.id.into(), - tracks::Entity::default().table_name().into(), - track.get("name").ok_or_else(bad)?.as_str().ok_or_else(bad)?.into(), + track.get("name").ok_or_else(bad_value_for("name"))?.as_str().ok_or_else(bad_value_for("name"))?.into(), track .get("description") - .ok_or_else(bad)? + .ok_or_else(bad_value_for("description"))? .as_str() - .ok_or_else(bad)? + .ok_or_else(bad_value_for("description"))? .into(), - track.get("icon").ok_or_else(bad)?.as_str().ok_or_else(bad)?.into(), - track.get("enabled").ok_or_else(bad)?.as_i64().into(), + track.get("icon").ok_or_else(bad_value_for("icon"))?.as_str().ok_or_else(bad_value_for("icon"))?.into(), + track.get("enabled").and_then(|it| it.as_i64()).into(), track .get("multiple_entries_per_day") - .ok_or_else(bad)? - .as_i64() + .and_then(|it| it.as_i64()) .into(), - track.get("color").ok_or_else(bad)?.as_i64().into(), - track.get("order").ok_or_else(bad)?.as_i64().into(), + track.get("color").and_then(|it| it.as_i64()).into(), + track.get("order").and_then(|it| it.as_i64()).into(), ], )) .await @@ -186,7 +194,7 @@ pub(super) async fn ticked( .insert(db as &DatabaseConnection) .await .map_err(|err| Right(Error::from(err).into()))? - .to_owned(); + ; tx.send(Update::tick_added(tick.clone())) .map_err(|err| Right(Error::from(err).into()))?; Ok(Json(tick)) @@ -214,7 +222,7 @@ pub(super) async fn ticked_on_date( .insert(db as &DatabaseConnection) .await .map_err(Error::from)? - .to_owned(); + ; tx.send(Update::tick_added(tick.clone())) .map_err(Error::from)?; Ok(Left(Json(tick))) @@ -242,7 +250,7 @@ pub(super) async fn clear_all_ticks( .map_err(Error::from)?; for tick in ticks.clone() { tick.clone().delete(db).await.map_err(Error::from)?; - Update::tick_cancelled(tick).send(&tx)?; + Update::tick_cancelled(tick).send(tx)?; } Ok(Right(Json(ticks))) } @@ -271,7 +279,7 @@ pub(super) async fn clear_all_ticks_on_day( .map_err(Error::from)?; for tick in ticks.clone() { tick.clone().delete(db).await.map_err(Error::from)?; - Update::tick_cancelled(tick).send(&tx)?; + Update::tick_cancelled(tick).send(tx)?; } Ok(Right(Json(ticks))) } diff --git a/server/src/entities/users.rs b/server/src/entities/users.rs index c79c5de..645f862 100644 --- a/server/src/entities/users.rs +++ b/server/src/entities/users.rs @@ -65,8 +65,11 @@ impl ActiveModel { impl Model { pub fn check_password( self, + password: impl AsRef<[u8]>, + ) -> std::result::Result> { match verify(password, &self.password_hash) { Ok(true) => Ok(self), + Ok(false) => Err(Left(Status::Unauthorized)), Err(err) => Err(Right(Error::from(err).into())), } } From 1c400e7ffa1f9d41d34bccc5e425c7b85c0decc8 Mon Sep 17 00:00:00 2001 From: "D. Scott Boggs" Date: Thu, 20 Jul 2023 07:39:46 -0400 Subject: [PATCH 09/11] Remove no-longer-existing Rust feature default_free_fn --- server/shell.nix | 9 +++++++++ server/src/api/mod.rs | 4 ++-- server/src/db/mod.rs | 3 +-- server/src/entities/ticks.rs | 6 +++--- server/src/entities/users.rs | 4 ++-- server/src/main.rs | 2 +- 6 files changed, 18 insertions(+), 10 deletions(-) create mode 100644 server/shell.nix diff --git a/server/shell.nix b/server/shell.nix new file mode 100644 index 0000000..96a8187 --- /dev/null +++ b/server/shell.nix @@ -0,0 +1,9 @@ +# DEVELOPMENT shell environment +{ pkgs ? import {} }: + +pkgs.mkShell { + nativeBuildInputs = with pkgs.buildPackages; [ + clang + ]; +} + diff --git a/server/src/api/mod.rs b/server/src/api/mod.rs index f4386a8..30cb521 100644 --- a/server/src/api/mod.rs +++ b/server/src/api/mod.rs @@ -8,7 +8,7 @@ mod tracks; pub(crate) mod update; use std::{ - default::default, + default::Default, env, fs, net::{IpAddr, Ipv4Addr}, }; @@ -83,7 +83,7 @@ pub(crate) fn start_server(db: DatabaseConnection) -> Rocket { .configure(Config { address: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), secret_key: SecretKey::derive_from(&get_secret()), - ..default() + ..Config::default() }) .register("/", catchers![spa_index_redirect]) .manage(db) diff --git a/server/src/db/mod.rs b/server/src/db/mod.rs index b141c4f..8cb0052 100644 --- a/server/src/db/mod.rs +++ b/server/src/db/mod.rs @@ -1,5 +1,4 @@ use std::{ - default::default, env, ffi::{OsStr, OsString}, fs::File, @@ -30,7 +29,7 @@ fn get_env_var_or_file>(key: A) -> Option { if let Some(path) = env::var_os(file_key) { // open the file and read it let mut file = File::open(&path).unwrap_or_else(|_| panic!("no such file at {path:?}")); - let mut val: String = default(); + let mut val = String::new(); file.read_to_string(&mut val) .unwrap_or_else(|_| panic!("reading file at {path:?}")); Some(val) diff --git a/server/src/entities/ticks.rs b/server/src/entities/ticks.rs index 41d4107..7734cf8 100644 --- a/server/src/entities/ticks.rs +++ b/server/src/entities/ticks.rs @@ -1,6 +1,6 @@ //! `SeaORM` Entity. Generated by sea-orm-codegen 0.11.3 -use std::default::default; +use std::default::Default; use chrono::{Datelike, Timelike, Utc}; use sea_orm::entity::prelude::*; @@ -60,7 +60,7 @@ impl ActiveModel { minute: Set(now.minute().try_into().ok()), second: Set(now.second().try_into().ok()), has_time_info: Set(Some(1)), - ..default() + ..Default::default() } } pub(crate) fn on(date: Date, track_id: i32) -> Self { @@ -80,7 +80,7 @@ impl ActiveModel { minute: Set(now.minute().try_into().ok()), second: Set(now.second().try_into().ok()), has_time_info: Set(Some(1)), - ..default() + ..Default::default() } } } diff --git a/server/src/entities/users.rs b/server/src/entities/users.rs index 645f862..5805910 100644 --- a/server/src/entities/users.rs +++ b/server/src/entities/users.rs @@ -1,6 +1,6 @@ //! `SeaORM` Entity. Generated by sea-orm-codegen 0.11.3 -use std::default::default; +use std::default::Default; use bcrypt::*; // TODO Add option for argon2 https://docs.rs/argon2/latest/argon2/ @@ -57,7 +57,7 @@ impl ActiveModel { Ok(Self { name, password_hash, - ..default() + ..Default::default() }) } } diff --git a/server/src/main.rs b/server/src/main.rs index d6aad4d..3a5835c 100644 --- a/server/src/main.rs +++ b/server/src/main.rs @@ -1,4 +1,4 @@ -#![feature(default_free_fn, proc_macro_hygiene, decl_macro, never_type)] +#![feature(proc_macro_hygiene, decl_macro, never_type)] #[macro_use] extern crate rocket; mod api; From a8e4e5145b36cab7ef0b29e1f284ea0b1e1ae0eb Mon Sep 17 00:00:00 2001 From: "D. Scott Boggs" Date: Sat, 22 Jul 2023 15:46:52 -0400 Subject: [PATCH 10/11] add tests --- Makefile | 3 +- client/src/state.ts | 11 ++++-- client/src/track.ts | 3 +- client/src/views/Login.vue | 13 +++++-- client/src/views/TableView.vue | 5 +++ docker-compose_test.yml | 45 +++++++++++++++++++++++ server/Cargo.lock | 14 ++++++++ server/Cargo.toml | 1 + server/src/api/auth.rs | 41 +++++++++++++++------ server/src/api/mod.rs | 4 ++- server/src/api/tracks.rs | 66 +++++++++++++++++++++++----------- server/src/api/update.rs | 9 +++-- server/src/db/mod.rs | 33 +++++++++++++++++ server/src/lib.rs | 8 +++++ server/src/main.rs | 27 ++------------ server/shell.nix => shell.nix | 5 +++ test.py | 61 +++++++++++++++++++++++++++++++ 17 files changed, 283 insertions(+), 66 deletions(-) create mode 100644 docker-compose_test.yml create mode 100644 server/src/lib.rs rename server/shell.nix => shell.nix (59%) create mode 100644 test.py diff --git a/Makefile b/Makefile index 274c3d3..bc6334b 100644 --- a/Makefile +++ b/Makefile @@ -11,4 +11,5 @@ start-server: build-client clean: docker compose down - rm -r server/public/ client/dist/ + -rm -r server/public/ client/dist/ + diff --git a/client/src/state.ts b/client/src/state.ts index 13e3312..67c0955 100644 --- a/client/src/state.ts +++ b/client/src/state.ts @@ -26,6 +26,7 @@ class AppState { tracks: Array state: State user?: LoggedInUser + source?: EventSource constructor() { this.tracks = new Array @@ -79,16 +80,22 @@ class AppState { window.location = window.location }) window.addEventListener('beforeunload', () => source.close()) + this.source = source } async repopulate() { + if (!this.user) { + this.tracks = [] + return + } this.state = State.Fetching this.tracks = await Track.fetchAll() + this.source?.close() + this.streamUpdatesFromServer() + this.state = State.Fetched } async populate() { if (this.state != State.Unfetched) return await this.repopulate() - this.streamUpdatesFromServer() - this.state = State.Fetched } async taskCompleted(track: Track, date: Date): Promise { const query = dateQuery(date) diff --git a/client/src/track.ts b/client/src/track.ts index 83947a3..9893eca 100644 --- a/client/src/track.ts +++ b/client/src/track.ts @@ -1,4 +1,5 @@ import { error } from "./error" +import { Tick, ITick } from './ticks' export interface ITrack { id?: number @@ -97,4 +98,4 @@ export class Track implements ITrack { } return [] } -} \ No newline at end of file +} diff --git a/client/src/views/Login.vue b/client/src/views/Login.vue index 2ef2efe..9f21ab0 100644 --- a/client/src/views/Login.vue +++ b/client/src/views/Login.vue @@ -1,6 +1,7 @@