1
0
Fork 0
forked from alemi/upub

feat(web): try to refresh credentials login upon start

This commit is contained in:
əlemi 2024-05-27 07:36:38 +02:00
parent 318fa4f670
commit dfbac324f5
Signed by: alemi
GPG key ID: A4895B84D311642C
2 changed files with 29 additions and 11 deletions

View file

@ -1,19 +1,37 @@
use leptos::*; use leptos::*;
use leptos_router::*; use leptos_router::*;
use reqwest::Method;
use crate::prelude::*; 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] #[component]
pub fn App() -> impl IntoView { pub fn App() -> impl IntoView {
let (token, set_token) = use_cookie_with_options::<String, FromToStringCodec>( let (token, set_token) = use_cookie::<String, FromToStringCodec>("token");
"token",
UseCookieOptions::default()
.max_age(1000 * 60 * 60 * 6)
);
let (config, set_config, _) = use_local_storage::<crate::Config, JsonCodec>("config");
let (userid, set_userid) = use_cookie::<String, FromToStringCodec>("user_id"); let (userid, set_userid) = use_cookie::<String, FromToStringCodec>("user_id");
let (config, set_config, _) = use_local_storage::<crate::Config, JsonCodec>("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::<AuthResponse>().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 }; let auth = Auth { token, userid };
provide_context(auth); provide_context(auth);

View file

@ -91,8 +91,8 @@ struct LoginForm {
#[derive(Debug, Clone, serde::Deserialize)] #[derive(Debug, Clone, serde::Deserialize)]
struct AuthResponse { pub struct AuthResponse {
token: String, pub token: String,
user: String, pub user: String,
expires: chrono::DateTime<chrono::Utc>, pub expires: chrono::DateTime<chrono::Utc>,
} }