2024-04-17 22:07:47 +02:00
|
|
|
use leptos::*;
|
2024-06-07 05:26:22 +02:00
|
|
|
use reqwest::Method;
|
|
|
|
use crate::{components::AuthResponse, URL_BASE};
|
2024-05-01 18:22:25 +02:00
|
|
|
|
|
|
|
#[derive(Debug, Clone, Copy)]
|
|
|
|
pub struct Auth {
|
|
|
|
pub token: Signal<Option<String>>,
|
2024-05-02 02:07:11 +02:00
|
|
|
pub userid: Signal<Option<String>>,
|
2024-04-17 23:07:56 +02:00
|
|
|
}
|
|
|
|
|
2024-06-07 05:26:22 +02:00
|
|
|
impl Auth {
|
|
|
|
pub fn token(&self) -> String {
|
2024-05-01 18:22:25 +02:00
|
|
|
self.token.get().unwrap_or_default()
|
|
|
|
}
|
2024-05-02 02:07:11 +02:00
|
|
|
|
2024-06-07 05:26:22 +02:00
|
|
|
pub fn user_id(&self) -> String {
|
2024-05-02 02:07:11 +02:00
|
|
|
self.userid.get().unwrap_or_default()
|
|
|
|
}
|
2024-05-01 18:22:25 +02:00
|
|
|
|
2024-06-07 05:26:22 +02:00
|
|
|
pub fn username(&self) -> String {
|
2024-05-02 02:07:11 +02:00
|
|
|
// TODO maybe cache this?? how often do i need it?
|
|
|
|
self.userid.get()
|
|
|
|
.unwrap_or_default()
|
|
|
|
.split('/')
|
|
|
|
.last()
|
|
|
|
.unwrap_or_default()
|
|
|
|
.to_string()
|
2024-04-17 22:07:47 +02:00
|
|
|
}
|
2024-05-01 18:22:25 +02:00
|
|
|
|
2024-06-07 05:26:22 +02:00
|
|
|
pub fn present(&self) -> bool {
|
2024-05-01 18:22:25 +02:00
|
|
|
self.token.get().map_or(false, |x| !x.is_empty())
|
|
|
|
}
|
|
|
|
|
2024-06-07 05:26:22 +02:00
|
|
|
pub fn outbox(&self) -> String {
|
2024-05-29 20:51:30 +02:00
|
|
|
format!("{URL_BASE}/actors/{}/outbox", self.username())
|
2024-04-17 22:07:47 +02:00
|
|
|
}
|
2024-06-07 05:26:22 +02:00
|
|
|
|
|
|
|
pub async fn refresh(
|
|
|
|
token: Signal<Option<String>>,
|
|
|
|
set_token: WriteSignal<Option<String>>,
|
|
|
|
set_userid: WriteSignal<Option<String>>
|
|
|
|
) -> bool {
|
|
|
|
if let Some(tok) = token.get_untracked() {
|
|
|
|
match reqwest::Client::new()
|
|
|
|
.request(Method::PATCH, format!("{URL_BASE}/auth"))
|
|
|
|
.json(&serde_json::json!({"token": tok}))
|
|
|
|
.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));
|
|
|
|
return true;
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
false
|
|
|
|
}
|
2024-04-17 22:07:47 +02:00
|
|
|
}
|