torii_core/services/
user.rs

1use crate::{
2    Error, User, UserId, repositories::UserRepository, storage::NewUser, validation::validate_email,
3};
4use std::sync::Arc;
5
6/// Service for user management operations
7pub struct UserService<R: UserRepository> {
8    repository: Arc<R>,
9}
10
11impl<R: UserRepository> UserService<R> {
12    /// Create a new UserService with the given repository
13    pub fn new(repository: Arc<R>) -> Self {
14        Self { repository }
15    }
16
17    /// Create a new user
18    pub async fn create_user(&self, email: &str, name: Option<String>) -> Result<User, Error> {
19        // Validate email format
20        validate_email(email)?;
21
22        let mut builder = NewUser::builder()
23            .id(UserId::new_random())
24            .email(email.to_string());
25
26        if let Some(name) = name {
27            builder = builder.name(name);
28        }
29
30        let new_user = builder.build()?;
31
32        self.repository.create(new_user).await
33    }
34
35    /// Get a user by ID
36    pub async fn get_user(&self, user_id: &UserId) -> Result<Option<User>, Error> {
37        self.repository.find_by_id(user_id).await
38    }
39
40    /// Get a user by email
41    pub async fn get_user_by_email(&self, email: &str) -> Result<Option<User>, Error> {
42        self.repository.find_by_email(email).await
43    }
44
45    /// Get or create a user by email
46    pub async fn get_or_create_user(&self, email: &str) -> Result<User, Error> {
47        // Validate email format
48        validate_email(email)?;
49
50        self.repository.find_or_create_by_email(email).await
51    }
52
53    /// Update a user
54    pub async fn update_user(&self, user: &User) -> Result<User, Error> {
55        self.repository.update(user).await
56    }
57
58    /// Delete a user
59    pub async fn delete_user(&self, user_id: &UserId) -> Result<(), Error> {
60        self.repository.delete(user_id).await
61    }
62
63    /// Mark a user's email as verified
64    pub async fn verify_email(&self, user_id: &UserId) -> Result<(), Error> {
65        self.repository.mark_email_verified(user_id).await
66    }
67}