From 8c689db1c8fa06ddb9119e626e7b1149f3493905 Mon Sep 17 00:00:00 2001 From: Joris Date: Sat, 12 Aug 2023 20:05:09 +0200 Subject: Sign cookie with secret key --- src/utils/cookie.rs | 35 +++++++++++++++++++++++++++++++++++ src/utils/mod.rs | 1 + 2 files changed, 36 insertions(+) create mode 100644 src/utils/cookie.rs (limited to 'src/utils') diff --git a/src/utils/cookie.rs b/src/utils/cookie.rs new file mode 100644 index 0000000..c716936 --- /dev/null +++ b/src/utils/cookie.rs @@ -0,0 +1,35 @@ +use uuid::Uuid; + +use crate::crypto::signed; +use crate::model::config::Config; + +pub fn login(config: &Config, token: Uuid) -> Result { + let signed_token = signed::sign(&config.auth_secret, &token.to_string())?; + Ok(cookie(config, &signed_token, 24 * 60 * 60)) +} + +pub fn logout(config: &Config) -> String { + cookie(config, "", 0) +} + +pub fn extract_token(config: &Config, cookie: &str) -> Result { + let mut xs = cookie.split('='); + xs.next(); + let signed_cookie = xs.next().ok_or("Error extracting cookie")?; + signed::verify(&config.auth_secret, signed_cookie) +} + +fn cookie(config: &Config, token: &str, max_age_seconds: i32) -> String { + let mut xs = vec![ + format!("TOKEN={token}"), + "SameSite=Strict".to_string(), + "HttpOnly".to_string(), + format!("Max-Age={}", max_age_seconds), + ]; + + if config.secure_cookies { + xs.push("Secure".to_string()) + } + + xs.join(";") +} diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 481c63a..f362d7b 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -1 +1,2 @@ +pub mod cookie; pub mod text; -- cgit v1.2.3