authr_http 0.1.0

Actix Web integration for authr.
Documentation
use actix_web::{
    HttpRequest,
    cookie::{Cookie, SameSite, time::Duration},
};
use chrono::Utc;

use authr_common::types::Session;

// -------------------- Constants --------------------

/// Name of the cookie used to store the user's session token.
pub const SESSION_COOKIE_NAME: &str = "authr_session";

// -------------------- Extraction --------------------

/// Extracts the raw session token from the request's session cookie.
///
/// Returns `None` if the cookie is not present.
pub fn extract_session_token(request: &HttpRequest) -> Option<String> {
    request
        .cookie(SESSION_COOKIE_NAME)
        .map(|cookie| cookie.value().to_owned())
}

// -------------------- Construction --------------------

/// Builds a cookie containing the session's raw token.
///
/// The cookie is HTTP-only, secure, restricted to the root path, and uses
/// `SameSite=Lax`. Its maximum age is derived from the session's expiration
/// time.
pub fn build_session_cookie(session: &Session) -> Cookie<'static> {
    let max_age = (session.expires_at - Utc::now()).num_seconds();

    let mut cookie = Cookie::build(SESSION_COOKIE_NAME, session.token.clone())
        .http_only(true)
        .secure(true)
        .same_site(SameSite::Lax)
        .path("/")
        .finish();

    if max_age > 0 {
        cookie.set_max_age(Duration::seconds(max_age));
    } else {
        cookie.make_removal();
    }

    cookie
}

/// Builds a removal cookie for the user's session.
///
/// The cookie uses the same name, path, and security attributes as the
/// session cookie so that the browser removes the correct cookie.
pub fn build_removal_session_cookie() -> Cookie<'static> {
    let mut cookie = Cookie::build(SESSION_COOKIE_NAME, "")
        .http_only(true)
        .secure(true)
        .same_site(SameSite::Lax)
        .path("/")
        .finish();

    cookie.make_removal();

    cookie
}