systemprompt_traits/
auth.rs1use async_trait::async_trait;
2use std::sync::Arc;
3use systemprompt_identifiers::UserId;
4
5pub type AuthResult<T> = Result<T, AuthProviderError>;
6
7#[derive(Debug, thiserror::Error)]
8#[non_exhaustive]
9pub enum AuthProviderError {
10 #[error("Invalid credentials")]
11 InvalidCredentials,
12
13 #[error("User not found")]
14 UserNotFound,
15
16 #[error("Invalid token")]
17 InvalidToken,
18
19 #[error("Token expired")]
20 TokenExpired,
21
22 #[error("Insufficient permissions")]
23 InsufficientPermissions,
24
25 #[error("Internal error: {0}")]
26 Internal(String),
27}
28
29impl From<anyhow::Error> for AuthProviderError {
30 fn from(err: anyhow::Error) -> Self {
31 Self::Internal(err.to_string())
32 }
33}
34
35#[derive(Debug, Clone)]
36pub struct AuthUser {
37 pub id: UserId,
38 pub name: String,
39 pub email: String,
40 pub roles: Vec<String>,
41 pub is_active: bool,
42}
43
44#[async_trait]
45pub trait UserProvider: Send + Sync {
46 async fn find_by_id(&self, id: &UserId) -> AuthResult<Option<AuthUser>>;
47 async fn find_by_email(&self, email: &str) -> AuthResult<Option<AuthUser>>;
48 async fn find_by_name(&self, name: &str) -> AuthResult<Option<AuthUser>>;
49 async fn create_user(
50 &self,
51 name: &str,
52 email: &str,
53 full_name: Option<&str>,
54 ) -> AuthResult<AuthUser>;
55 async fn create_anonymous(&self, fingerprint: &str) -> AuthResult<AuthUser>;
56 async fn assign_roles(&self, user_id: &UserId, roles: &[String]) -> AuthResult<()>;
57}
58
59#[async_trait]
60pub trait RoleProvider: Send + Sync {
61 async fn get_roles(&self, user_id: &UserId) -> AuthResult<Vec<String>>;
62 async fn assign_role(&self, user_id: &UserId, role: &str) -> AuthResult<()>;
63 async fn revoke_role(&self, user_id: &UserId, role: &str) -> AuthResult<()>;
64 async fn list_users_by_role(&self, role: &str) -> AuthResult<Vec<AuthUser>>;
65}
66
67pub type DynUserProvider = Arc<dyn UserProvider>;
68pub type DynRoleProvider = Arc<dyn RoleProvider>;