Skip to main content

oxinbox_backend/
auth.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3
4use tokio::sync::RwLock;
5use tracing::instrument;
6use url::Url;
7use webauthn_rs::prelude::*;
8
9use crate::ai::AiProvider;
10use crate::database::ParadeDbRepository;
11use crate::push::PushService;
12
13#[derive(Clone)]
14pub struct AuthState {
15    pub webauthn: Arc<Webauthn>,
16    pub reg_states: Arc<RwLock<HashMap<String, (PasskeyRegistration, String)>>>,
17    pub auth_states: Arc<RwLock<HashMap<String, (PasskeyAuthentication, i32)>>>,
18    pub credentials: Arc<RwLock<HashMap<i32, Vec<Passkey>>>>,
19    pub users: Arc<RwLock<HashMap<String, i32>>>,
20    pub sessions: Arc<RwLock<HashMap<String, i32>>>,
21    pub ai_provider: Option<Arc<dyn AiProvider>>,
22    pub db: Option<Arc<ParadeDbRepository>>,
23    pub push: PushService,
24}
25
26impl AuthState {
27    #[instrument(skip(ai_provider, db, push))]
28    pub fn new(
29        ai_provider: Option<Arc<dyn AiProvider>>,
30        db: Option<Arc<ParadeDbRepository>>,
31        push: PushService,
32    ) -> Self {
33        let rp_id = std::env::var("RP_ID").unwrap_or_else(|_| "localhost".into());
34        let rp_origin_str =
35            std::env::var("RP_ORIGIN").unwrap_or_else(|_| "http://localhost:3300".into());
36        let rp_origin = Url::parse(&rp_origin_str).expect("invalid RP_ORIGIN");
37
38        tracing::debug!(%rp_id, %rp_origin_str, "configuring WebAuthn");
39
40        let webauthn = WebauthnBuilder::new(&rp_id, &rp_origin)
41            .expect("failed to create webauthn builder")
42            .build()
43            .expect("failed to build webauthn");
44
45        Self {
46            webauthn: Arc::new(webauthn),
47            reg_states: Arc::new(RwLock::new(HashMap::new())),
48            auth_states: Arc::new(RwLock::new(HashMap::new())),
49            credentials: Arc::new(RwLock::new(HashMap::new())),
50            users: Arc::new(RwLock::new(HashMap::new())),
51            sessions: Arc::new(RwLock::new(HashMap::new())),
52            ai_provider,
53            db,
54            push,
55        }
56    }
57
58    pub fn next_user_id() -> i32 {
59        use std::sync::atomic::{AtomicI32, Ordering};
60        static COUNTER: AtomicI32 = AtomicI32::new(1);
61        COUNTER.fetch_add(1, Ordering::Relaxed)
62    }
63
64    pub fn generate_token() -> String {
65        use rand::Rng;
66        let mut rng = rand::thread_rng();
67        (0..64)
68            .map(|_| rng.sample(rand::distributions::Alphanumeric) as char)
69            .collect()
70    }
71}
72
73#[derive(Clone, Copy, Debug)]
74pub struct AuthUser {
75    pub user_id: i32,
76}