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/// Emitted after a user and their sessions and accounts are deleted.
53#[derive(Clone, Debug, PartialEq, Eq)]
54pub struct UserDeleted {
55    pub user_id: Id,
56    pub email: String,
57}
58
59#[derive(Clone, Debug, PartialEq, Eq)]
60pub struct SessionCreated {
61    pub session_id: Id,
62    pub user_id: Id,
63}
64
65#[derive(Clone, Debug, PartialEq, Eq)]
66pub struct SessionRevoked {
67    pub user_id: Id,
68    /// `None` when several sessions were revoked at once.
69    pub session_id: Option<Id>,
70}
71
72#[derive(Clone, Debug, PartialEq, Eq)]
73pub struct PasswordChanged {
74    pub user_id: Id,
75}
76
77#[derive(Clone, Debug, PartialEq, Eq)]
78pub struct EmailVerified {
79    pub user_id: Id,
80}
81
82#[derive(Clone, Debug, PartialEq, Eq)]
83pub struct AccountLinked {
84    pub user_id: Id,
85    pub provider_id: String,
86}
87
88impl Event for UserCreated {}
89impl Event for UserUpdated {}
90impl Event for UserDeleted {}
91impl Event for SessionCreated {}
92impl Event for SessionRevoked {}
93impl Event for PasswordChanged {}
94impl Event for EmailVerified {}
95impl Event for AccountLinked {}