When not logged in redirection to login page

Every page is locked behind a jwt, when it is not supplied neither other
pages not api calls will work
This commit is contained in:
2026-05-01 16:18:15 +02:00
parent b672fe9768
commit e54be14526
8 changed files with 221 additions and 68 deletions

58
frontend/src/auth.rs Normal file
View File

@@ -0,0 +1,58 @@
use gloo_net::http::Request;
use wasm_bindgen_futures::spawn_local;
use yew::prelude::*;
use yew_router::prelude::*;
#[derive(Clone, Debug, PartialEq)]
pub struct AuthState {
pub is_authenticated: bool,
}
#[derive(Properties, PartialEq)]
pub struct ProtectedRouteProps {
pub children: Children,
}
#[component(ProtectedRoute)]
pub fn protected_route(props: &ProtectedRouteProps) -> Html {
let is_authenticated = use_state(|| None::<bool>);
{
let is_authenticated = is_authenticated.clone();
use_effect_with((), move |_| {
let is_authenticated = is_authenticated.clone();
spawn_local(async move {
match Request::get("/api/users/current")
.credentials(web_sys::RequestCredentials::Include)
.send()
.await
{
Ok(resp) => {
let status = resp.status();
web_sys::console::log_1(&format!("Auth check: status {}", status).into());
if status == 200 {
is_authenticated.set(Some(true));
} else {
is_authenticated.set(Some(false));
}
}
Err(err) => {
web_sys::console::log_1(&format!("Auth check error: {:?}", err).into());
is_authenticated.set(Some(false));
}
}
});
|| ()
});
}
match *is_authenticated {
None => html! { <div>{"Loading..."}</div> },
Some(true) => props.children.clone().into(),
Some(false) => {
html! {
<Redirect<crate::Route> to={crate::Route::Login} />
}
}
}
}