summaryrefslogtreecommitdiffstats
path: root/crates/auth/src/server/csrf_token_validation.rs
blob: c9a627c0d486bdb8cd875a148aa5893fb771ba7a (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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use anyhow::{Context, anyhow};
use axum_extra::headers;
use oauth2::CsrfToken;
use time::OffsetDateTime;
use tower_sessions::{CachingSessionStore, SessionStore, session::Id};
use tower_sessions_moka_store::MokaStore;
use tower_sessions_sqlx_store::PostgresStore;

use crate::{
    error::AppError,
    server::{COOKIE_NAME, CSRF_TOKEN, routes::authorised::AuthRequest},
    state::AppHandle,
};

pub struct Session {
    id: String,
    expires_at: OffsetDateTime,
    user_id: String,
}

pub async fn csrf_token_validation_workflow(
    auth_request: &AuthRequest,
    store: &CachingSessionStore<MokaStore, PostgresStore>,
    oauth_session_id: Id,
) -> Result<(), AppError> {
    let oauth_session = store.load(&oauth_session_id).await.unwrap().unwrap();

    // Extract the CSRF token from the session
    let csrf_token_serialized = oauth_session
        .data
        .get(CSRF_TOKEN)
        .context("failed to get value from session")?;
    let csrf_token = serde_json::from_value::<CsrfToken>(csrf_token_serialized.clone())
        .context("CSRF token not found in session")?
        .to_owned();

    // Cleanup the CSRF token session
    store
        .delete(&oauth_session_id)
        .await
        .context("Failed to destroy old session")?;

    // Validate CSRF token is the same as the one in the auth request
    if *csrf_token.secret() != auth_request.state {
        return Err(anyhow!("CSRF token mismatch").into());
    }

    Ok(())
}