diff options
author | Joris | 2023-08-12 20:05:09 +0200 |
---|---|---|
committer | Joris | 2023-08-12 20:05:09 +0200 |
commit | 8c689db1c8fa06ddb9119e626e7b1149f3493905 (patch) | |
tree | cb4029776162387a03a7a131ceee3628ed1ba4ef /src/utils | |
parent | 459016e70dd4933a8082d27748097de81a3e53ff (diff) |
Sign cookie with secret key
Diffstat (limited to 'src/utils')
-rw-r--r-- | src/utils/cookie.rs | 35 | ||||
-rw-r--r-- | src/utils/mod.rs | 1 |
2 files changed, 36 insertions, 0 deletions
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<String, String> { + 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<String, String> { + 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; |