Load user account data from server

This commit is contained in:
Jeremy Wall 2023-01-04 18:42:02 -05:00
parent f7cf7bd468
commit d9618aac35
3 changed files with 55 additions and 7 deletions

View File

@ -333,6 +333,15 @@ async fn api_save_inventory(
}
}
async fn api_user_account(session: storage::UserIdFromSession) -> api::AccountResponse {
use storage::{UserId, UserIdFromSession::FoundUserId};
if let FoundUserId(UserId(user_id)) = session {
api::AccountResponse::from(api::UserData { user_id })
} else {
api::Response::Unauthorized
}
}
fn mk_v1_routes() -> Router {
Router::new()
.route("/recipes", get(api_recipes).post(api_save_recipes))
@ -349,10 +358,21 @@ fn mk_v1_routes() -> Router {
}
fn mk_v2_routes() -> Router {
Router::new().route(
"/inventory",
get(api_inventory_v2).post(api_save_inventory_v2),
)
Router::new()
.route("/recipes", get(api_recipes).post(api_save_recipes))
// recipe entry api path route
.route("/recipe/:recipe_id", get(api_recipe_entry))
// mealplan api path routes
.route("/plan", get(api_plan).post(api_save_plan))
.route("/plan/:date", get(api_plan_since))
.route(
"/inventory",
get(api_inventory_v2).post(api_save_inventory_v2),
)
.route("/categories", get(api_categories).post(api_save_categories))
// All the routes above require a UserId.
.route("/auth", get(auth::handler).post(auth::handler))
.route("/account", get(api_user_account))
}
#[instrument(fields(recipe_dir=?recipe_dir_path), skip_all)]

View File

@ -377,6 +377,27 @@ impl HttpStore {
return None;
}
#[instrument]
pub async fn get_user_data(&self) -> Option<UserData> {
debug!("Retrieving User Account data");
let mut path = self.v2_path();
path.push_str("/account");
let result = reqwasm::http::Request::get(&path).send().await;
if let Ok(resp) = &result {
if resp.status() == 200 {
let user_data = resp
.json::<AccountResponse>()
.await
.expect("Unparseable authentication response")
.as_success();
return user_data;
}
error!(status = resp.status(), "Login was unsuccessful")
} else {
error!(err=?result.unwrap_err(), "Failed to send auth request");
}
return None;
}
//#[instrument]
pub async fn get_categories(&self) -> Result<Option<String>, Error> {
let mut path = self.v1_path();

View File

@ -185,9 +185,16 @@ impl StateMachine {
.map(|(k, v)| (k.clone(), *v as i32))
.collect::<Vec<(String, i32)>>();
local_store.save_plan(&plan);
info!("Checking for user_data in local storage");
let user_data = local_store.get_user_data();
state.auth = user_data;
info!("Checking for user account data");
if let Some(user_data) = store.get_user_data().await {
debug!("Successfully got account data from server");
local_store.set_user_data(Some(&user_data));
state.auth = Some(user_data);
} else {
debug!("Using account data from local store");
let user_data = local_store.get_user_data();
state.auth = user_data;
}
info!("Synchronizing categories");
match store.get_categories().await {
Ok(Some(categories_content)) => {