aboutsummaryrefslogtreecommitdiff
path: root/src/utils/cookie.rs
blob: c71693698f6162239a4525f7bdbf78d35a501efa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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(";")
}