diff --git a/Cargo.toml b/Cargo.toml index 3151af9..3b21a1f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,6 @@ yew-router = "0.17.0" # Web wasm-bindgen = "0.2.87" wasm-bindgen-futures = "0.4" -web-sys = { version = "0.3.64", features = ["HtmlInputElement"] } +web-sys = { version = "0.3.64", features = ["HtmlInputElement", "HtmlDocument"] } gloo = "0.10.0" gloo-net = "0.4.0" \ No newline at end of file diff --git a/src/backend/mod.rs b/src/backend/mod.rs index 2d46af7..ec33bd7 100644 --- a/src/backend/mod.rs +++ b/src/backend/mod.rs @@ -3,9 +3,33 @@ mod data; use anyhow::{Error, Result}; use gloo_net::http::Request; use serde_json::json; -use web_sys::RequestMode; +use wasm_bindgen::JsCast; +use web_sys::{HtmlDocument, RequestCredentials, RequestMode}; use yew::Callback; +fn get_auth_cookie() -> Option { + match gloo::utils::document() + .unchecked_into::() + .cookie() + .unwrap() + .split(";") + .find(|x| x.contains("nc-api-auth")) + { + Some(cookie) => match cookie.split_once("=") { + Some(cookie) => Some(cookie.1.to_string()), + None => None, + }, + None => None, + } +} + +fn set_auth_cookie(token: &str) { + gloo::utils::document() + .unchecked_into::() + .set_cookie(format!("nc-api-auth={token}; SameSite=Lax").as_str()) + .unwrap(); +} + #[derive(Clone, PartialEq)] pub struct Session { base_url: String, @@ -16,7 +40,7 @@ impl Default for Session { fn default() -> Self { Self { base_url: "https://api.nerdcult.net".to_owned(), - auth_token: None, + auth_token: get_auth_cookie(), } } } @@ -25,7 +49,7 @@ impl Session { pub fn new(base_url: String) -> Self { Self { base_url, - auth_token: None, + auth_token: get_auth_cookie(), } } @@ -44,14 +68,23 @@ impl Session { }); let call = async move { - let request = Request::post(&url).mode(RequestMode::Cors).json(&body)?; + let request = Request::post(&url) + .mode(RequestMode::Cors) + .credentials(RequestCredentials::Omit) + .json(&body)?; let response = request.send().await?; match response.status() { - 200 => Ok(response - .json::() - .await? - .token), + 200 => { + let token = response + .json::() + .await? + .token; + + set_auth_cookie(&token); + + Ok(token) + } 400 => Err(Error::msg(format!("Bad request"))), 401 => Err(Error::msg(format!("Wrong password!"))), 403 => Err(Error::msg(format!("You're not allowed to do this!"))),