Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion web_frontend/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ log = "0.4.17"
wasm-logger = "0.2.0"
gloo-timers = { version = "0.4", features = ["futures"] }
serde-tuple-vec-map = "1.0.1"
web-sys = { version = "0.3.77", features = ["InputEvent", "InputEventInit", "HtmlSelectElement", "Window", "Location", "Clipboard", "Navigator", "SubmitEvent", "KeyboardEvent"]}
web-sys = { version = "0.3.77", features = ["InputEvent", "InputEventInit", "HtmlSelectElement", "Window", "Location", "Clipboard", "Navigator", "SubmitEvent", "KeyboardEvent", "DomTokenList"]}
gloo-net = "0.6"
serde_with = "3.8.1"
url = "2.5.0"
Expand Down
53 changes: 34 additions & 19 deletions web_frontend/src/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use web_sys::{HtmlInputElement, SubmitEvent};
use yew::prelude::*;
use yew::{html, Callback, Component, Context, Html};

use crate::auth::AuthStatus;
use crate::{api, auth::AuthStatus};

#[derive(Serialize)]
struct ChangePasswordPayload {
Expand All @@ -20,6 +20,7 @@ struct ApiKeyResponse {

pub enum Message {
StatusLoaded(Option<String>),
LoadApiKey,
ApiKeyLoaded(String),
UpdateCurrentPassword(String),
UpdateNewPassword(String),
Expand Down Expand Up @@ -62,17 +63,7 @@ impl Component for AccountSettings {
}
});

let link = ctx.link().clone();
spawn_local(async move {
match Request::get("/api/auth/api-key").send().await {
Ok(response) if response.ok() => {
if let Ok(payload) = response.json::<ApiKeyResponse>().await {
link.send_message(Message::ApiKeyLoaded(payload.api_key));
}
}
_ => {}
}
});
ctx.link().send_message(Message::LoadApiKey);

Self {
username: None,
Expand All @@ -84,17 +75,34 @@ impl Component for AccountSettings {
password_success: false,
password_submitting: false,
api_key_error: None,
api_key_busy: false,
api_key_busy: true,
}
}

fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Message::LoadApiKey => {
self.api_key_busy = true;
self.api_key_error = None;
let link = ctx.link().clone();
spawn_local(async move {
link.send_message(
match api::get_json::<ApiKeyResponse>("/api/auth/api-key").await {
Ok(payload) => Message::ApiKeyLoaded(payload.api_key),
Err(error) => Message::ApiKeyRotateFailed(format!(
"Could not load API key: {error}"
)),
},
);
});
true
}
Message::StatusLoaded(username) => {
self.username = username;
true
}
Message::ApiKeyLoaded(key) => {
self.api_key_busy = false;
self.api_key = Some(key);
true
}
Expand Down Expand Up @@ -233,10 +241,14 @@ impl Component for AccountSettings {
let on_rotate = link.callback(|_| Message::RotateApiKey);

let username_display = self.username.clone().unwrap_or_else(|| "—".to_string());
let api_key_display = self
.api_key
.clone()
.unwrap_or_else(|| "Loading...".to_string());
let api_key_display = self.api_key.clone().unwrap_or_else(|| {
if self.api_key_busy {
"Loading..."
} else {
"Unavailable"
}
.to_string()
});

html! {
<>
Expand Down Expand Up @@ -288,14 +300,17 @@ impl Component for AccountSettings {
/>
</div>
{ if let Some(msg) = &self.api_key_error {
html! { <div class="mt-3 p-3 rounded bg-red-50 border border-red-200 text-sm text-red-700">{msg.clone()}</div> }
html! { <div role="alert" class="mt-3 p-3 rounded bg-red-50 border border-red-200 text-sm text-red-700">{msg.clone()}</div> }
} else { html!{} } }
if self.api_key.is_none() && self.api_key_error.is_some() {
<button type="button" class="mt-3 mr-4 text-blue-600 underline" onclick={ctx.link().callback(|_| Message::LoadApiKey)}>{"Retry loading API key"}</button>
}
<button
type="button"
onclick={on_rotate}
disabled={self.api_key_busy}
class="mt-3 inline-flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 disabled:opacity-50 disabled:cursor-not-allowed">
{ if self.api_key_busy { "Rotating..." } else { "Rotate API key" } }
{ if self.api_key_busy { "Loading..." } else { "Rotate API key" } }
</button>
<p class="text-xs text-gray-400 mt-2">
{ "Rotating invalidates the previous key immediately." }
Expand Down
32 changes: 32 additions & 0 deletions web_frontend/src/api.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use gloo_net::http::{Request, RequestBuilder, Response};
use serde::{de::DeserializeOwned, Serialize};

pub async fn response_error(response: Response) -> String {
let status = response.status();
response
.json::<crate::ApiError>()
.await
.map(|error| error.error)
.unwrap_or_else(|_| format!("HTTP {status}"))
}

pub async fn get_json<T: DeserializeOwned>(url: &str) -> Result<T, String> {
let response = Request::get(url).send().await.map_err(|e| e.to_string())?;
if !response.ok() {
return Err(response_error(response).await);
}
response.json().await.map_err(|e| e.to_string())
}

pub async fn send_json<T: Serialize>(request: RequestBuilder, body: &T) -> Result<(), String> {
let response = request
.json(body)
.map_err(|e| e.to_string())?
.send()
.await
.map_err(|e| e.to_string())?;
if !response.ok() {
return Err(response_error(response).await);
}
Ok(())
}
12 changes: 11 additions & 1 deletion web_frontend/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ struct SetupPayload {
#[derive(Debug, Clone, PartialEq)]
enum GateState {
Loading,
Failed,
NeedsSetup,
NeedsLogin,
Authenticated(Option<String>),
Expand Down Expand Up @@ -86,7 +87,7 @@ impl Component for AuthGate {
true
}
GateMessage::StatusLoadFailed => {
self.state = GateState::NeedsLogin;
self.state = GateState::Failed;
true
}
GateMessage::SetupCompleted(username) => {
Expand All @@ -107,6 +108,15 @@ impl Component for AuthGate {
fn view(&self, ctx: &Context<Self>) -> Html {
match &self.state {
GateState::Loading => render_loading(),
GateState::Failed => render_card(
"Unable to load Privaxy",
html! {
<>
<p role="alert" class="mb-4 text-sm text-red-700">{"Could not check your sign-in status. Check the connection and try again."}</p>
<button type="button" class="text-blue-600 underline" onclick={ctx.link().callback(|_| GateMessage::LoadStatus)}>{"Retry"}</button>
</>
},
),
GateState::NeedsSetup => {
let on_setup = ctx
.link()
Expand Down
Loading
Loading