Skip to main content

fastauth_core/
events.rs

1//! Events fire after an endpoint succeeds, for every caller (HTTP, server API, plugins).
2//! Server API calls made with `Api::within` defer them to a [`DeferredEvents`] queue.
3
4use std::sync::{Arc, Mutex};
5
6use crate::endpoint::BoxFuture;
7use crate::value::Id;
8
9pub(crate) type Dispatch = Box<dyn FnOnce() -> BoxFuture<'static, ()> + Send>;
10
11/// Events from server API calls, held back until the caller fires them after its own
12/// commit. Clones share one queue; dropping the last one discards the events.
13#[derive(Clone, Default)]
14pub struct DeferredEvents(Arc<Mutex<Vec<Dispatch>>>);
15
16impl std::fmt::Debug for DeferredEvents {
17    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18        f.debug_tuple("DeferredEvents")
19            .field(&self.0.lock().unwrap().len())
20            .finish()
21    }
22}
23
24impl DeferredEvents {
25    pub(crate) fn push(&self, dispatch: Dispatch) {
26        self.0.lock().unwrap().push(dispatch);
27    }
28
29    /// Runs the handlers of every queued event, in the order the calls emitted them, and
30    /// empties the queue.
31    pub async fn fire(&self) {
32        let queued = std::mem::take(&mut *self.0.lock().unwrap());
33        for dispatch in queued {
34            dispatch().await;
35        }
36    }
37}
38
39pub trait Event: Clone + Send + Sync + 'static {}
40
41#[derive(Clone, Debug, PartialEq, Eq)]
42pub struct UserCreated {
43    pub user_id: Id,
44    pub email: String,
45}
46
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub struct UserUpdated {
49    pub user_id: Id,
50}
51
52#[derive(Clone, Debug, PartialEq, Eq)]
53pub struct SessionCreated {
54    pub session_id: Id,
55    pub user_id: Id,
56}
57
58#[derive(Clone, Debug, PartialEq, Eq)]
59pub struct SessionRevoked {
60    pub user_id: Id,
61    /// `None` when several sessions were revoked at once.
62    pub session_id: Option<Id>,
63}
64
65#[derive(Clone, Debug, PartialEq, Eq)]
66pub struct PasswordChanged {
67    pub user_id: Id,
68}
69
70#[derive(Clone, Debug, PartialEq, Eq)]
71pub struct EmailVerified {
72    pub user_id: Id,
73}
74
75#[derive(Clone, Debug, PartialEq, Eq)]
76pub struct AccountLinked {
77    pub user_id: Id,
78    pub provider_id: String,
79}
80
81impl Event for UserCreated {}
82impl Event for UserUpdated {}
83impl Event for SessionCreated {}
84impl Event for SessionRevoked {}
85impl Event for PasswordChanged {}
86impl Event for EmailVerified {}
87impl Event for AccountLinked {}