kit_rs/auth/provider.rs
1//! User provider trait for retrieving authenticated users from storage
2//!
3//! The application must implement this trait and register it with the container
4//! to enable `Auth::user()`.
5
6use async_trait::async_trait;
7use std::sync::Arc;
8
9use super::authenticatable::Authenticatable;
10use crate::error::FrameworkError;
11
12/// Trait for retrieving authenticated users from storage
13///
14/// The application must implement this trait and register it with the container
15/// to enable `Auth::user()`.
16///
17/// # Example
18///
19/// ```rust,ignore
20/// use kit::auth::{UserProvider, Authenticatable};
21/// use kit::FrameworkError;
22/// use async_trait::async_trait;
23/// use std::sync::Arc;
24///
25/// pub struct DatabaseUserProvider;
26///
27/// #[async_trait]
28/// impl UserProvider for DatabaseUserProvider {
29/// async fn retrieve_by_id(&self, id: i64) -> Result<Option<Arc<dyn Authenticatable>>, FrameworkError> {
30/// let user = User::query()
31/// .filter(Column::Id.eq(id as i32))
32/// .first()
33/// .await?;
34/// Ok(user.map(|u| Arc::new(u) as Arc<dyn Authenticatable>))
35/// }
36/// }
37/// ```
38#[async_trait]
39pub trait UserProvider: Send + Sync + 'static {
40 /// Retrieve a user by their unique identifier
41 async fn retrieve_by_id(
42 &self,
43 id: i64,
44 ) -> Result<Option<Arc<dyn Authenticatable>>, FrameworkError>;
45
46 /// Retrieve a user by credentials (for custom authentication flows)
47 ///
48 /// Default implementation returns None (not supported).
49 /// Override this if you need to authenticate by credentials other than ID.
50 async fn retrieve_by_credentials(
51 &self,
52 _credentials: &serde_json::Value,
53 ) -> Result<Option<Arc<dyn Authenticatable>>, FrameworkError> {
54 Ok(None)
55 }
56
57 /// Validate credentials against a user
58 ///
59 /// Default implementation returns false (not supported).
60 /// Override this if you need password validation.
61 async fn validate_credentials(
62 &self,
63 _user: &dyn Authenticatable,
64 _credentials: &serde_json::Value,
65 ) -> Result<bool, FrameworkError> {
66 Ok(false)
67 }
68}