aboutsummaryrefslogtreecommitdiff
path: root/src/utils
diff options
context:
space:
mode:
Diffstat (limited to 'src/utils')
-rw-r--r--src/utils/cookie.rs35
-rw-r--r--src/utils/mod.rs1
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;