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