feat: storing api access tokens as cookie

This commit is contained in:
antifallobst 2023-10-02 21:41:11 +02:00
parent 482e5d60a4
commit de0e2b0976
Signed by: antifallobst
GPG Key ID: 2B4F402172791BAF
2 changed files with 42 additions and 9 deletions

View File

@ -19,6 +19,6 @@ yew-router = "0.17.0"
# Web # Web
wasm-bindgen = "0.2.87" wasm-bindgen = "0.2.87"
wasm-bindgen-futures = "0.4" 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 = "0.10.0"
gloo-net = "0.4.0" gloo-net = "0.4.0"

View File

@ -3,9 +3,33 @@ mod data;
use anyhow::{Error, Result}; use anyhow::{Error, Result};
use gloo_net::http::Request; use gloo_net::http::Request;
use serde_json::json; use serde_json::json;
use web_sys::RequestMode; use wasm_bindgen::JsCast;
use web_sys::{HtmlDocument, RequestCredentials, RequestMode};
use yew::Callback; use yew::Callback;
fn get_auth_cookie() -> Option<String> {
match gloo::utils::document()
.unchecked_into::<HtmlDocument>()
.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::<HtmlDocument>()
.set_cookie(format!("nc-api-auth={token}; SameSite=Lax").as_str())
.unwrap();
}
#[derive(Clone, PartialEq)] #[derive(Clone, PartialEq)]
pub struct Session { pub struct Session {
base_url: String, base_url: String,
@ -16,7 +40,7 @@ impl Default for Session {
fn default() -> Self { fn default() -> Self {
Self { Self {
base_url: "https://api.nerdcult.net".to_owned(), 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 { pub fn new(base_url: String) -> Self {
Self { Self {
base_url, base_url,
auth_token: None, auth_token: get_auth_cookie(),
} }
} }
@ -44,14 +68,23 @@ impl Session {
}); });
let call = async move { 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?; let response = request.send().await?;
match response.status() { match response.status() {
200 => Ok(response 200 => {
.json::<data::AccountAuthenticateResponse>() let token = response
.await? .json::<data::AccountAuthenticateResponse>()
.token), .await?
.token;
set_auth_cookie(&token);
Ok(token)
}
400 => Err(Error::msg(format!("Bad request"))), 400 => Err(Error::msg(format!("Bad request"))),
401 => Err(Error::msg(format!("Wrong password!"))), 401 => Err(Error::msg(format!("Wrong password!"))),
403 => Err(Error::msg(format!("You're not allowed to do this!"))), 403 => Err(Error::msg(format!("You're not allowed to do this!"))),