From c91dce4f77ae12453203f0a28b91efb6533cc095 Mon Sep 17 00:00:00 2001 From: Benedikt Peetz Date: Tue, 9 Dec 2025 13:07:14 +0100 Subject: feat(rocie-server): Implement basic user handling and authentication --- crates/rocie-server/Cargo.toml | 1 + crates/rocie-server/src/api/get/auth/inventory.rs | 53 +++ crates/rocie-server/src/api/get/auth/mod.rs | 32 ++ crates/rocie-server/src/api/get/auth/product.rs | 362 +++++++++++++++++++++ .../src/api/get/auth/product_parent.rs | 111 +++++++ crates/rocie-server/src/api/get/auth/recipe.rs | 76 +++++ crates/rocie-server/src/api/get/auth/unit.rs | 120 +++++++ .../rocie-server/src/api/get/auth/unit_property.rs | 79 +++++ crates/rocie-server/src/api/get/auth/user.rs | 85 +++++ crates/rocie-server/src/api/get/inventory.rs | 44 --- crates/rocie-server/src/api/get/mod.rs | 31 +- crates/rocie-server/src/api/get/no_auth/mod.rs | 3 + crates/rocie-server/src/api/get/product.rs | 237 -------------- crates/rocie-server/src/api/get/product_parent.rs | 64 ---- crates/rocie-server/src/api/get/recipe.rs | 66 ---- crates/rocie-server/src/api/get/unit.rs | 105 ------ crates/rocie-server/src/api/get/unit_property.rs | 68 ---- crates/rocie-server/src/api/set/auth/barcode.rs | 125 +++++++ crates/rocie-server/src/api/set/auth/mod.rs | 21 ++ crates/rocie-server/src/api/set/auth/product.rs | 138 ++++++++ .../src/api/set/auth/product_parent.rs | 67 ++++ crates/rocie-server/src/api/set/auth/recipe.rs | 60 ++++ crates/rocie-server/src/api/set/auth/unit.rs | 67 ++++ .../rocie-server/src/api/set/auth/unit_property.rs | 57 ++++ crates/rocie-server/src/api/set/auth/user.rs | 63 ++++ crates/rocie-server/src/api/set/barcode.rs | 105 ------ crates/rocie-server/src/api/set/mod.rs | 21 +- crates/rocie-server/src/api/set/no_auth/mod.rs | 7 + crates/rocie-server/src/api/set/no_auth/user.rs | 131 ++++++++ crates/rocie-server/src/api/set/product.rs | 126 ------- crates/rocie-server/src/api/set/product_parent.rs | 60 ---- crates/rocie-server/src/api/set/recipe.rs | 54 --- crates/rocie-server/src/api/set/unit.rs | 60 ---- crates/rocie-server/src/api/set/unit_property.rs | 51 --- crates/rocie-server/src/cli.rs | 2 +- crates/rocie-server/src/main.rs | 77 +++-- .../rocie-server/src/storage/migrate/sql/0->1.sql | 8 + crates/rocie-server/src/storage/sql/get/mod.rs | 7 +- .../rocie-server/src/storage/sql/get/user/mod.rs | 77 +++++ crates/rocie-server/src/storage/sql/insert/mod.rs | 1 + .../src/storage/sql/insert/user/mod.rs | 117 +++++++ crates/rocie-server/src/storage/sql/mod.rs | 1 + crates/rocie-server/src/storage/sql/user.rs | 86 +++++ crates/rocie-server/tests/_testenv/init.rs | 27 +- crates/rocie-server/tests/product_parents/query.rs | 14 +- .../rocie-server/tests/product_parents/register.rs | 8 +- crates/rocie-server/tests/products/barcode.rs | 26 +- crates/rocie-server/tests/products/mod.rs | 6 +- crates/rocie-server/tests/products/query.rs | 16 +- crates/rocie-server/tests/products/register.rs | 6 +- crates/rocie-server/tests/recipies/mod.rs | 4 +- crates/rocie-server/tests/tests.rs | 1 + crates/rocie-server/tests/units/fetch.rs | 6 +- crates/rocie-server/tests/units/register.rs | 6 +- crates/rocie-server/tests/users/mod.rs | 53 +++ 55 files changed, 2123 insertions(+), 1176 deletions(-) create mode 100644 crates/rocie-server/src/api/get/auth/inventory.rs create mode 100644 crates/rocie-server/src/api/get/auth/mod.rs create mode 100644 crates/rocie-server/src/api/get/auth/product.rs create mode 100644 crates/rocie-server/src/api/get/auth/product_parent.rs create mode 100644 crates/rocie-server/src/api/get/auth/recipe.rs create mode 100644 crates/rocie-server/src/api/get/auth/unit.rs create mode 100644 crates/rocie-server/src/api/get/auth/unit_property.rs create mode 100644 crates/rocie-server/src/api/get/auth/user.rs delete mode 100644 crates/rocie-server/src/api/get/inventory.rs create mode 100644 crates/rocie-server/src/api/get/no_auth/mod.rs delete mode 100644 crates/rocie-server/src/api/get/product.rs delete mode 100644 crates/rocie-server/src/api/get/product_parent.rs delete mode 100644 crates/rocie-server/src/api/get/recipe.rs delete mode 100644 crates/rocie-server/src/api/get/unit.rs delete mode 100644 crates/rocie-server/src/api/get/unit_property.rs create mode 100644 crates/rocie-server/src/api/set/auth/barcode.rs create mode 100644 crates/rocie-server/src/api/set/auth/mod.rs create mode 100644 crates/rocie-server/src/api/set/auth/product.rs create mode 100644 crates/rocie-server/src/api/set/auth/product_parent.rs create mode 100644 crates/rocie-server/src/api/set/auth/recipe.rs create mode 100644 crates/rocie-server/src/api/set/auth/unit.rs create mode 100644 crates/rocie-server/src/api/set/auth/unit_property.rs create mode 100644 crates/rocie-server/src/api/set/auth/user.rs delete mode 100644 crates/rocie-server/src/api/set/barcode.rs create mode 100644 crates/rocie-server/src/api/set/no_auth/mod.rs create mode 100644 crates/rocie-server/src/api/set/no_auth/user.rs delete mode 100644 crates/rocie-server/src/api/set/product.rs delete mode 100644 crates/rocie-server/src/api/set/product_parent.rs delete mode 100644 crates/rocie-server/src/api/set/recipe.rs delete mode 100644 crates/rocie-server/src/api/set/unit.rs delete mode 100644 crates/rocie-server/src/api/set/unit_property.rs create mode 100644 crates/rocie-server/src/storage/sql/get/user/mod.rs create mode 100644 crates/rocie-server/src/storage/sql/insert/user/mod.rs create mode 100644 crates/rocie-server/src/storage/sql/user.rs create mode 100644 crates/rocie-server/tests/users/mod.rs (limited to 'crates/rocie-server') diff --git a/crates/rocie-server/Cargo.toml b/crates/rocie-server/Cargo.toml index 51df09c..9e20321 100644 --- a/crates/rocie-server/Cargo.toml +++ b/crates/rocie-server/Cargo.toml @@ -35,6 +35,7 @@ actix-cors = "0.7.1" actix-identity = "0.9.0" actix-session = { version = "0.11.0", features = ["cookie-session"] } actix-web = "4.11.0" +argon2 = "0.5.3" chrono = "0.4.41" clap = { version = "4.5.45", features = ["derive", "env"] } env_logger = "0.11.8" diff --git a/crates/rocie-server/src/api/get/auth/inventory.rs b/crates/rocie-server/src/api/get/auth/inventory.rs new file mode 100644 index 0000000..24a8e3d --- /dev/null +++ b/crates/rocie-server/src/api/get/auth/inventory.rs @@ -0,0 +1,53 @@ +use actix_identity::Identity; +use actix_web::{HttpResponse, Responder, Result, get, web}; + +use crate::{ + app::App, + storage::sql::{ + product::{ProductId, ProductIdStub}, + product_amount::ProductAmount, + }, +}; + +/// Get the amount of an product +#[utoipa::path( + responses( + ( + status = OK, + description = "Product found in database and amount fetched", + body = ProductAmount + ), + ( + status = NOT_FOUND, + description = "Product not found in database" + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), + params( + ( + "id" = ProductId, + description = "Product id" + ), + ) +)] +#[get("/inventory/{id}")] +pub(crate) async fn amount_by_id( + app: web::Data, + id: web::Path, + _user: Identity, +) -> Result { + let id = id.into_inner(); + + match ProductAmount::from_id(&app, id.into()).await? { + Some(product) => Ok(HttpResponse::Ok().json(product)), + None => Ok(HttpResponse::NotFound().finish()), + } +} diff --git a/crates/rocie-server/src/api/get/auth/mod.rs b/crates/rocie-server/src/api/get/auth/mod.rs new file mode 100644 index 0000000..c51f6a7 --- /dev/null +++ b/crates/rocie-server/src/api/get/auth/mod.rs @@ -0,0 +1,32 @@ +use actix_web::web; + +pub(crate) mod inventory; +pub(crate) mod product; +pub(crate) mod product_parent; +pub(crate) mod recipe; +pub(crate) mod unit; +pub(crate) mod unit_property; +pub(crate) mod user; + +pub(crate) fn register_paths(cfg: &mut web::ServiceConfig) { + cfg.service(inventory::amount_by_id) + .service(product::product_by_id) + .service(product::product_by_name) + .service(product::product_suggestion_by_name) + .service(product::products_by_product_parent_id_direct) + .service(product::products_by_product_parent_id_indirect) + .service(product::products_in_storage) + .service(product::products_registered) + .service(product_parent::product_parents) + .service(product_parent::product_parents_toplevel) + .service(product_parent::product_parents_under) + .service(recipe::recipe_by_id) + .service(recipe::recipes) + .service(unit::unit_by_id) + .service(unit::units) + .service(unit::units_by_property_id) + .service(unit_property::unit_properties) + .service(unit_property::unit_property_by_id) + .service(user::users) + .service(user::user_by_id); +} diff --git a/crates/rocie-server/src/api/get/auth/product.rs b/crates/rocie-server/src/api/get/auth/product.rs new file mode 100644 index 0000000..1a1e31d --- /dev/null +++ b/crates/rocie-server/src/api/get/auth/product.rs @@ -0,0 +1,362 @@ +use actix_identity::Identity; +use actix_web::{HttpRequest, HttpResponse, Responder, Result, get, web}; +use log::info; +use percent_encoding::percent_decode_str; + +use crate::{ + app::App, + storage::sql::{ + product::{Product, ProductId, ProductIdStub}, + product_amount::ProductAmount, + product_parent::{ProductParent, ProductParentId, ProductParentIdStub}, + }, +}; + +/// A String, that is not url-decoded on parse. +struct UrlEncodedString(String); + +impl UrlEncodedString { + /// Percent de-encode a given string + fn percent_decode(&self) -> Result { + percent_decode_str(self.0.replace('+', "%20").as_str()) + .decode_utf8() + .map(|s| s.to_string()) + .inspect(|s| info!("Decoded `{}` as `{s}`", self.0)) + } + + fn from_str(inner: &str) -> Self { + Self(inner.to_owned()) + } +} + +/// Get Product by id +#[utoipa::path( + responses( + ( + status = OK, + description = "Product found from database", + body = Product + ), + ( + status = NOT_FOUND, + description = "Product not found in database" + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), + params( + ( + "id" = ProductId, + description = "Product id" + ), + ) +)] +#[get("/product/by-id/{id}")] +pub(crate) async fn product_by_id( + app: web::Data, + id: web::Path, + _user: Identity, +) -> Result { + let id = id.into_inner(); + + match Product::from_id(&app, id.into()).await? { + Some(product) => Ok(HttpResponse::Ok().json(product)), + + None => Ok(HttpResponse::NotFound().finish()), + } +} + +/// Get Product by name +#[utoipa::path( + responses( + ( + status = OK, + description = "Product found from database", + body = Product + ), + ( + status = NOT_FOUND, + description = "Product not found in database" + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), + params( + ( + "name" = String, + description = "Name of the product" + ), + ) +)] +#[get("/product/by-name/{name}")] +pub(crate) async fn product_by_name( + app: web::Data, + req: HttpRequest, + name: web::Path, + _user: Identity, +) -> Result { + drop(name); + + let name = UrlEncodedString::from_str( + req.path() + .strip_prefix("/product/by-name/") + .expect("Will always exists"), + ); + let name = name.percent_decode()?; + + match Product::from_name(&app, name).await? { + Some(product) => Ok(HttpResponse::Ok().json(product)), + + None => Ok(HttpResponse::NotFound().finish()), + } +} + +/// Get Product suggestion by name +#[utoipa::path( + responses( + ( + status = OK, + description = "Product suggestions found from database", + body = Vec + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), + params( + ( + "name" = String, + description = "Partial name of a product" + ), + ) +)] +#[get("/product/by-part-name/{name}")] +pub(crate) async fn product_suggestion_by_name( + app: web::Data, + req: HttpRequest, + name: web::Path, + _user: Identity, +) -> Result { + drop(name); + + let name = UrlEncodedString::from_str( + req.path() + .strip_prefix("/product/by-part-name/") + .expect("Will always exists"), + ); + let name = &name.percent_decode()?; + + let all = Product::get_all(&app).await?; + + let matching = all + .into_iter() + .filter(|product| product.name.starts_with(name.as_str())) + .collect::>(); + + Ok(HttpResponse::Ok().json(matching)) +} + +/// Return all registered products +#[utoipa::path( + responses( + ( + status = OK, + description = "All products found", + body = Vec + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), +)] +#[get("/products_registered/")] +pub(crate) async fn products_registered( + app: web::Data, + _user: Identity, +) -> Result { + let all = Product::get_all(&app).await?; + + Ok(HttpResponse::Ok().json(all)) +} + +/// Return all products, which non-null amount in storage +#[utoipa::path( + responses( + ( + status = OK, + description = "All products found", + body = Vec + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), +)] +#[get("/products_in_storage/")] +pub(crate) async fn products_in_storage( + app: web::Data, + _user: Identity, +) -> Result { + let all = Product::get_all(&app).await?; + + let mut output_products = Vec::with_capacity(all.len()); + for product in all { + let amount = ProductAmount::from_id(&app, product.id).await?; + + if amount.is_some_and(|amount| amount.amount.value > 0) { + output_products.push(product); + } + } + + Ok(HttpResponse::Ok().json(output_products)) +} + +/// Get Products by it's product parent id +/// +/// This will also return all products below this product parent id +#[utoipa::path( + responses( + ( + status = OK, + description = "Products found from database", + body = Vec + ), + ( + status = NOT_FOUND, + description = "Product parent id not found in database" + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), + params( + ( + "id" = ProductParentId, + description = "Product parent id" + ), + ) +)] +#[get("/product/by-product-parent-id-indirect/{id}")] +pub(crate) async fn products_by_product_parent_id_indirect( + app: web::Data, + id: web::Path, + _user: Identity, +) -> Result { + let id = id.into_inner(); + + if let Some(parent) = ProductParent::from_id(&app, id.into()).await? { + async fn collect_products(app: &App, parent: ProductParent) -> Result> { + let mut all = Product::get_all(app) + .await? + .into_iter() + .filter(|prod| prod.parent.is_some_and(|val| val == parent.id)) + .collect::>(); + + if let Some(child) = ProductParent::get_all(app) + .await? + .into_iter() + .find(|pp| pp.parent.is_some_and(|id| id == parent.id)) + { + all.extend(Box::pin(collect_products(app, child)).await?); + } + + Ok(all) + } + + let all = collect_products(&app, parent).await?; + + Ok(HttpResponse::Ok().json(all)) + } else { + Ok(HttpResponse::NotFound().finish()) + } +} + +/// Get Products by it's product parent id +/// +/// This will only return products directly associated with this product parent id +#[utoipa::path( + responses( + ( + status = OK, + description = "Products found from database", + body = Vec + ), + ( + status = NOT_FOUND, + description = "Product parent id not found in database" + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), + params( + ( + "id" = ProductParentId, + description = "Product parent id" + ), + ) +)] +#[get("/product/by-product-parent-id-direct/{id}")] +pub(crate) async fn products_by_product_parent_id_direct( + app: web::Data, + id: web::Path, + _user: Identity, +) -> Result { + let id = id.into_inner(); + + if let Some(parent) = ProductParent::from_id(&app, id.into()).await? { + let all = Product::get_all(&app) + .await? + .into_iter() + .filter(|prod| prod.parent.is_some_and(|val| val == parent.id)) + .collect::>(); + + Ok(HttpResponse::Ok().json(all)) + } else { + Ok(HttpResponse::NotFound().finish()) + } +} diff --git a/crates/rocie-server/src/api/get/auth/product_parent.rs b/crates/rocie-server/src/api/get/auth/product_parent.rs new file mode 100644 index 0000000..6c3351d --- /dev/null +++ b/crates/rocie-server/src/api/get/auth/product_parent.rs @@ -0,0 +1,111 @@ +use actix_identity::Identity; +use actix_web::{HttpResponse, Responder, error::Result, get, web}; + +use crate::{ + app::App, + storage::sql::product_parent::{ProductParent, ProductParentId, ProductParentIdStub}, +}; + +/// Return all registered product parents +#[utoipa::path( + responses( + ( + status = OK, + description = "All parents found", + body = Vec + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), +)] +#[get("/product_parents/")] +pub(crate) async fn product_parents( + app: web::Data, + _user: Identity, +) -> Result { + let all: Vec = ProductParent::get_all(&app).await?; + + Ok(HttpResponse::Ok().json(all)) +} + +/// Return all registered product parents, that have no parents themselves +#[utoipa::path( + responses( + ( + status = OK, + description = "All parents found", + body = Vec + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), +)] +#[get("/product_parents_toplevel/")] +pub(crate) async fn product_parents_toplevel( + app: web::Data, + _user: Identity, +) -> Result { + let all: Vec = ProductParent::get_all(&app) + .await? + .into_iter() + .filter(|parent| parent.parent.is_none()) + .collect(); + + Ok(HttpResponse::Ok().json(all)) +} + +/// Return all parents, that have this parent as parent +#[utoipa::path( + responses( + ( + status = OK, + description = "All parents found", + body = Vec + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), + params( + ( + "id" = ProductParentId, + description = "Product parent id" + ), + ), +)] +#[get("/product_parents_under/{id}")] +pub(crate) async fn product_parents_under( + app: web::Data, + id: web::Path, + _user: Identity, +) -> Result { + let id = id.into_inner().into(); + + let all: Vec<_> = ProductParent::get_all(&app) + .await? + .into_iter() + .filter(|parent| parent.parent.is_some_and(|found| found == id)) + .collect(); + + Ok(HttpResponse::Ok().json(all)) +} diff --git a/crates/rocie-server/src/api/get/auth/recipe.rs b/crates/rocie-server/src/api/get/auth/recipe.rs new file mode 100644 index 0000000..cb80597 --- /dev/null +++ b/crates/rocie-server/src/api/get/auth/recipe.rs @@ -0,0 +1,76 @@ +use actix_identity::Identity; +use actix_web::{HttpResponse, Responder, error::Result, get, web}; + +use crate::{ + app::App, + storage::sql::recipe::{Recipe, RecipeId, RecipeIdStub}, +}; + +/// Get an recipe by it's id. +#[utoipa::path( + responses( + ( + status = OK, + description = "Recipe found in database and fetched", + body = Recipe, + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = NOT_FOUND, + description = "Recipe not found in database" + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), + params( + ( + "id" = RecipeId, + description = "Recipe id" + ), + ) +)] +#[get("/recipe/by-id/{id}")] +pub(crate) async fn recipe_by_id( + app: web::Data, + id: web::Path, + _user: Identity, +) -> Result { + let id = id.into_inner(); + + match Recipe::from_id(&app, id.into()).await? { + Some(recipe) => Ok(HttpResponse::Ok().json(recipe)), + None => Ok(HttpResponse::NotFound().finish()), + } +} + +/// Get all added recipes +#[utoipa::path( + responses( + ( + status = OK, + description = "All recipes found in database and fetched", + body = Recipe, + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), +)] +#[get("/recipe/all")] +pub(crate) async fn recipes(app: web::Data, _user: Identity) -> Result { + let all = Recipe::get_all(&app).await?; + + Ok(HttpResponse::Ok().json(all)) +} diff --git a/crates/rocie-server/src/api/get/auth/unit.rs b/crates/rocie-server/src/api/get/auth/unit.rs new file mode 100644 index 0000000..980d9c7 --- /dev/null +++ b/crates/rocie-server/src/api/get/auth/unit.rs @@ -0,0 +1,120 @@ +use actix_identity::Identity; +use actix_web::{HttpResponse, Responder, Result, get, web}; + +use crate::{ + app::App, + storage::sql::{ + unit::{Unit, UnitId, UnitIdStub}, + unit_property::{UnitPropertyId, UnitPropertyIdStub}, + }, +}; + +/// Return all registered units +#[utoipa::path( + responses( + ( + status = OK, + description = "All units founds", + body = Vec + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), +)] +#[get("/units/")] +pub(crate) async fn units(app: web::Data, _user: Identity) -> Result { + let all = Unit::get_all(&app).await?; + + Ok(HttpResponse::Ok().json(all)) +} + +/// Return all registered units for a specific unit property +#[utoipa::path( + responses( + ( + status = OK, + description = "All units founds", + body = Vec + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), + params( + ( + "id" = UnitPropertyId, + description = "Unit property id" + ), + ) +)] +#[get("/units-by-property/{id}")] +pub(crate) async fn units_by_property_id( + app: web::Data, + id: web::Path, + _user: Identity, +) -> Result { + let id = id.into_inner(); + let all = Unit::get_all(&app) + .await? + .into_iter() + .filter(|unit| unit.unit_property == id.into()) + .collect::>(); + + Ok(HttpResponse::Ok().json(all)) +} + +/// Get Unit by id +#[utoipa::path( + responses( + ( + status = OK, + description = "Unit found from database", + body = Unit + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = NOT_FOUND, + description = "Unit not found in database" + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), + params( + ( + "id" = UnitId, + description = "Unit id" + ), + ) +)] +#[get("/unit/{id}")] +pub(crate) async fn unit_by_id( + app: web::Data, + id: web::Path, + _user: Identity, +) -> Result { + let id = id.into_inner(); + + match Unit::from_id(&app, id.into()).await? { + Some(unit) => Ok(HttpResponse::Ok().json(unit)), + None => Ok(HttpResponse::NotFound().finish()), + } +} diff --git a/crates/rocie-server/src/api/get/auth/unit_property.rs b/crates/rocie-server/src/api/get/auth/unit_property.rs new file mode 100644 index 0000000..f5b070a --- /dev/null +++ b/crates/rocie-server/src/api/get/auth/unit_property.rs @@ -0,0 +1,79 @@ +use actix_identity::Identity; +use actix_web::{HttpResponse, Responder, Result, get, web}; + +use crate::{ + app::App, + storage::sql::unit_property::{UnitProperty, UnitPropertyId, UnitPropertyIdStub}, +}; + +/// Return all registered unit properties +#[utoipa::path( + responses( + ( + status = OK, + description = "All unit properties founds", + body = Vec + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), +)] +#[get("/unit-properties/")] +pub(crate) async fn unit_properties( + app: web::Data, + _user: Identity, +) -> Result { + let all = UnitProperty::get_all(&app).await?; + + Ok(HttpResponse::Ok().json(all)) +} + +/// Get Unit property by id +#[utoipa::path( + responses( + ( + status = OK, + description = "Unit property found from database", + body = UnitProperty + ), + ( + status = NOT_FOUND, + description = "Unit Property not found in database" + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), + params( + ( + "id" = UnitPropertyId, + description = "Unit Property id" + ), + ) +)] +#[get("/unit-property/{id}")] +pub(crate) async fn unit_property_by_id( + app: web::Data, + id: web::Path, + _user: Identity, +) -> Result { + let id = id.into_inner(); + + match UnitProperty::from_id(&app, id.into()).await? { + Some(unit_property) => Ok(HttpResponse::Ok().json(unit_property)), + None => Ok(HttpResponse::NotFound().finish()), + } +} diff --git a/crates/rocie-server/src/api/get/auth/user.rs b/crates/rocie-server/src/api/get/auth/user.rs new file mode 100644 index 0000000..e4a5046 --- /dev/null +++ b/crates/rocie-server/src/api/get/auth/user.rs @@ -0,0 +1,85 @@ +use actix_identity::Identity; +use actix_web::{HttpResponse, Responder, Result, get, web}; + +use crate::{ + app::App, + storage::sql::user::{User, UserId, UserIdStub}, +}; + +/// Get all registered users. +#[utoipa::path( + responses( + ( + status = OK, + description = "Users found in database and fetched", + body = Vec, + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), +)] +#[get("/users")] +async fn users(app: web::Data, _user: Identity) -> Result { + let output = User::get_all(&app).await?; + + Ok(HttpResponse::Ok().json(output)) +} + +/// Get an specific user by id. +#[utoipa::path( + responses( + ( + status = OK, + description = "User found in database and fetched", + body = User, + ), + ( + status = NOT_FOUND, + description = "User not found in database" + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = FORBIDDEN, + description = "The current logged in user is not allowed to access this end-point." + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), + params( + ( + "id" = UserId, + description = "User id" + ), + ) +)] +#[get("/user/{id}")] +async fn user_by_id( + id: web::Path, + app: web::Data, + user: Identity, +) -> Result { + let id: UserId = id.into_inner().into(); + + if user.id().expect("to have one") != id.to_string() { + return Ok(HttpResponse::Forbidden() + .body("You must be logged-in as the same user, you request the info for.")); + } + + match User::from_id(&app, id).await? { + Some(user) => Ok(HttpResponse::Ok().json(user)), + None => Ok(HttpResponse::NotFound().finish()), + } +} diff --git a/crates/rocie-server/src/api/get/inventory.rs b/crates/rocie-server/src/api/get/inventory.rs deleted file mode 100644 index d1ca436..0000000 --- a/crates/rocie-server/src/api/get/inventory.rs +++ /dev/null @@ -1,44 +0,0 @@ -use actix_web::{HttpResponse, Responder, Result, get, web}; - -use crate::{ - app::App, - storage::sql::{product::{ProductId, ProductIdStub}, product_amount::ProductAmount}, -}; - -/// Get the amount of an product -#[utoipa::path( - responses( - ( - status = OK, - description = "Product found in database and amount fetched", - body = ProductAmount - ), - ( - status = NOT_FOUND, - description = "Product not found in database" - ), - ( - status = INTERNAL_SERVER_ERROR, - description = "Server encountered error", - body = String - ) - ), - params( - ( - "id" = ProductId, - description = "Product id" - ), - ) -)] -#[get("/inventory/{id}")] -pub(crate) async fn amount_by_id( - app: web::Data, - id: web::Path, -) -> Result { - let id = id.into_inner(); - - match ProductAmount::from_id(&app, id.into()).await? { - Some(product) => Ok(HttpResponse::Ok().json(product)), - None => Ok(HttpResponse::NotFound().finish()), - } -} diff --git a/crates/rocie-server/src/api/get/mod.rs b/crates/rocie-server/src/api/get/mod.rs index 487b55c..c6ee9ab 100644 --- a/crates/rocie-server/src/api/get/mod.rs +++ b/crates/rocie-server/src/api/get/mod.rs @@ -1,29 +1,2 @@ -use actix_web::web; - -pub(crate) mod inventory; -pub(crate) mod product; -pub(crate) mod product_parent; -pub(crate) mod recipe; -pub(crate) mod unit; -pub(crate) mod unit_property; - -pub(crate) fn register_paths(cfg: &mut web::ServiceConfig) { - cfg.service(product::product_by_id) - .service(product::product_by_name) - .service(product::product_suggestion_by_name) - .service(product::products_registered) - .service(product::products_in_storage) - .service(product::products_by_product_parent_id_indirect) - .service(product::products_by_product_parent_id_direct) - .service(product_parent::product_parents) - .service(product_parent::product_parents_toplevel) - .service(product_parent::product_parents_under) - .service(recipe::recipe_by_id) - .service(recipe::recipes) - .service(unit::units) - .service(unit::units_by_property_id) - .service(unit::unit_by_id) - .service(unit_property::unit_properties) - .service(unit_property::unit_property_by_id) - .service(inventory::amount_by_id); -} +pub(crate) mod auth; +pub(crate) mod no_auth; diff --git a/crates/rocie-server/src/api/get/no_auth/mod.rs b/crates/rocie-server/src/api/get/no_auth/mod.rs new file mode 100644 index 0000000..38a041c --- /dev/null +++ b/crates/rocie-server/src/api/get/no_auth/mod.rs @@ -0,0 +1,3 @@ +use actix_web::web; + +pub(crate) fn register_paths(cfg: &mut web::ServiceConfig) {} diff --git a/crates/rocie-server/src/api/get/product.rs b/crates/rocie-server/src/api/get/product.rs deleted file mode 100644 index 4216f9b..0000000 --- a/crates/rocie-server/src/api/get/product.rs +++ /dev/null @@ -1,237 +0,0 @@ -use actix_web::{HttpRequest, HttpResponse, Responder, Result, get, web}; -use log::info; -use percent_encoding::percent_decode_str; - -use crate::{ - app::App, - storage::sql::{ - product::{Product, ProductId, ProductIdStub}, - product_amount::ProductAmount, - product_parent::{ProductParent, ProductParentId, ProductParentIdStub}, - }, -}; - -/// A String, that is not url-decoded on parse. -struct UrlEncodedString(String); - -impl UrlEncodedString { - /// Percent de-encode a given string - fn percent_decode(&self) -> Result { - percent_decode_str(self.0.replace('+', "%20").as_str()) - .decode_utf8() - .map(|s| s.to_string()) - .inspect(|s| info!("Decoded `{}` as `{s}`", self.0)) - } - - fn from_str(inner: &str) -> Self { - Self(inner.to_owned()) - } -} - -/// Get Product by id -#[utoipa::path( - responses( - (status = OK, description = "Product found from database", body = Product), - (status = NOT_FOUND, description = "Product not found in database"), - (status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String) - ), - params( - ("id" = ProductId, description = "Product id" ), - ) -)] -#[get("/product/by-id/{id}")] -pub(crate) async fn product_by_id( - app: web::Data, - id: web::Path, -) -> Result { - let id = id.into_inner(); - - match Product::from_id(&app, id.into()).await? { - Some(product) => Ok(HttpResponse::Ok().json(product)), - None => Ok(HttpResponse::NotFound().finish()), - } -} - -/// Get Product by name -#[utoipa::path( - responses( - (status = OK, description = "Product found from database", body = Product), - (status = NOT_FOUND, description = "Product not found in database"), - (status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String) - ), - params( - ("name" = String, description = "Name of the product" ), - ) -)] -#[get("/product/by-name/{name}")] -pub(crate) async fn product_by_name( - app: web::Data, - req: HttpRequest, - name: web::Path, -) -> Result { - drop(name); - - let name = UrlEncodedString::from_str( - req.path() - .strip_prefix("/product/by-name/") - .expect("Will always exists"), - ); - let name = name.percent_decode()?; - - match Product::from_name(&app, name).await? { - Some(product) => Ok(HttpResponse::Ok().json(product)), - None => Ok(HttpResponse::NotFound().finish()), - } -} - -/// Get Product suggestion by name -#[utoipa::path( - responses( - (status = OK, description = "Product suggestions found from database", body = Vec), - (status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String) - ), - params( - ("name" = String, description = "Partial name of a product" ), - ) -)] -#[get("/product/by-part-name/{name}")] -pub(crate) async fn product_suggestion_by_name( - app: web::Data, - req: HttpRequest, - name: web::Path, -) -> Result { - drop(name); - - let name = UrlEncodedString::from_str( - req.path() - .strip_prefix("/product/by-part-name/") - .expect("Will always exists"), - ); - let name = &name.percent_decode()?; - - let all = Product::get_all(&app).await?; - - let matching = all - .into_iter() - .filter(|product| product.name.starts_with(name.as_str())) - .collect::>(); - - Ok(HttpResponse::Ok().json(matching)) -} - -/// Return all registered products -#[utoipa::path( - responses( - (status = OK, description = "All products found", body = Vec), - (status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String) - ), -)] -#[get("/products_registered/")] -pub(crate) async fn products_registered(app: web::Data) -> Result { - let all = Product::get_all(&app).await?; - - Ok(HttpResponse::Ok().json(all)) -} - -/// Return all products, which non-null amount in storage -#[utoipa::path( - responses( - (status = OK, description = "All products found", body = Vec), - (status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String) - ), -)] -#[get("/products_in_storage/")] -pub(crate) async fn products_in_storage(app: web::Data) -> Result { - let all = Product::get_all(&app).await?; - - let mut output_products = Vec::with_capacity(all.len()); - for product in all { - let amount = ProductAmount::from_id(&app, product.id).await?; - - if amount.is_some_and(|amount| amount.amount.value > 0) { - output_products.push(product); - } - } - - Ok(HttpResponse::Ok().json(output_products)) -} - -/// Get Products by it's product parent id -/// -/// This will also return all products below this product parent id -#[utoipa::path( - responses( - (status = OK, description = "Products found from database", body = Vec), - (status = NOT_FOUND, description = "Product parent id not found in database"), - (status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String) - ), - params( - ("id" = ProductParentId, description = "Product parent id" ), - ) -)] -#[get("/product/by-product-parent-id-indirect/{id}")] -pub(crate) async fn products_by_product_parent_id_indirect( - app: web::Data, - id: web::Path, -) -> Result { - let id = id.into_inner(); - - if let Some(parent) = ProductParent::from_id(&app, id.into()).await? { - async fn collect_products(app: &App, parent: ProductParent) -> Result> { - let mut all = Product::get_all(app) - .await? - .into_iter() - .filter(|prod| prod.parent.is_some_and(|val| val == parent.id)) - .collect::>(); - - if let Some(child) = ProductParent::get_all(app) - .await? - .into_iter() - .find(|pp| pp.parent.is_some_and(|id| id == parent.id)) - { - all.extend(Box::pin(collect_products(app, child)).await?); - } - - Ok(all) - } - - let all = collect_products(&app, parent).await?; - - Ok(HttpResponse::Ok().json(all)) - } else { - Ok(HttpResponse::NotFound().finish()) - } -} - -/// Get Products by it's product parent id -/// -/// This will only return products directly associated with this product parent id -#[utoipa::path( - responses( - (status = OK, description = "Products found from database", body = Vec), - (status = NOT_FOUND, description = "Product parent id not found in database"), - (status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String) - ), - params( - ("id" = ProductParentId, description = "Product parent id" ), - ) -)] -#[get("/product/by-product-parent-id-direct/{id}")] -pub(crate) async fn products_by_product_parent_id_direct( - app: web::Data, - id: web::Path, -) -> Result { - let id = id.into_inner(); - - if let Some(parent) = ProductParent::from_id(&app, id.into()).await? { - let all = Product::get_all(&app) - .await? - .into_iter() - .filter(|prod| prod.parent.is_some_and(|val| val == parent.id)) - .collect::>(); - - Ok(HttpResponse::Ok().json(all)) - } else { - Ok(HttpResponse::NotFound().finish()) - } -} diff --git a/crates/rocie-server/src/api/get/product_parent.rs b/crates/rocie-server/src/api/get/product_parent.rs deleted file mode 100644 index a62397c..0000000 --- a/crates/rocie-server/src/api/get/product_parent.rs +++ /dev/null @@ -1,64 +0,0 @@ -use actix_web::{HttpResponse, Responder, error::Result, get, web}; - -use crate::{ - app::App, - storage::sql::product_parent::{ProductParent, ProductParentId, ProductParentIdStub}, -}; - -/// Return all registered product parents -#[utoipa::path( - responses( - (status = OK, description = "All parents found", body = Vec), - (status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String) - ), -)] -#[get("/product_parents/")] -pub(crate) async fn product_parents(app: web::Data) -> Result { - let all: Vec = ProductParent::get_all(&app).await?; - - Ok(HttpResponse::Ok().json(all)) -} - -/// Return all registered product parents, that have no parents themselves -#[utoipa::path( - responses( - (status = OK, description = "All parents found", body = Vec), - (status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String) - ), -)] -#[get("/product_parents_toplevel/")] -pub(crate) async fn product_parents_toplevel(app: web::Data) -> Result { - let all: Vec = ProductParent::get_all(&app) - .await? - .into_iter() - .filter(|parent| parent.parent.is_none()) - .collect(); - - Ok(HttpResponse::Ok().json(all)) -} - -/// Return all parents, that have this parent as parent -#[utoipa::path( - responses( - (status = OK, description = "All parents found", body = Vec), - (status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String) - ), - params( - ("id" = ProductParentId, description = "Product parent id" ), - ), -)] -#[get("/product_parents_under/{id}")] -pub(crate) async fn product_parents_under( - app: web::Data, - id: web::Path, -) -> Result { - let id = id.into_inner().into(); - - let all: Vec<_> = ProductParent::get_all(&app) - .await? - .into_iter() - .filter(|parent| parent.parent.is_some_and(|found| found == id)) - .collect(); - - Ok(HttpResponse::Ok().json(all)) -} diff --git a/crates/rocie-server/src/api/get/recipe.rs b/crates/rocie-server/src/api/get/recipe.rs deleted file mode 100644 index 70bab39..0000000 --- a/crates/rocie-server/src/api/get/recipe.rs +++ /dev/null @@ -1,66 +0,0 @@ -use actix_web::{HttpResponse, Responder, error::Result, get, web}; - -use crate::{ - app::App, - storage::sql::recipe::{Recipe, RecipeId, RecipeIdStub}, -}; - -/// Get an recipe by it's id. -#[utoipa::path( - responses( - ( - status = OK, - description = "Recipe found in database and fetched", - body = Recipe, - ), - ( - status = NOT_FOUND, - description = "Recipe not found in database" - ), - ( - status = INTERNAL_SERVER_ERROR, - description = "Server encountered error", - body = String - ) - ), - params( - ( - "id" = RecipeId, - description = "Recipe id" - ), - ) -)] -#[get("/recipe/by-id/{id}")] -pub(crate) async fn recipe_by_id( - app: web::Data, - id: web::Path, -) -> Result { - let id = id.into_inner(); - - match Recipe::from_id(&app, id.into()).await? { - Some(recipe) => Ok(HttpResponse::Ok().json(recipe)), - None => Ok(HttpResponse::NotFound().finish()), - } -} - -/// Get all added recipes -#[utoipa::path( - responses( - ( - status = OK, - description = "All recipes found in database and fetched", - body = Recipe, - ), - ( - status = INTERNAL_SERVER_ERROR, - description = "Server encountered error", - body = String - ) - ), -)] -#[get("/recipe/all")] -pub(crate) async fn recipes(app: web::Data) -> Result { - let all = Recipe::get_all(&app).await?; - - Ok(HttpResponse::Ok().json(all)) -} diff --git a/crates/rocie-server/src/api/get/unit.rs b/crates/rocie-server/src/api/get/unit.rs deleted file mode 100644 index caafaa3..0000000 --- a/crates/rocie-server/src/api/get/unit.rs +++ /dev/null @@ -1,105 +0,0 @@ -use actix_web::{HttpResponse, Responder, Result, get, web}; - -use crate::{ - app::App, - storage::sql::{ - unit::{Unit, UnitId, UnitIdStub}, - unit_property::{UnitPropertyId, UnitPropertyIdStub}, - }, -}; - -/// Return all registered units -#[utoipa::path( - responses( - ( - status = OK, - description = "All units founds", - body = Vec - ), - ( - status = INTERNAL_SERVER_ERROR, - description = "Server encountered error", - body = String - ) - ), -)] -#[get("/units/")] -pub(crate) async fn units(app: web::Data) -> Result { - let all = Unit::get_all(&app).await?; - - Ok(HttpResponse::Ok().json(all)) -} - -/// Return all registered units for a specific unit property -#[utoipa::path( - responses( - ( - status = OK, - description = "All units founds", - body = Vec - ), - ( - status = INTERNAL_SERVER_ERROR, - description = "Server encountered error", - body = String - ) - ), - params( - ( - "id" = UnitPropertyId, - description = "Unit property id" - ), - ) -)] -#[get("/units-by-property/{id}")] -pub(crate) async fn units_by_property_id( - app: web::Data, - id: web::Path, -) -> Result { - let id = id.into_inner(); - let all = Unit::get_all(&app) - .await? - .into_iter() - .filter(|unit| unit.unit_property == id.into()) - .collect::>(); - - Ok(HttpResponse::Ok().json(all)) -} - -/// Get Unit by id -#[utoipa::path( - responses( - ( - status = OK, - description = "Unit found from database", - body = Unit - ), - ( - status = NOT_FOUND, - description = "Unit not found in database" - ), - ( - status = INTERNAL_SERVER_ERROR, - description = "Server encountered error", - body = String - ) - ), - params( - ( - "id" = UnitId, - description = "Unit id" - ), - ) -)] -#[get("/unit/{id}")] -pub(crate) async fn unit_by_id( - app: web::Data, - id: web::Path, -) -> Result { - let id = id.into_inner(); - - match Unit::from_id(&app, id.into()).await? { - Some(unit) => Ok(HttpResponse::Ok().json(unit)), - None => Ok(HttpResponse::NotFound().finish()), - } -} diff --git a/crates/rocie-server/src/api/get/unit_property.rs b/crates/rocie-server/src/api/get/unit_property.rs deleted file mode 100644 index 3160480..0000000 --- a/crates/rocie-server/src/api/get/unit_property.rs +++ /dev/null @@ -1,68 +0,0 @@ -use actix_web::{HttpResponse, Responder, Result, get, web}; - -use crate::{ - app::App, - storage::sql::{ - unit_property::{UnitProperty, UnitPropertyId, UnitPropertyIdStub}, - }, -}; - -/// Return all registered unit properties -#[utoipa::path( - responses( - ( - status = OK, - description = "All unit properties founds", - body = Vec - ), - ( - status = INTERNAL_SERVER_ERROR, - description = "Server encountered error", - body = String - ) - ), -)] -#[get("/unit-properties/")] -pub(crate) async fn unit_properties(app: web::Data) -> Result { - let all = UnitProperty::get_all(&app).await?; - - Ok(HttpResponse::Ok().json(all)) -} - -/// Get Unit property by id -#[utoipa::path( - responses( - ( - status = OK, - description = "Unit property found from database", - body = UnitProperty - ), - ( - status = NOT_FOUND, - description = "Unit Property not found in database" - ), - ( - status = INTERNAL_SERVER_ERROR, - description = "Server encountered error", - body = String - ) - ), - params( - ( - "id" = UnitPropertyId, - description = "Unit Property id" - ), - ) -)] -#[get("/unit-property/{id}")] -pub(crate) async fn unit_property_by_id( - app: web::Data, - id: web::Path, -) -> Result { - let id = id.into_inner(); - - match UnitProperty::from_id(&app, id.into()).await? { - Some(unit_property) => Ok(HttpResponse::Ok().json(unit_property)), - None => Ok(HttpResponse::NotFound().finish()), - } -} diff --git a/crates/rocie-server/src/api/set/auth/barcode.rs b/crates/rocie-server/src/api/set/auth/barcode.rs new file mode 100644 index 0000000..1d97852 --- /dev/null +++ b/crates/rocie-server/src/api/set/auth/barcode.rs @@ -0,0 +1,125 @@ +use actix_identity::Identity; +use actix_web::{HttpResponse, Responder, Result, post, web}; +use log::debug; + +use crate::{ + app::App, + storage::sql::{ + barcode::{Barcode, BarcodeId, BarcodeIdStub}, + insert::Operations, + unit::UnitAmount, + }, +}; + +/// Buy an barcode +#[utoipa::path( + responses( + ( + status = OK, + description = "Barcode successfully bought", + ), + ( + status = NOT_FOUND, + description = "Barcode id was not found", + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String, + ) + ), + params( + ( + "barcode_id" = BarcodeId, + description = "The numeric value of the barcode" + ), + ( + "times" = u16, + description = "How often to buy the barcode" + ), + ) +)] +#[post("/barcode/{barcode_id}/buy/{times}")] +pub(crate) async fn buy_barcode( + app: web::Data, + path: web::Path<(BarcodeIdStub, u16)>, + _user: Identity, +) -> Result { + let (barcode_id, times) = path.into_inner(); + + let mut ops = Operations::new("buy barcode unit"); + + let barcode = Barcode::from_id(&app, barcode_id.into()).await?; + + match barcode { + Some(barcode) => { + for _ in 0..times { + barcode.buy(&mut ops); + } + + ops.apply(&app).await?; + + Ok(HttpResponse::Ok().finish()) + } + None => Ok(HttpResponse::NotFound().finish()), + } +} + +/// Consume an barcode +#[utoipa::path( + responses( + ( + status = OK, + description = "Barcode successfully consumed", + ), + ( + status = NOT_FOUND, + description = "Barcode id was not found", + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String, + ) + ), + params( + ( + "id" = BarcodeId, + description = "The numeric value of the barcode" + ), + ), + request_body = UnitAmount, +)] +#[post("/barcode/{id}/consume")] +pub(crate) async fn consume_barcode( + app: web::Data, + barcode_id: web::Path, + unit_amount: web::Json, + _user: Identity, +) -> Result { + let mut ops = Operations::new("consume barcode unit"); + + let barcode = Barcode::from_id(&app, barcode_id.into_inner().into()).await?; + debug!("Starting consume for barcode: {barcode:?}"); + + match barcode { + Some(barcode) => { + barcode + .consume(&app, unit_amount.into_inner(), &mut ops) + .await?; + + ops.apply(&app).await?; + + Ok(HttpResponse::Ok().finish()) + } + None => Ok(HttpResponse::NotFound().finish()), + } +} diff --git a/crates/rocie-server/src/api/set/auth/mod.rs b/crates/rocie-server/src/api/set/auth/mod.rs new file mode 100644 index 0000000..4e733a9 --- /dev/null +++ b/crates/rocie-server/src/api/set/auth/mod.rs @@ -0,0 +1,21 @@ +use actix_web::web; + +pub(crate) mod barcode; +pub(crate) mod product; +pub(crate) mod product_parent; +pub(crate) mod recipe; +pub(crate) mod unit; +pub(crate) mod unit_property; +pub(crate) mod user; + +pub(crate) fn register_paths(cfg: &mut web::ServiceConfig) { + cfg.service(product::register_product) + .service(product::associate_barcode) + .service(product_parent::register_product_parent) + .service(recipe::add_recipe) + .service(unit::register_unit) + .service(unit_property::register_unit_property) + .service(barcode::consume_barcode) + .service(barcode::buy_barcode) + .service(user::register_user); +} diff --git a/crates/rocie-server/src/api/set/auth/product.rs b/crates/rocie-server/src/api/set/auth/product.rs new file mode 100644 index 0000000..b2a751f --- /dev/null +++ b/crates/rocie-server/src/api/set/auth/product.rs @@ -0,0 +1,138 @@ +use actix_identity::Identity; +use actix_web::{HttpResponse, Responder, Result, post, web}; +use serde::Deserialize; +use utoipa::ToSchema; + +use crate::{ + app::App, + storage::sql::{ + barcode::Barcode, + insert::Operations, + product::{Product, ProductId, ProductIdStub}, + product_parent::ProductParentId, + unit::Unit, + unit_property::UnitPropertyId, + }, +}; + +#[derive(Deserialize, ToSchema)] +struct ProductStub { + /// The name of the product + name: String, + + /// The Unit Property to use for this product. + unit_property: UnitPropertyId, + + /// A description. + #[schema(nullable = false)] + description: Option, + + /// A parent of this product, otherwise the parent will be the root of the parent tree. + #[schema(nullable = false)] + parent: Option, +} + +/// Register a product +#[utoipa::path( + responses( + ( + status = 200, + description = "Product successfully registered in database", + body = ProductId, + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String, + ) + ), + request_body = ProductStub, +)] +#[post("/product/new")] +pub(crate) async fn register_product( + app: web::Data, + product_stub: web::Json, + _user: Identity, +) -> Result { + let product_stub = product_stub.into_inner(); + let mut ops = Operations::new("register product"); + + let product = Product::register( + product_stub.name, + product_stub.description, + product_stub.parent, + product_stub.unit_property, + &mut ops, + ); + + ops.apply(&app).await?; + + Ok(HttpResponse::Ok().json(product.id)) +} + +/// Associate a barcode with a product +#[utoipa::path( + responses( + ( + status = OK, + description = "Barcode successfully associated with product", + ), + ( + status = NOT_FOUND, + description = "Product id not found in database", + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = BAD_REQUEST, + description = "Unit used in request has not been registered yet", + body = String, + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String, + ) + ), + params ( + ( + "id" = ProductId, + description = "The id of the product to associated the barcode with" + ), + ), + request_body = Barcode, +)] +#[post("/product/{id}/associate")] +pub(crate) async fn associate_barcode( + app: web::Data, + id: web::Path, + barcode: web::Json, + _user: Identity, +) -> Result { + let mut ops = Operations::new("associated barcode with product"); + + { + let units = Unit::get_all(&app).await?; + if !units.into_iter().any(|unit| unit.id == barcode.amount.unit) { + return Ok(HttpResponse::BadRequest() + .body("The used unit has not been registered; it cannot be used.\n")); + } + } + + match Product::from_id(&app, id.into_inner().into()).await? { + Some(product) => { + product.associate_barcode(barcode.into_inner(), &mut ops); + + ops.apply(&app).await?; + + Ok(HttpResponse::Ok().finish()) + } + None => Ok(HttpResponse::NotFound().finish()), + } +} diff --git a/crates/rocie-server/src/api/set/auth/product_parent.rs b/crates/rocie-server/src/api/set/auth/product_parent.rs new file mode 100644 index 0000000..416875b --- /dev/null +++ b/crates/rocie-server/src/api/set/auth/product_parent.rs @@ -0,0 +1,67 @@ +use actix_identity::Identity; +use actix_web::{HttpResponse, Responder, Result, post, web}; +use serde::Deserialize; +use utoipa::ToSchema; + +use crate::{ + app::App, + storage::sql::{ + insert::Operations, + product_parent::{ProductParent, ProductParentId}, + }, +}; + +#[derive(Deserialize, ToSchema)] +struct ProductParentStub { + /// The name of the product parent + name: String, + + /// A description. + #[schema(nullable = false)] + description: Option, + + /// A parent of this product parent, otherwise the parent will be the root of the parent tree. + #[schema(nullable = false)] + parent: Option, +} + +/// Register a product parent +#[utoipa::path( + responses( + ( + status = OK, + description = "Product parent successfully registered in database", + body = ProductParentId, + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String, + ) + ), + request_body = ProductParentStub, +)] +#[post("/product_parent/new")] +pub(crate) async fn register_product_parent( + app: web::Data, + product_stub: web::Json, + _user: Identity, +) -> Result { + let product_stub = product_stub.into_inner(); + let mut ops = Operations::new("register product parent"); + + let product = ProductParent::register( + product_stub.name, + product_stub.description, + product_stub.parent, + &mut ops, + ); + + ops.apply(&app).await?; + + Ok(HttpResponse::Ok().json(product.id)) +} diff --git a/crates/rocie-server/src/api/set/auth/recipe.rs b/crates/rocie-server/src/api/set/auth/recipe.rs new file mode 100644 index 0000000..43a034e --- /dev/null +++ b/crates/rocie-server/src/api/set/auth/recipe.rs @@ -0,0 +1,60 @@ +use std::path::PathBuf; + +use actix_identity::Identity; +use actix_web::{HttpResponse, Responder, error::Result, post, web}; +use serde::Deserialize; +use utoipa::ToSchema; + +use crate::{ + app::App, + storage::sql::{ + insert::Operations, + recipe::{Recipe, RecipeId}, + }, +}; + +#[derive(Deserialize, ToSchema)] +struct RecipeStub { + /// The path the recipe should have + #[schema(value_type = String)] + path: PathBuf, + + /// The content of this recipe, in cooklang format + content: String, +} + +/// Register a product parent +#[utoipa::path( + responses( + ( + status = OK, + description = "Product parent successfully registered in database", + body = RecipeId, + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String, + ) + ), + request_body = RecipeStub, +)] +#[post("/recipe/new")] +pub(crate) async fn add_recipe( + app: web::Data, + stub: web::Json, + _user: Identity, +) -> Result { + let stub = stub.into_inner(); + let mut ops = Operations::new("add recipe parent"); + + let recipe = Recipe::new(stub.path, stub.content, &mut ops); + + ops.apply(&app).await?; + + Ok(HttpResponse::Ok().json(recipe.id)) +} diff --git a/crates/rocie-server/src/api/set/auth/unit.rs b/crates/rocie-server/src/api/set/auth/unit.rs new file mode 100644 index 0000000..21d1e11 --- /dev/null +++ b/crates/rocie-server/src/api/set/auth/unit.rs @@ -0,0 +1,67 @@ +use actix_identity::Identity; +use actix_web::{HttpResponse, Responder, Result, post, web}; +use serde::Deserialize; +use utoipa::ToSchema; + +use crate::{ + app::App, + storage::sql::{ + insert::Operations, + unit::{Unit, UnitId}, + unit_property::UnitPropertyId, + }, +}; + +#[derive(Deserialize, ToSchema)] +struct UnitStub { + full_name_plural: String, + full_name_singular: String, + short_name: String, + unit_property: UnitPropertyId, + + #[schema(nullable = false)] + description: Option, +} + +/// Register an Unit +#[utoipa::path( + responses( + ( + status = OK, + description = "Unit successfully registered in database", + body = UnitId, + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String, + ) + ), + request_body = UnitStub, +)] +#[post("/unit/new")] +pub(crate) async fn register_unit( + app: web::Data, + unit: web::Json, + _user: Identity, +) -> Result { + let unit = unit.into_inner(); + let mut ops = Operations::new("register unit"); + + let unit = Unit::register( + unit.full_name_singular, + unit.full_name_plural, + unit.short_name, + unit.description, + unit.unit_property, + &mut ops, + ); + + ops.apply(&app).await?; + + Ok(HttpResponse::Ok().json(unit.id)) +} diff --git a/crates/rocie-server/src/api/set/auth/unit_property.rs b/crates/rocie-server/src/api/set/auth/unit_property.rs new file mode 100644 index 0000000..2958e1f --- /dev/null +++ b/crates/rocie-server/src/api/set/auth/unit_property.rs @@ -0,0 +1,57 @@ +use actix_identity::Identity; +use actix_web::{HttpResponse, Responder, Result, post, web}; +use serde::Deserialize; +use utoipa::ToSchema; + +use crate::{ + app::App, + storage::sql::{ + insert::Operations, + unit_property::{UnitProperty, UnitPropertyId}, + }, +}; + +#[derive(Deserialize, ToSchema)] +struct UnitPropertyStub { + /// The name of the unit property. + name: String, + + /// An optional description of the unit property. + #[schema(nullable = false)] + description: Option, +} + +/// Register an Unit Property +#[utoipa::path( + responses( + ( + status = OK, + description = "Unit property successfully registered in database", + body = UnitPropertyId, + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String, + ) + ), + request_body = UnitPropertyStub, +)] +#[post("/unit-property/new")] +pub(crate) async fn register_unit_property( + app: web::Data, + unit: web::Json, + _user: Identity, +) -> Result { + let mut ops = Operations::new("register unit property"); + + let unit = UnitProperty::register(unit.name.clone(), unit.description.clone(), &mut ops); + + ops.apply(&app).await?; + + Ok(HttpResponse::Ok().json(unit.id)) +} diff --git a/crates/rocie-server/src/api/set/auth/user.rs b/crates/rocie-server/src/api/set/auth/user.rs new file mode 100644 index 0000000..1f262d5 --- /dev/null +++ b/crates/rocie-server/src/api/set/auth/user.rs @@ -0,0 +1,63 @@ +use actix_identity::Identity; +use actix_web::{HttpResponse, Responder, Result, post, web}; +use serde::Deserialize; +use utoipa::ToSchema; + +use crate::{ + app::App, + storage::sql::{ + insert::Operations, + user::{PasswordHash, User, UserId}, + }, +}; + +#[derive(Deserialize, ToSchema)] +pub(crate) struct UserStub { + /// The name of the new user. + pub(crate) name: String, + + /// The password of the new user. + pub(crate) password: String, + + /// An optional description of the new user. + #[schema(nullable = false)] + pub(crate) description: Option, +} + +/// Register an new User +#[utoipa::path( + responses( + ( + status = OK, + description = "User successfully registered in database", + body = UserId, + ), + ( + status = UNAUTHORIZED, + description = "You did not login before calling this endpoint", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String, + ) + ), + request_body = UserStub, +)] +#[post("/user/new")] +pub(crate) async fn register_user( + app: web::Data, + new_user: web::Json, + _user: Identity, +) -> Result { + let user = new_user.into_inner(); + + let mut ops = Operations::new("register user"); + + let password_hash = PasswordHash::from_password(&user.password); + let user = User::register(user.name, password_hash, user.description, &mut ops); + + ops.apply(&app).await?; + + Ok(HttpResponse::Ok().json(user.id)) +} diff --git a/crates/rocie-server/src/api/set/barcode.rs b/crates/rocie-server/src/api/set/barcode.rs deleted file mode 100644 index bb84bbf..0000000 --- a/crates/rocie-server/src/api/set/barcode.rs +++ /dev/null @@ -1,105 +0,0 @@ -use actix_web::{HttpResponse, Responder, Result, post, web}; -use log::debug; - -use crate::{ - app::App, - storage::sql::{ - barcode::{Barcode, BarcodeId, BarcodeIdStub}, - insert::Operations, - unit::UnitAmount, - }, -}; - -/// Buy an barcode -#[utoipa::path( - responses( - ( - status = OK, - description = "Barcode successfully bought", - ), - ( - status = NOT_FOUND, - description = "Barcode id was not found", - ), - ( - status = INTERNAL_SERVER_ERROR, - description = "Server encountered error", - body = String, - ) - ), - params( - ("barcode_id" = BarcodeId, description = "The numeric value of the barcode"), - ("times" = u16, description = "How often to buy the barcode"), - ) -)] -#[post("/barcode/{barcode_id}/buy/{times}")] -pub(crate) async fn buy_barcode( - app: web::Data, - path: web::Path<(BarcodeIdStub, u16)>, -) -> Result { - let (barcode_id, times) = path.into_inner(); - - let mut ops = Operations::new("buy barcode unit"); - - let barcode = Barcode::from_id(&app, barcode_id.into()).await?; - - match barcode { - Some(barcode) => { - for _ in 0..times { - barcode.buy(&mut ops); - } - - ops.apply(&app).await?; - - Ok(HttpResponse::Ok().finish()) - } - None => Ok(HttpResponse::NotFound().finish()), - } -} - -/// Consume an barcode -#[utoipa::path( - responses( - ( - status = OK, - description = "Barcode successfully consumed", - ), - ( - status = NOT_FOUND, - description = "Barcode id was not found", - ), - ( - status = INTERNAL_SERVER_ERROR, - description = "Server encountered error", - body = String, - ) - ), - params( - ("id" = BarcodeId, description = "The numeric value of the barcode"), - ), - request_body = UnitAmount, -)] -#[post("/barcode/{id}/consume")] -pub(crate) async fn consume_barcode( - app: web::Data, - barcode_id: web::Path, - unit_amount: web::Json, -) -> Result { - let mut ops = Operations::new("consume barcode unit"); - - let barcode = Barcode::from_id(&app, barcode_id.into_inner().into()).await?; - debug!("Starting consume for barcode: {barcode:?}"); - - match barcode { - Some(barcode) => { - barcode - .consume(&app, unit_amount.into_inner(), &mut ops) - .await?; - - ops.apply(&app).await?; - - Ok(HttpResponse::Ok().finish()) - } - None => Ok(HttpResponse::NotFound().finish()), - } -} diff --git a/crates/rocie-server/src/api/set/mod.rs b/crates/rocie-server/src/api/set/mod.rs index a6037b9..c6ee9ab 100644 --- a/crates/rocie-server/src/api/set/mod.rs +++ b/crates/rocie-server/src/api/set/mod.rs @@ -1,19 +1,2 @@ -use actix_web::web; - -pub(crate) mod barcode; -pub(crate) mod product; -pub(crate) mod product_parent; -pub(crate) mod recipe; -pub(crate) mod unit; -pub(crate) mod unit_property; - -pub(crate) fn register_paths(cfg: &mut web::ServiceConfig) { - cfg.service(product::register_product) - .service(product::associate_barcode) - .service(product_parent::register_product_parent) - .service(recipe::add_recipe) - .service(unit::register_unit) - .service(unit_property::register_unit_property) - .service(barcode::consume_barcode) - .service(barcode::buy_barcode); -} +pub(crate) mod auth; +pub(crate) mod no_auth; diff --git a/crates/rocie-server/src/api/set/no_auth/mod.rs b/crates/rocie-server/src/api/set/no_auth/mod.rs new file mode 100644 index 0000000..27783fc --- /dev/null +++ b/crates/rocie-server/src/api/set/no_auth/mod.rs @@ -0,0 +1,7 @@ +use actix_web::web; + +pub(crate) mod user; + +pub(crate) fn register_paths(cfg: &mut web::ServiceConfig) { + cfg.service(user::login).service(user::logout).service(user::provision); +} diff --git a/crates/rocie-server/src/api/set/no_auth/user.rs b/crates/rocie-server/src/api/set/no_auth/user.rs new file mode 100644 index 0000000..7acb482 --- /dev/null +++ b/crates/rocie-server/src/api/set/no_auth/user.rs @@ -0,0 +1,131 @@ +use actix_identity::Identity; +use actix_web::{HttpMessage, HttpRequest, HttpResponse, Responder, Result, post, web}; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; + +use crate::{ + api::set::auth::user::UserStub, + app::App, + storage::sql::{ + insert::Operations, + user::{PasswordHash, User, UserId}, + }, +}; + +#[derive(ToSchema, Deserialize, Serialize)] +struct LoginInfo { + /// The id of the user. + id: UserId, + + /// The password of the user. + password: String, +} + +/// Log in as a specific user +#[utoipa::path( + responses( + ( + status = OK, + description = "User logged in", + ), + ( + status = NOT_FOUND, + description = "User id not found" + ), + ( + status = FORBIDDEN, + description = "Password did not match" + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), + request_body = LoginInfo, +)] +#[post("/login")] +async fn login( + request: HttpRequest, + app: web::Data, + info: web::Json, +) -> Result { + let info = info.into_inner(); + + if let Some(user) = User::from_id(&app, info.id).await? { + if user.password_hash.verify(&info.password) { + Identity::login(&request.extensions(), info.id.to_string())?; + Ok(HttpResponse::Ok().finish()) + } else { + Ok(HttpResponse::Forbidden().finish()) + } + } else { + Ok(HttpResponse::NotFound().finish()) + } +} + +/// Log the current user out +#[utoipa::path( + responses( + ( + status = OK, + description = "User logged out", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), +)] +#[post("/logout")] +async fn logout(user: Identity) -> impl Responder { + user.logout(); + HttpResponse::Ok() +} + +/// Provision this instance. +/// +/// This only works, if no users exist yet. +#[utoipa::path( + responses( + ( + status = OK, + description = "User created and logged in", + body = UserId, + ), + ( + status = FORBIDDEN, + description = "Instance already provisioned", + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String + ) + ), + request_body = UserStub, +)] +#[post("/provision")] +async fn provision( + request: HttpRequest, + app: web::Data, + new_user: web::Json, +) -> Result { + if User::get_all(&app).await?.is_empty() { + let user = new_user.into_inner(); + + let mut ops = Operations::new("register user (during provisioning)"); + + let password_hash = PasswordHash::from_password(&user.password); + let user = User::register(user.name, password_hash, user.description, &mut ops); + + ops.apply(&app).await?; + + Identity::login(&request.extensions(), user.id.to_string())?; + + Ok(HttpResponse::Ok().json(user.id)) + } else { + Ok(HttpResponse::Forbidden().finish()) + } +} diff --git a/crates/rocie-server/src/api/set/product.rs b/crates/rocie-server/src/api/set/product.rs deleted file mode 100644 index 74a92d2..0000000 --- a/crates/rocie-server/src/api/set/product.rs +++ /dev/null @@ -1,126 +0,0 @@ -use actix_web::{HttpResponse, Responder, Result, post, web}; -use serde::Deserialize; -use utoipa::ToSchema; - -use crate::{ - app::App, - storage::sql::{ - barcode::Barcode, - insert::Operations, - product::{Product, ProductId, ProductIdStub}, - product_parent::ProductParentId, - unit::Unit, - unit_property::UnitPropertyId, - }, -}; - -#[derive(Deserialize, ToSchema)] -struct ProductStub { - /// The name of the product - name: String, - - /// The Unit Property to use for this product. - unit_property: UnitPropertyId, - - /// A description. - #[schema(nullable = false)] - description: Option, - - /// A parent of this product, otherwise the parent will be the root of the parent tree. - #[schema(nullable = false)] - parent: Option, -} - -/// Register a product -#[utoipa::path( - responses( - ( - status = 200, - description = "Product successfully registered in database", - body = ProductId, - ), - ( - status = INTERNAL_SERVER_ERROR, - description = "Server encountered error", - body = String, - ) - ), - request_body = ProductStub, -)] -#[post("/product/new")] -pub(crate) async fn register_product( - app: web::Data, - product_stub: web::Json, -) -> Result { - let mut ops = Operations::new("register product"); - - let product = Product::register( - product_stub.name.clone(), - product_stub.description.clone(), - product_stub.parent.into(), - product_stub.unit_property, - &mut ops, - ); - - ops.apply(&app).await?; - - Ok(HttpResponse::Ok().json(product.id)) -} - -/// Associate a barcode with a product -#[utoipa::path( - responses( - ( - status = OK, - description = "Barcode successfully associated with product", - ), - ( - status = NOT_FOUND, - description = "Product id not found in database", - ), - ( - status = FORBIDDEN, - description = "Unit used in request has not been registered yet", - body = String, - ), - ( - status = INTERNAL_SERVER_ERROR, - description = "Server encountered error", - body = String, - ) - ), - params ( - ( - "id" = ProductId, - description = "The id of the product to associated the barcode with" - ), - ), - request_body = Barcode, -)] -#[post("/product/{id}/associate")] -pub(crate) async fn associate_barcode( - app: web::Data, - id: web::Path, - barcode: web::Json, -) -> Result { - let mut ops = Operations::new("associated barcode with product"); - - { - let units = Unit::get_all(&app).await?; - if !units.into_iter().any(|unit| unit.id == barcode.amount.unit) { - return Ok(HttpResponse::Forbidden() - .body("The used unit has not been registered; it cannot be used.\n")); - } - } - - match Product::from_id(&app, id.into_inner().into()).await? { - Some(product) => { - product.associate_barcode(barcode.into_inner(), &mut ops); - - ops.apply(&app).await?; - - Ok(HttpResponse::Ok().finish()) - } - None => Ok(HttpResponse::NotFound().finish()), - } -} diff --git a/crates/rocie-server/src/api/set/product_parent.rs b/crates/rocie-server/src/api/set/product_parent.rs deleted file mode 100644 index f917207..0000000 --- a/crates/rocie-server/src/api/set/product_parent.rs +++ /dev/null @@ -1,60 +0,0 @@ -use actix_web::{HttpResponse, Responder, Result, post, web}; -use serde::Deserialize; -use utoipa::ToSchema; - -use crate::{ - app::App, - storage::sql::{ - insert::Operations, - product_parent::{ProductParent, ProductParentId}, - }, -}; - -#[derive(Deserialize, ToSchema)] -struct ProductParentStub { - /// The name of the product parent - name: String, - - /// A description. - #[schema(nullable = false)] - description: Option, - - /// A parent of this product parent, otherwise the parent will be the root of the parent tree. - #[schema(nullable = false)] - parent: Option, -} - -/// Register a product parent -#[utoipa::path( - responses( - ( - status = 200, - description = "Product parent successfully registered in database", - body = ProductParentId, - ), - ( - status = INTERNAL_SERVER_ERROR, - description = "Server encountered error", - body = String, - ) - ), - request_body = ProductParentStub, -)] -#[post("/product_parent/new")] -pub(crate) async fn register_product_parent( - app: web::Data, - product_stub: web::Json, -) -> Result { - let mut ops = Operations::new("register product parent"); - - let product = ProductParent::register( - product_stub.name.clone(), - product_stub.description.clone(), - product_stub.parent.into(), - &mut ops, - ); - - ops.apply(&app).await?; - - Ok(HttpResponse::Ok().json(product.id)) -} diff --git a/crates/rocie-server/src/api/set/recipe.rs b/crates/rocie-server/src/api/set/recipe.rs deleted file mode 100644 index bb5be37..0000000 --- a/crates/rocie-server/src/api/set/recipe.rs +++ /dev/null @@ -1,54 +0,0 @@ -use std::path::PathBuf; - -use actix_web::{HttpResponse, Responder, error::Result, post, web}; -use serde::Deserialize; -use utoipa::ToSchema; - -use crate::{ - app::App, - storage::sql::{ - insert::Operations, - recipe::{Recipe, RecipeId}, - }, -}; - -#[derive(Deserialize, ToSchema)] -struct RecipeStub { - /// The path the recipe should have - #[schema(value_type = String)] - path: PathBuf, - - /// The content of this recipe, in cooklang format - content: String, -} - -/// Register a product parent -#[utoipa::path( - responses( - ( - status = 200, - description = "Product parent successfully registered in database", - body = RecipeId, - ), - ( - status = INTERNAL_SERVER_ERROR, - description = "Server encountered error", - body = String, - ) - ), - request_body = RecipeStub, -)] -#[post("/recipe/new")] -pub(crate) async fn add_recipe( - app: web::Data, - stub: web::Json, -) -> Result { - let stub = stub.into_inner(); - let mut ops = Operations::new("add recipe parent"); - - let recipe = Recipe::new(stub.path, stub.content, &mut ops); - - ops.apply(&app).await?; - - Ok(HttpResponse::Ok().json(recipe.id)) -} diff --git a/crates/rocie-server/src/api/set/unit.rs b/crates/rocie-server/src/api/set/unit.rs deleted file mode 100644 index 1671918..0000000 --- a/crates/rocie-server/src/api/set/unit.rs +++ /dev/null @@ -1,60 +0,0 @@ -use actix_web::{HttpResponse, Responder, Result, post, web}; -use serde::Deserialize; -use utoipa::ToSchema; - -use crate::{ - app::App, - storage::sql::{ - insert::Operations, - unit::{Unit, UnitId}, - unit_property::UnitPropertyId, - }, -}; - -#[derive(Deserialize, ToSchema)] -struct UnitStub { - full_name_plural: String, - full_name_singular: String, - short_name: String, - unit_property: UnitPropertyId, - - #[schema(nullable = false)] - description: Option, -} - -/// Register an Unit -#[utoipa::path( - responses( - ( - status = 200, - description = "Unit successfully registered in database", - body = UnitId, - ), - ( - status = INTERNAL_SERVER_ERROR, - description = "Server encountered error", - body = String, - ) - ), - request_body = UnitStub, -)] -#[post("/unit/new")] -pub(crate) async fn register_unit( - app: web::Data, - unit: web::Json, -) -> Result { - let mut ops = Operations::new("register unit"); - - let unit = Unit::register( - unit.full_name_singular.clone(), - unit.full_name_plural.clone(), - unit.short_name.clone(), - unit.description.clone(), - unit.unit_property, - &mut ops, - ); - - ops.apply(&app).await?; - - Ok(HttpResponse::Ok().json(unit.id)) -} diff --git a/crates/rocie-server/src/api/set/unit_property.rs b/crates/rocie-server/src/api/set/unit_property.rs deleted file mode 100644 index ca2960f..0000000 --- a/crates/rocie-server/src/api/set/unit_property.rs +++ /dev/null @@ -1,51 +0,0 @@ -use actix_web::{HttpResponse, Responder, Result, post, web}; -use serde::Deserialize; -use utoipa::ToSchema; - -use crate::{ - app::App, - storage::sql::{ - insert::Operations, - unit_property::{UnitProperty, UnitPropertyId}, - }, -}; - -#[derive(Deserialize, ToSchema)] -struct UnitPropertyStub { - /// The name of the unit property. - name: String, - - /// An optional description of the unit property. - #[schema(nullable = false)] - description: Option, -} - -/// Register an Unit Property -#[utoipa::path( - responses( - ( - status = 200, - description = "Unit property successfully registered in database", - body = UnitPropertyId, - ), - ( - status = INTERNAL_SERVER_ERROR, - description = "Server encountered error", - body = String, - ) - ), - request_body = UnitPropertyStub, -)] -#[post("/unit-property/new")] -pub(crate) async fn register_unit_property( - app: web::Data, - unit: web::Json, -) -> Result { - let mut ops = Operations::new("register unit property"); - - let unit = UnitProperty::register(unit.name.clone(), unit.description.clone(), &mut ops); - - ops.apply(&app).await?; - - Ok(HttpResponse::Ok().json(unit.id)) -} diff --git a/crates/rocie-server/src/cli.rs b/crates/rocie-server/src/cli.rs index 80b4292..01c4199 100644 --- a/crates/rocie-server/src/cli.rs +++ b/crates/rocie-server/src/cli.rs @@ -20,7 +20,7 @@ pub(crate) enum Command { /// Print the used port as single u16 to stdout when started. /// - /// This can be used, to determine the used port, when the `port` was left at `None`. + /// This can be used to determine the used port, when the `port` was left at `None`. #[arg(long)] print_port: bool, diff --git a/crates/rocie-server/src/main.rs b/crates/rocie-server/src/main.rs index dc5be0b..caa210d 100644 --- a/crates/rocie-server/src/main.rs +++ b/crates/rocie-server/src/main.rs @@ -26,39 +26,42 @@ use actix_session::{SessionMiddleware, storage::CookieSessionStore}; async fn main() -> Result<(), std::io::Error> { #[derive(OpenApi)] #[openapi( - paths( - api::get::product::product_by_id, - api::get::product::product_by_name, - api::get::product::product_suggestion_by_name, - api::get::product::products_registered, - api::get::product::products_in_storage, - api::get::product::products_by_product_parent_id_indirect, - api::get::product::products_by_product_parent_id_direct, - api::get::product_parent::product_parents, - api::get::product_parent::product_parents_toplevel, - api::get::product_parent::product_parents_under, - api::get::recipe::recipe_by_id, - api::get::recipe::recipes, - api::get::unit::units, - api::get::unit::units_by_property_id, - api::get::unit::unit_by_id, - api::get::unit_property::unit_property_by_id, - api::get::unit_property::unit_properties, - api::get::inventory::amount_by_id, - api::set::product::register_product, - api::set::product::associate_barcode, - api::set::product_parent::register_product_parent, - api::set::recipe::add_recipe, - api::set::unit::register_unit, - api::set::unit_property::register_unit_property, - api::set::barcode::buy_barcode, - api::set::barcode::consume_barcode, + paths( + api::get::auth::product::product_by_id, + api::get::auth::product::product_by_name, + api::get::auth::product::product_suggestion_by_name, + api::get::auth::product::products_registered, + api::get::auth::product::products_in_storage, + api::get::auth::product::products_by_product_parent_id_indirect, + api::get::auth::product::products_by_product_parent_id_direct, + api::get::auth::product_parent::product_parents, + api::get::auth::product_parent::product_parents_toplevel, + api::get::auth::product_parent::product_parents_under, + api::get::auth::recipe::recipe_by_id, + api::get::auth::recipe::recipes, + api::get::auth::unit::units, + api::get::auth::unit::units_by_property_id, + api::get::auth::unit::unit_by_id, + api::get::auth::unit_property::unit_property_by_id, + api::get::auth::unit_property::unit_properties, + api::get::auth::inventory::amount_by_id, + api::get::auth::user::users, + api::get::auth::user::user_by_id, + // + api::set::auth::product::register_product, + api::set::auth::product::associate_barcode, + api::set::auth::product_parent::register_product_parent, + api::set::auth::recipe::add_recipe, + api::set::auth::unit::register_unit, + api::set::auth::unit_property::register_unit_property, + api::set::auth::barcode::buy_barcode, + api::set::auth::barcode::consume_barcode, + api::set::auth::user::register_user, + // + api::set::no_auth::user::login, + api::set::no_auth::user::logout, + api::set::no_auth::user::provision, ), - // security( - // (), - // ("my_auth" = ["read:items", "edit:items"]), - // ("token_jwt" = []) - // ), )] struct ApiDoc; @@ -67,6 +70,7 @@ async fn main() -> Result<(), std::io::Error> { // When using `Key::generate()` it is important to initialize outside of the // `HttpServer::new` closure. When deployed the secret key should be read from a // configuration file or environment variables. + // TODO: Load from a config file. <2025-12-07> let secret_key = Key::generate(); let args = CliArgs::parse(); @@ -91,7 +95,7 @@ async fn main() -> Result<(), std::io::Error> { .wrap(Logger::new( r#"%a "%r" -> %s %b ("%{Referer}i" "%{User-Agent}i" %T s)"#, )) - // Install the identity framework before middle-ware (as actix is filo). + // Install the identity framework before middleware (as actix uses FILO). .wrap(IdentityMiddleware::default()) .wrap( SessionMiddleware::builder( @@ -104,8 +108,10 @@ async fn main() -> Result<(), std::io::Error> { .build(), ) .app_data(Data::clone(&data)) - .configure(api::get::register_paths) - .configure(api::set::register_paths) + .configure(api::get::auth::register_paths) + .configure(api::get::no_auth::register_paths) + .configure(api::set::auth::register_paths) + .configure(api::set::no_auth::register_paths) }) .bind((host, port.unwrap_or(0)))?; @@ -121,6 +127,7 @@ async fn main() -> Result<(), std::io::Error> { } Command::OpenApi => { let openapi = ApiDoc::openapi(); + println!("{}", openapi.to_pretty_json().expect("Comp-time constant")); Ok(()) } diff --git a/crates/rocie-server/src/storage/migrate/sql/0->1.sql b/crates/rocie-server/src/storage/migrate/sql/0->1.sql index 664f40f..e3dd879 100644 --- a/crates/rocie-server/src/storage/migrate/sql/0->1.sql +++ b/crates/rocie-server/src/storage/migrate/sql/0->1.sql @@ -27,6 +27,14 @@ CREATE TABLE parents ( FOREIGN KEY(parent) REFERENCES parents(id) ) STRICT; +-- Stores the registered users. +CREATE TABLE users ( + id TEXT UNIQUE NOT NULL PRIMARY KEY, + name TEXT UNIQUE NOT NULL, + password_hash TEXT NOT NULL, + description TEXT +) STRICT; + -- Record with barcodes were bought, and how much of this buy is already used up. CREATE TABLE buys ( buy_id TEXT UNIQUE NOT NULL PRIMARY KEY, diff --git a/crates/rocie-server/src/storage/sql/get/mod.rs b/crates/rocie-server/src/storage/sql/get/mod.rs index 1fb54b0..92b34aa 100644 --- a/crates/rocie-server/src/storage/sql/get/mod.rs +++ b/crates/rocie-server/src/storage/sql/get/mod.rs @@ -1,7 +1,8 @@ +pub(crate) mod barcode; pub(crate) mod product; -pub(crate) mod product_parent; pub(crate) mod product_amount; +pub(crate) mod product_parent; +pub(crate) mod recipe; pub(crate) mod unit; pub(crate) mod unit_property; -pub(crate) mod barcode; -pub(crate) mod recipe; +pub(crate) mod user; diff --git a/crates/rocie-server/src/storage/sql/get/user/mod.rs b/crates/rocie-server/src/storage/sql/get/user/mod.rs new file mode 100644 index 0000000..e36c6cf --- /dev/null +++ b/crates/rocie-server/src/storage/sql/get/user/mod.rs @@ -0,0 +1,77 @@ +use crate::{ + app::App, + storage::sql::user::{PasswordHash, User, UserId}, +}; + +use sqlx::query; + +impl User { + pub(crate) async fn get_all(app: &App) -> Result, get_all::Error> { + let records = query!( + " + SELECT id, name, password_hash, description + FROM users +" + ) + .fetch_all(&app.db) + .await?; + + Ok(records + .into_iter() + .map(|record| Self { + id: UserId::from_db(&record.id), + name: record.name, + password_hash: PasswordHash::from_db(record.password_hash), + description: record.description, + }) + .collect()) + } + + pub(crate) async fn from_id(app: &App, id: UserId) -> Result, from_id::Error> { + let record = query!( + " + SELECT name, password_hash, description + FROM users + WHERE id = ? +", + id + ) + .fetch_optional(&app.db) + .await?; + + if let Some(record) = record { + Ok(Some(Self { + name: record.name, + description: record.description, + id, + password_hash: PasswordHash::from_db(record.password_hash), + })) + } else { + Ok(None) + } + } +} + +pub(crate) mod get_all { + use actix_web::ResponseError; + + #[derive(thiserror::Error, Debug)] + pub(crate) enum Error { + #[error("Failed to execute the sql query")] + SqlError(#[from] sqlx::Error), + } + + impl ResponseError for Error {} +} + +pub(crate) mod from_id { + use actix_web::ResponseError; + + #[derive(thiserror::Error, Debug)] + pub(crate) enum Error { + #[error("Failed to execute the sql query")] + SqlError(#[from] sqlx::Error), + } + + impl ResponseError for Error {} +} diff --git a/crates/rocie-server/src/storage/sql/insert/mod.rs b/crates/rocie-server/src/storage/sql/insert/mod.rs index 8a15385..54717c3 100644 --- a/crates/rocie-server/src/storage/sql/insert/mod.rs +++ b/crates/rocie-server/src/storage/sql/insert/mod.rs @@ -13,6 +13,7 @@ pub(crate) mod product_parent; pub(crate) mod unit; pub(crate) mod unit_property; pub(crate) mod recipe; +pub(crate) mod user; pub(crate) trait Transactionable: Sized + std::fmt::Debug + Serialize + DeserializeOwned diff --git a/crates/rocie-server/src/storage/sql/insert/user/mod.rs b/crates/rocie-server/src/storage/sql/insert/user/mod.rs new file mode 100644 index 0000000..325253e --- /dev/null +++ b/crates/rocie-server/src/storage/sql/insert/user/mod.rs @@ -0,0 +1,117 @@ +use serde::{Deserialize, Serialize}; +use sqlx::query; +use uuid::Uuid; + +use crate::storage::sql::{ + insert::{Operations, Transactionable}, + user::{PasswordHash, User, UserId}, +}; + +#[derive(Debug, Deserialize, Serialize)] +pub(crate) enum Operation { + RegisterUser { + id: UserId, + name: String, + description: Option, + password_hash: PasswordHash, + }, +} + +impl Transactionable for Operation { + type ApplyError = apply::Error; + type UndoError = undo::Error; + + async fn apply(self, txn: &mut sqlx::SqliteConnection) -> Result<(), apply::Error> { + match self { + Operation::RegisterUser { + id, + name, + description, + password_hash, + } => { + let password_hash = password_hash.to_string(); + + query!( + " + INSERT INTO users (id, name, password_hash, description) + VALUES (?,?,?,?) +", + id, + name, + password_hash, + description, + ) + .execute(txn) + .await?; + } + } + Ok(()) + } + + async fn undo(self, txn: &mut sqlx::SqliteConnection) -> Result<(), undo::Error> { + match self { + Operation::RegisterUser { + id, + name, + description, + password_hash, + } => { + let password_hash = password_hash.to_string(); + + query!( + " + DELETE FROM users + WHERE id = ? AND name = ? AND description = ? AND password_hash = ?; +", + id, + name, + description, + password_hash, + ) + .execute(txn) + .await?; + } + } + Ok(()) + } +} + +pub(crate) mod undo { + #[derive(thiserror::Error, Debug)] + pub(crate) enum Error { + #[error("Failed to execute undo sql statments: {0}")] + SqlError(#[from] sqlx::Error), + } +} +pub(crate) mod apply { + #[derive(thiserror::Error, Debug)] + pub(crate) enum Error { + #[error("Failed to execute apply sql statments: {0}")] + SqlError(#[from] sqlx::Error), + } +} + +impl User { + pub(crate) fn register( + name: String, + password_hash: PasswordHash, + description: Option, + ops: &mut Operations, + ) -> Self { + let id = UserId::from(Uuid::new_v4()); + + ops.push(Operation::RegisterUser { + id, + name: name.clone(), + description: description.clone(), + password_hash: password_hash.clone(), + }); + + Self { + id, + name, + description, + password_hash, + } + } +} diff --git a/crates/rocie-server/src/storage/sql/mod.rs b/crates/rocie-server/src/storage/sql/mod.rs index dd46eab..315c251 100644 --- a/crates/rocie-server/src/storage/sql/mod.rs +++ b/crates/rocie-server/src/storage/sql/mod.rs @@ -9,6 +9,7 @@ pub(crate) mod product_parent; pub(crate) mod recipe; pub(crate) mod unit; pub(crate) mod unit_property; +pub(crate) mod user; macro_rules! mk_id { ($name:ident and $stub_name:ident) => { diff --git a/crates/rocie-server/src/storage/sql/user.rs b/crates/rocie-server/src/storage/sql/user.rs new file mode 100644 index 0000000..2bac555 --- /dev/null +++ b/crates/rocie-server/src/storage/sql/user.rs @@ -0,0 +1,86 @@ +use std::fmt::Display; + +use argon2::{ + Argon2, PasswordHasher, PasswordVerifier, + password_hash::{SaltString, rand_core::OsRng}, +}; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; + +use crate::storage::sql::mk_id; + +/// The definition of an rocie user. +#[derive(ToSchema, Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Deserialize)] +pub(crate) struct User { + /// The unique ID for this user. + pub(crate) id: UserId, + + /// The user-displayed name of this user. + pub(crate) name: String, + + /// The hash of the user's password. + pub(crate) password_hash: PasswordHash, + + /// An description of this user. + #[schema(nullable = false)] + pub(crate) description: Option, +} + +/// This is stored as an PHC password string. +/// +/// This type corresponds to the string representation of a PHC string as +/// described in the [PHC string format specification][1]. +/// +/// PHC strings have the following format: +/// +/// ```text +/// $[$v=][$=(,=)*][$[$]] +/// ``` +#[derive(ToSchema, Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Deserialize)] +pub(crate) struct PasswordHash { + value: String, +} +impl PasswordHash { + pub(crate) fn from_db(password_hash: String) -> PasswordHash { + Self { + value: password_hash, + } + } + + pub(crate) fn from_password(password: &str) -> Self { + let salt = SaltString::generate(&mut OsRng); + + let argon2 = Argon2::default(); + + let password_hash = argon2 + .hash_password(password.as_bytes(), &salt) + .expect("to not fail") + .to_string(); + + Self { + value: password_hash, + } + } + + /// Check that self, and the other password have the same hash. + pub(crate) fn verify(&self, other: &str) -> bool { + let argon2 = Argon2::default(); + + argon2 + .verify_password(other.as_bytes(), &self.as_argon_hash()) + .is_ok() + } + + fn as_argon_hash(&self) -> argon2::PasswordHash<'_> { + argon2::PasswordHash::new(&self.value) + .expect("to be valid, as we are just deserializing a previously serialize value") + } +} + +impl Display for PasswordHash { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.value.fmt(f) + } +} + +mk_id!(UserId and UserIdStub); diff --git a/crates/rocie-server/tests/_testenv/init.rs b/crates/rocie-server/tests/_testenv/init.rs index 9cb0b91..5318238 100644 --- a/crates/rocie-server/tests/_testenv/init.rs +++ b/crates/rocie-server/tests/_testenv/init.rs @@ -19,9 +19,15 @@ use std::{ process::{self, Stdio}, }; -use rocie_client::apis::configuration::Configuration; +use rocie_client::{ + apis::{api_set_no_auth_user_api::provision, configuration::Configuration}, + models::{LoginInfo, UserStub}, +}; -use crate::{_testenv::Paths, testenv::TestEnv}; +use crate::{ + _testenv::{Paths, log::request}, + testenv::TestEnv, +}; macro_rules! function_name { () => {{ @@ -105,7 +111,22 @@ fn rocie_server_args(paths: &Paths) -> [&OsStr; 4] { } impl TestEnv { - pub(crate) fn new(name: &'static str) -> TestEnv { + pub(crate) async fn new(name: &'static str) -> TestEnv { + let env = Self::new_no_login(name); + + request!( + env, + provision(UserStub { + description: Some("Test user, used during test runs".to_string()), + name: "rocie".to_string(), + password: "server".to_string() + }) + ); + + env + } + + pub(crate) fn new_no_login(name: &'static str) -> TestEnv { let test_dir = test_dir(name); let paths = prepare_files_and_dirs(&test_dir) diff --git a/crates/rocie-server/tests/product_parents/query.rs b/crates/rocie-server/tests/product_parents/query.rs index 6d16ca3..635a0ba 100644 --- a/crates/rocie-server/tests/product_parents/query.rs +++ b/crates/rocie-server/tests/product_parents/query.rs @@ -1,10 +1,10 @@ use rocie_client::{ apis::{ - api_get_product_api::{products_by_product_parent_id_direct, products_by_product_parent_id_indirect}, - api_get_product_parent_api::{product_parents_toplevel, product_parents_under}, - api_set_product_api::register_product, - api_set_product_parent_api::register_product_parent, - api_set_unit_property_api::register_unit_property, + api_get_auth_product_api::{products_by_product_parent_id_direct, products_by_product_parent_id_indirect}, + api_get_auth_product_parent_api::{product_parents_toplevel, product_parents_under}, + api_set_auth_product_api::register_product, + api_set_auth_product_parent_api::register_product_parent, + api_set_auth_unit_property_api::register_unit_property, }, models::{ProductParentStub, ProductStub, UnitPropertyStub}, }; @@ -16,7 +16,7 @@ use crate::{ #[tokio::test] async fn test_product_parent_query() { - let env = TestEnv::new(function_name!()); + let env = TestEnv::new(function_name!()).await; let parent_dairy = request!( env, @@ -63,7 +63,7 @@ async fn test_product_parent_query() { #[tokio::test] async fn test_product_parent_query_product() { - let env = TestEnv::new(function_name!()); + let env = TestEnv::new(function_name!()).await; let parent_dairy = request!( env, diff --git a/crates/rocie-server/tests/product_parents/register.rs b/crates/rocie-server/tests/product_parents/register.rs index c84ffea..c9e48f2 100644 --- a/crates/rocie-server/tests/product_parents/register.rs +++ b/crates/rocie-server/tests/product_parents/register.rs @@ -1,8 +1,8 @@ use rocie_client::{ apis::{ - api_get_product_api::product_by_id, api_set_product_api::register_product, - api_set_product_parent_api::register_product_parent, - api_set_unit_property_api::register_unit_property, + api_get_auth_product_api::product_by_id, api_set_auth_product_api::register_product, + api_set_auth_product_parent_api::register_product_parent, + api_set_auth_unit_property_api::register_unit_property, }, models::{ProductParentStub, ProductStub, UnitPropertyStub}, }; @@ -14,7 +14,7 @@ use crate::{ #[tokio::test] async fn test_product_parent_register_roundtrip() { - let env = TestEnv::new(function_name!()); + let env = TestEnv::new(function_name!()).await; let parent_dairy = request!( env, diff --git a/crates/rocie-server/tests/products/barcode.rs b/crates/rocie-server/tests/products/barcode.rs index 5335eb7..7b48ab7 100644 --- a/crates/rocie-server/tests/products/barcode.rs +++ b/crates/rocie-server/tests/products/barcode.rs @@ -1,10 +1,10 @@ use rocie_client::{ apis::{ - api_get_inventory_api::amount_by_id, - api_set_barcode_api::{buy_barcode, consume_barcode}, - api_set_product_api::{associate_barcode, register_product}, - api_set_unit_api::register_unit, - api_set_unit_property_api::register_unit_property, + api_get_auth_inventory_api::amount_by_id, + api_set_auth_barcode_api::{buy_barcode, consume_barcode}, + api_set_auth_product_api::{associate_barcode, register_product}, + api_set_auth_unit_api::register_unit, + api_set_auth_unit_property_api::register_unit_property, }, models::{Barcode, BarcodeId, ProductStub, UnitAmount, UnitPropertyStub, UnitStub}, }; @@ -17,7 +17,7 @@ use crate::{ #[tokio::test] async fn test_barcode_buy() { - let env = TestEnv::new(function_name!()); + let env = TestEnv::new(function_name!()).await; let barcode_id = 23; let unit_value = 1; @@ -36,7 +36,7 @@ async fn test_barcode_buy() { #[tokio::test] async fn test_barcode_buy_multiple() { - let env = TestEnv::new(function_name!()); + let env = TestEnv::new(function_name!()).await; let barcode_id = 23; let unit_value = 1; @@ -55,7 +55,7 @@ async fn test_barcode_buy_multiple() { #[tokio::test] async fn test_barcode_consume() { - let env = TestEnv::new(function_name!()); + let env = TestEnv::new(function_name!()).await; let barcode_id = BarcodeId { value: 23 }; let unit_value = 1; @@ -92,7 +92,7 @@ async fn test_barcode_consume() { #[tokio::test] async fn test_barcode_consume_error() { - let env = TestEnv::new(function_name!()); + let env = TestEnv::new(function_name!()).await; let barcode_id = BarcodeId { value: 23 }; let unit_value = 1; @@ -131,7 +131,7 @@ async fn test_barcode_consume_error() { #[tokio::test] async fn test_barcode_consume_error_other() { - let env = TestEnv::new(function_name!()); + let env = TestEnv::new(function_name!()).await; let barcode_id = BarcodeId { value: 23 }; let unit_value = 1; @@ -181,7 +181,7 @@ async fn test_barcode_consume_error_other() { #[tokio::test] async fn test_barcode_multiple_buy_and_consume() { - let env = TestEnv::new(function_name!()); + let env = TestEnv::new(function_name!()).await; let barcode_id = BarcodeId { value: 23 }; let unit_value = 1; @@ -237,7 +237,7 @@ async fn test_barcode_multiple_buy_and_consume() { #[tokio::test] async fn test_barcode_fill_up() { - let env = TestEnv::new(function_name!()); + let env = TestEnv::new(function_name!()).await; let milk_id = BarcodeId { value: 23 }; let bread_id = BarcodeId { value: 24 }; @@ -254,7 +254,7 @@ async fn test_barcode_fill_up() { #[tokio::test] async fn test_barcode_associate_false_unit() { - let env = TestEnv::new(function_name!()); + let env = TestEnv::new(function_name!()).await; let unit_property_mass = request!( env, diff --git a/crates/rocie-server/tests/products/mod.rs b/crates/rocie-server/tests/products/mod.rs index ee139f0..e503684 100644 --- a/crates/rocie-server/tests/products/mod.rs +++ b/crates/rocie-server/tests/products/mod.rs @@ -1,8 +1,8 @@ use rocie_client::{ apis::{ - api_set_product_api::{associate_barcode, register_product}, - api_set_unit_api::register_unit, - api_set_unit_property_api::register_unit_property, + api_set_auth_product_api::{associate_barcode, register_product}, + api_set_auth_unit_api::register_unit, + api_set_auth_unit_property_api::register_unit_property, }, models::{ Barcode, BarcodeId, ProductId, ProductStub, UnitAmount, UnitId, UnitPropertyId, diff --git a/crates/rocie-server/tests/products/query.rs b/crates/rocie-server/tests/products/query.rs index 8adfbb5..b2095cb 100644 --- a/crates/rocie-server/tests/products/query.rs +++ b/crates/rocie-server/tests/products/query.rs @@ -1,7 +1,7 @@ use rocie_client::{ apis::{ - api_get_product_api::{product_by_name, product_suggestion_by_name}, - api_set_unit_property_api::register_unit_property, + api_get_auth_product_api::{product_by_name, product_suggestion_by_name}, + api_set_auth_unit_property_api::register_unit_property, }, models::UnitPropertyStub, }; @@ -14,7 +14,7 @@ use crate::{ #[tokio::test] #[expect(clippy::similar_names)] async fn test_product_name_suggestions() { - let env = TestEnv::new(function_name!()); + let env = TestEnv::new(function_name!()).await; let unit_property = request!( env, @@ -46,7 +46,7 @@ async fn test_product_name_suggestions() { #[tokio::test] async fn test_product_name_suggest_space() { - let env = TestEnv::new(function_name!()); + let env = TestEnv::new(function_name!()).await; let unit_property = request!( env, @@ -68,7 +68,7 @@ async fn test_product_name_suggest_space() { #[tokio::test] async fn test_product_name_lookup_space() { - let env = TestEnv::new(function_name!()); + let env = TestEnv::new(function_name!()).await; let unit_property = request!( env, @@ -87,7 +87,7 @@ async fn test_product_name_lookup_space() { #[tokio::test] async fn test_product_name_lookup_fancy() { - let env = TestEnv::new(function_name!()); + let env = TestEnv::new(function_name!()).await; let unit_property = request!( env, @@ -106,7 +106,7 @@ async fn test_product_name_lookup_fancy() { #[tokio::test] async fn test_product_name_lookup_emoji() { - let env = TestEnv::new(function_name!()); + let env = TestEnv::new(function_name!()).await; let unit_property = request!( env, @@ -125,7 +125,7 @@ async fn test_product_name_lookup_emoji() { #[tokio::test] async fn test_product_name_lookup_plus() { - let env = TestEnv::new(function_name!()); + let env = TestEnv::new(function_name!()).await; let unit_property = request!( env, diff --git a/crates/rocie-server/tests/products/register.rs b/crates/rocie-server/tests/products/register.rs index bae7bc7..2d4bf7e 100644 --- a/crates/rocie-server/tests/products/register.rs +++ b/crates/rocie-server/tests/products/register.rs @@ -1,7 +1,7 @@ use rocie_client::{ apis::{ - api_get_product_api::product_by_id, api_set_product_api::register_product, - api_set_unit_property_api::register_unit_property, + api_get_auth_product_api::product_by_id, api_set_auth_product_api::register_product, + api_set_auth_unit_property_api::register_unit_property, }, models::{ProductStub, UnitPropertyStub}, }; @@ -13,7 +13,7 @@ use crate::{ #[tokio::test] async fn test_product_register_roundtrip() { - let env = TestEnv::new(function_name!()); + let env = TestEnv::new(function_name!()).await; let unit_property = request!( env, diff --git a/crates/rocie-server/tests/recipies/mod.rs b/crates/rocie-server/tests/recipies/mod.rs index e8aa3c2..dfc8983 100644 --- a/crates/rocie-server/tests/recipies/mod.rs +++ b/crates/rocie-server/tests/recipies/mod.rs @@ -1,5 +1,5 @@ use rocie_client::{ - apis::{api_get_recipe_api::recipe_by_id, api_set_recipe_api::add_recipe}, + apis::{api_get_auth_recipe_api::recipe_by_id, api_set_auth_recipe_api::add_recipe}, models::RecipeStub, }; @@ -7,7 +7,7 @@ use crate::testenv::{TestEnv, init::function_name, log::request}; #[tokio::test] async fn test_recipe_roundtrip() { - let env = TestEnv::new(function_name!()); + let env = TestEnv::new(function_name!()).await; let recipe_id = request!( env, diff --git a/crates/rocie-server/tests/tests.rs b/crates/rocie-server/tests/tests.rs index 3759042..4a218d1 100644 --- a/crates/rocie-server/tests/tests.rs +++ b/crates/rocie-server/tests/tests.rs @@ -7,3 +7,4 @@ mod products; mod product_parents; mod units; mod recipies; +mod users; diff --git a/crates/rocie-server/tests/units/fetch.rs b/crates/rocie-server/tests/units/fetch.rs index b0bfffb..a0ffd9b 100644 --- a/crates/rocie-server/tests/units/fetch.rs +++ b/crates/rocie-server/tests/units/fetch.rs @@ -1,7 +1,7 @@ use rocie_client::{ apis::{ - api_get_unit_api::units_by_property_id, api_set_unit_api::register_unit, - api_set_unit_property_api::register_unit_property, + api_get_auth_unit_api::units_by_property_id, api_set_auth_unit_api::register_unit, + api_set_auth_unit_property_api::register_unit_property, }, models::{UnitPropertyStub, UnitStub}, }; @@ -10,7 +10,7 @@ use crate::testenv::{TestEnv, init::function_name, log::request}; #[tokio::test] async fn test_units_fetch_by_property_id() { - let env = TestEnv::new(function_name!()); + let env = TestEnv::new(function_name!()).await; let unit_property = request!( env, diff --git a/crates/rocie-server/tests/units/register.rs b/crates/rocie-server/tests/units/register.rs index 8181c25..e725a5c 100644 --- a/crates/rocie-server/tests/units/register.rs +++ b/crates/rocie-server/tests/units/register.rs @@ -1,7 +1,7 @@ use rocie_client::{ apis::{ - api_get_unit_api::unit_by_id, api_set_unit_api::register_unit, - api_set_unit_property_api::register_unit_property, + api_get_auth_unit_api::unit_by_id, api_set_auth_unit_api::register_unit, + api_set_auth_unit_property_api::register_unit_property, }, models::{UnitPropertyStub, UnitStub}, }; @@ -13,7 +13,7 @@ use crate::{ #[tokio::test] async fn test_unit_register_roundtrip() { - let env = TestEnv::new(function_name!()); + let env = TestEnv::new(function_name!()).await; let unit_property = request!( env, diff --git a/crates/rocie-server/tests/users/mod.rs b/crates/rocie-server/tests/users/mod.rs new file mode 100644 index 0000000..eaa387f --- /dev/null +++ b/crates/rocie-server/tests/users/mod.rs @@ -0,0 +1,53 @@ +use rocie_client::{ + apis::{ + api_get_no_auth_user_api::user_by_id, + api_set_auth_user_api::register_user, + api_set_no_auth_user_api::{login, logout}, + }, + models::{LoginInfo, UserStub}, +}; + +use crate::testenv::{TestEnv, init::function_name, log::request}; + +#[tokio::test] +async fn test_register_user() { + let env = TestEnv::new_no_login(function_name!()); + + let user_id = request!( + env, + register_user(UserStub { + description: Some("Myself".to_string()), + name: "me".to_string(), + password: "hunter14".to_string() + }) + ); + + request!( + @expect_error "The password is wrong" + env, + login(LoginInfo { + id: user_id, + password: "hunter13".to_owned() + }) + ); + + request!( + env, + login(LoginInfo { + id: user_id, + password: "hunter14".to_owned() + }) + ); + + let user = request!(env, user_by_id(user_id)); + + assert_eq!(&user.name, "me"); + assert_eq!(user.description.as_deref(), Some("Myself")); + + request!(env, logout()); + request!( + @expect_error "We are not logged in anymore" + env, + user_by_id(user_id) + ); +} -- cgit 1.4.1