aboutsummaryrefslogtreecommitdiffstats
path: root/src/server/driver/mod.rs
blob: 68bd18c90132cc2a5cad93b5202acf8fd3250930 (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#[cfg(feature = "oauth")]
pub mod auth;

#[cfg(feature = "oauth")]
use async_session::Session;
use async_trait::async_trait;
#[cfg(feature = "oauth")]
use axum::{
    http::HeaderMap,
    response::{IntoResponse, Redirect},
};
#[cfg(feature = "oauth")]
use oauth2::CsrfToken;
use sqlx::PgPool;

use crate::{config::DatabaseOptions, server::state::database};

#[derive(Debug, Clone)]
pub struct Services {
    database: PgPool,
}

impl Services {
    pub async fn new(database: &DatabaseOptions) -> anyhow::Result<Self> {
        let database = database::connect(database).await?;

        Ok(Self { database })
    }
}

#[async_trait]
pub trait SellershutDriver: Send + Sync + 'static {
    async fn hello(&self);

    #[cfg(feature = "oauth")]
    async fn create_auth_session(
        &self,
        csrf_token: &CsrfToken,
        auth_url: &url::Url,
    ) -> anyhow::Result<(HeaderMap, Redirect)>;
}

#[async_trait]
impl SellershutDriver for Services {
    async fn hello(&self) {
        todo!()
    }

    #[cfg(feature = "oauth")]
    async fn create_auth_session(
        &self,
        csrf_token: &CsrfToken,
        auth_url: &url::Url,
    ) -> anyhow::Result<(HeaderMap, Redirect)> {
        use anyhow::Context;
        use async_session::SessionStore;
        use axum::{
            http::{HeaderMap, header::SET_COOKIE},
            response::Redirect,
        };

        use crate::server::driver::auth::{COOKIE_NAME, CSRF_TOKEN};

        let mut session = Session::new();
        session.insert(CSRF_TOKEN, csrf_token)?;

        let res = self
            .store_session(session)
            .await?
            .context("missing csrf token")?;

        let cookie = format!("{COOKIE_NAME}={res}; SameSite=Lax; HttpOnly; Secure; Path=/");
        let mut headers = HeaderMap::new();
        headers.insert(
            SET_COOKIE,
            cookie.parse().context("failed to parse cookie")?,
        );

        Ok((headers, Redirect::to(auth_url.as_str())))
    }
}