From dfbac324f56694b275a925a0c3d1cf8b9b954356 Mon Sep 17 00:00:00 2001 From: alemi Date: Mon, 27 May 2024 07:36:38 +0200 Subject: [PATCH] feat(web): try to refresh credentials login upon start --- web/src/app.rs | 32 +++++++++++++++++++++++++------- web/src/components/login.rs | 8 ++++---- 2 files changed, 29 insertions(+), 11 deletions(-) diff --git a/web/src/app.rs b/web/src/app.rs index 920262b1..b07ddc40 100644 --- a/web/src/app.rs +++ b/web/src/app.rs @@ -1,19 +1,37 @@ use leptos::*; use leptos_router::*; +use reqwest::Method; use crate::prelude::*; -use leptos_use::{storage::use_local_storage, use_cookie, use_cookie_with_options, utils::{FromToStringCodec, JsonCodec}, UseCookieOptions}; +use leptos_use::{storage::use_local_storage, use_cookie, utils::{FromToStringCodec, JsonCodec}}; #[component] pub fn App() -> impl IntoView { - let (token, set_token) = use_cookie_with_options::( - "token", - UseCookieOptions::default() - .max_age(1000 * 60 * 60 * 6) - ); - let (config, set_config, _) = use_local_storage::("config"); + let (token, set_token) = use_cookie::("token"); let (userid, set_userid) = use_cookie::("user_id"); + let (config, set_config, _) = use_local_storage::("config"); + + spawn_local(async move { + match reqwest::Client::new() + .request(Method::PATCH, format!("{URL_BASE}/auth")) + .json(&serde_json::json!({"token": token.get().unwrap_or_default()})) + .send() + .await + { + Err(e) => tracing::error!("could not refresh token: {e}"), + Ok(res) => match res.error_for_status() { + Err(e) => tracing::error!("server rejected refresh: {e}"), + Ok(doc) => match doc.json::().await { + Err(e) => tracing::error!("failed parsing auth response: {e}"), + Ok(auth) => { + set_token.set(Some(auth.token)); + set_userid.set(Some(auth.user)); + }, + } + } + } + }); let auth = Auth { token, userid }; provide_context(auth); diff --git a/web/src/components/login.rs b/web/src/components/login.rs index 88a84aed..4d17cdee 100644 --- a/web/src/components/login.rs +++ b/web/src/components/login.rs @@ -91,8 +91,8 @@ struct LoginForm { #[derive(Debug, Clone, serde::Deserialize)] -struct AuthResponse { - token: String, - user: String, - expires: chrono::DateTime, +pub struct AuthResponse { + pub token: String, + pub user: String, + pub expires: chrono::DateTime, }