Skip to main content

systemprompt_users/services/
user_provider.rs

1use async_trait::async_trait;
2use systemprompt_identifiers::UserId;
3use systemprompt_traits::{AuthProviderError, AuthResult, AuthUser, UserProvider};
4
5use crate::UserService;
6
7#[derive(Debug, Clone)]
8pub struct UserProviderImpl {
9    user_service: UserService,
10}
11
12impl UserProviderImpl {
13    pub const fn new(user_service: UserService) -> Self {
14        Self { user_service }
15    }
16}
17
18impl From<crate::User> for AuthUser {
19    fn from(user: crate::User) -> Self {
20        Self {
21            id: UserId::new(user.id.to_string()),
22            name: user.name,
23            email: user.email,
24            roles: user.roles,
25            is_active: user.status.as_deref() == Some("active"),
26        }
27    }
28}
29
30#[async_trait]
31impl UserProvider for UserProviderImpl {
32    async fn find_by_id(&self, id: &UserId) -> AuthResult<Option<AuthUser>> {
33        self.user_service
34            .find_by_id(id)
35            .await
36            .map(|opt| opt.map(AuthUser::from))
37            .map_err(|e| AuthProviderError::Internal(e.to_string()))
38    }
39
40    async fn find_by_email(&self, email: &str) -> AuthResult<Option<AuthUser>> {
41        self.user_service
42            .find_by_email(email)
43            .await
44            .map(|opt| opt.map(AuthUser::from))
45            .map_err(|e| AuthProviderError::Internal(e.to_string()))
46    }
47
48    async fn find_by_name(&self, name: &str) -> AuthResult<Option<AuthUser>> {
49        self.user_service
50            .find_by_name(name)
51            .await
52            .map(|opt| opt.map(AuthUser::from))
53            .map_err(|e| AuthProviderError::Internal(e.to_string()))
54    }
55
56    async fn create_user(
57        &self,
58        name: &str,
59        email: &str,
60        full_name: Option<&str>,
61    ) -> AuthResult<AuthUser> {
62        self.user_service
63            .create(name, email, full_name, None)
64            .await
65            .map(AuthUser::from)
66            .map_err(|e| AuthProviderError::Internal(e.to_string()))
67    }
68
69    async fn create_anonymous(&self, fingerprint: &str) -> AuthResult<AuthUser> {
70        self.user_service
71            .create_anonymous(fingerprint)
72            .await
73            .map(AuthUser::from)
74            .map_err(|e| AuthProviderError::Internal(e.to_string()))
75    }
76
77    async fn assign_roles(&self, user_id: &UserId, roles: &[String]) -> AuthResult<()> {
78        self.user_service
79            .assign_roles(user_id, roles)
80            .await
81            .map(|_| ())
82            .map_err(|e| AuthProviderError::Internal(e.to_string()))
83    }
84}