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: 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: &str) -> AuthResult<Option<AuthUser>> {
33        let user_id = UserId::new(id.to_string());
34        self.user_service
35            .find_by_id(&user_id)
36            .await
37            .map(|opt| opt.map(AuthUser::from))
38            .map_err(|e| AuthProviderError::Internal(e.to_string()))
39    }
40
41    async fn find_by_email(&self, email: &str) -> AuthResult<Option<AuthUser>> {
42        self.user_service
43            .find_by_email(email)
44            .await
45            .map(|opt| opt.map(AuthUser::from))
46            .map_err(|e| AuthProviderError::Internal(e.to_string()))
47    }
48
49    async fn find_by_name(&self, name: &str) -> AuthResult<Option<AuthUser>> {
50        self.user_service
51            .find_by_name(name)
52            .await
53            .map(|opt| opt.map(AuthUser::from))
54            .map_err(|e| AuthProviderError::Internal(e.to_string()))
55    }
56
57    async fn create_user(
58        &self,
59        name: &str,
60        email: &str,
61        full_name: Option<&str>,
62    ) -> AuthResult<AuthUser> {
63        self.user_service
64            .create(name, email, full_name, None)
65            .await
66            .map(AuthUser::from)
67            .map_err(|e| AuthProviderError::Internal(e.to_string()))
68    }
69
70    async fn create_anonymous(&self, fingerprint: &str) -> AuthResult<AuthUser> {
71        self.user_service
72            .create_anonymous(fingerprint)
73            .await
74            .map(AuthUser::from)
75            .map_err(|e| AuthProviderError::Internal(e.to_string()))
76    }
77
78    async fn assign_roles(&self, user_id: &str, roles: &[String]) -> AuthResult<()> {
79        let id = UserId::new(user_id.to_string());
80        self.user_service
81            .assign_roles(&id, roles)
82            .await
83            .map(|_| ())
84            .map_err(|e| AuthProviderError::Internal(e.to_string()))
85    }
86}