37 lines
952 B
Rust
37 lines
952 B
Rust
use domain::events::DomainEvent;
|
|
use domain::models::User;
|
|
use domain::{DomainResult, Email, Password};
|
|
|
|
use super::commands::RegisterCommand;
|
|
use super::deps::AuthDeps;
|
|
|
|
pub async fn execute(deps: &AuthDeps, cmd: RegisterCommand) -> DomainResult<User> {
|
|
let email = Email::new(&cmd.email)?;
|
|
let password = Password::new(&cmd.password)?;
|
|
|
|
if deps.user_query.find_by_email(email.as_ref()).await?.is_some() {
|
|
return Err(domain::DomainError::UserAlreadyExists(cmd.email));
|
|
}
|
|
|
|
let hash = deps.auth_service.hash_password(password.as_ref())?;
|
|
|
|
let mut user = User::new_local(email, hash);
|
|
if deps.user_query.count_users().await? == 0 {
|
|
user.promote_to_admin();
|
|
}
|
|
|
|
deps.user_command.save(&user).await?;
|
|
|
|
deps.event_publisher
|
|
.publish(DomainEvent::UserRegistered {
|
|
user_id: user.id(),
|
|
})
|
|
.await?;
|
|
|
|
Ok(user)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "tests/register.rs"]
|
|
mod tests;
|