(host: &Uri, auth_token: &str)
| 261 | |
| 262 | #[cfg(feature = "browser")] |
| 263 | async fn fetch_ws_token(host: &Uri, auth_token: &str) -> Result<String, WsError> { |
| 264 | use gloo_net::http::{Method, RequestBuilder}; |
| 265 | use js_sys::{Reflect, JSON}; |
| 266 | use wasm_bindgen::{JsCast, JsValue}; |
| 267 | |
| 268 | let url = format!("{host}v1/identity/websocket-token"); |
| 269 | |
| 270 | // helpers to convert gloo_net::Error or JsValue into WsError::TokenVerification |
| 271 | let gloo_to_ws_err = |e: gloo_net::Error| match e { |
| 272 | gloo_net::Error::JsError(js_err) => WsError::TokenVerification(js_err.message), |
| 273 | gloo_net::Error::SerdeError(e) => WsError::TokenVerification(e.to_string()), |
| 274 | gloo_net::Error::GlooError(msg) => WsError::TokenVerification(msg), |
| 275 | }; |
| 276 | let js_to_ws_err = |e: JsValue| { |
| 277 | if let Some(err) = e.dyn_ref::<js_sys::Error>() { |
| 278 | WsError::TokenVerification(err.message().into()) |
| 279 | } else if let Some(s) = e.as_string() { |
| 280 | WsError::TokenVerification(s) |
| 281 | } else { |
| 282 | WsError::TokenVerification(format!("{e:?}")) |
| 283 | } |
| 284 | }; |
| 285 | |
| 286 | let res = RequestBuilder::new(&url) |
| 287 | .method(Method::POST) |
| 288 | .header("Authorization", &format!("Bearer {auth_token}")) |
| 289 | .send() |
| 290 | .await |
| 291 | .map_err(gloo_to_ws_err)?; |
| 292 | |
| 293 | if !res.ok() { |
| 294 | return Err(WsError::TokenVerification(format!( |
| 295 | "HTTP error: {} {}", |
| 296 | res.status(), |
| 297 | res.status_text() |
| 298 | ))); |
| 299 | } |
| 300 | |
| 301 | let body = res.text().await.map_err(gloo_to_ws_err)?; |
| 302 | let json = JSON::parse(&body).map_err(js_to_ws_err)?; |
| 303 | let token_js = Reflect::get(&json, &JsValue::from_str("token")).map_err(js_to_ws_err)?; |
| 304 | token_js |
| 305 | .as_string() |
| 306 | .ok_or_else(|| WsError::TokenVerification("`token` parsing failed".into())) |
| 307 | } |
| 308 | |
| 309 | /// If `res` evaluates to `Err(e)`, log a warning in the form `"{}: {:?}", $cause, e`. |
| 310 | /// |
no test coverage detected
searching dependent graphs…