Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,92 @@ impl<R: ApiKeyRepository> ApiKeyUseCase<R> {
self.repo.delete(id).await
}
}

#[cfg(test)]
mod tests {
use super::*;
use async_trait::async_trait;

#[derive(Clone, Default)]
struct MockApiKeyRepository;

#[async_trait]
impl ApiKeyRepository for MockApiKeyRepository {
async fn create(&self, storable: StorableApiKey) -> Result<ApiKeyModel> {
Ok(ApiKeyModel {
id: "api-key-1".to_string(),
key_prefix: storable.key_prefix,
key_hash: storable.key_hash,
permissions: storable.permissions,
created_at: "2026-01-01T00:00:00Z".to_string(),
created_by: storable.created_by.clone(),
updated_at: "2026-01-01T00:00:00Z".to_string(),
updated_by: storable.created_by,
name: storable.name,
})
}

async fn find_by_id(&self, id: &str) -> Result<ApiKeyModel> {
Ok(ApiKeyModel {
id: id.to_string(),
name: "Billing API".to_string(),
key_prefix: "avr_ab12c".to_string(),
key_hash: "hash".to_string(),
permissions: vec![ApiKeyPermission {
endpoint: "/api/v1/entities".to_string(),
method: "GET".to_string(),
}],
created_at: "2026-01-01T00:00:00Z".to_string(),
created_by: "admin".to_string(),
updated_at: "2026-01-01T00:00:00Z".to_string(),
updated_by: "admin".to_string(),
})
}

async fn find_by_hash(&self, _key_hash: &str) -> Result<Option<ApiKeyModel>> {
Ok(None)
}

async fn list(&self, _page: u64, _limit: u64) -> Result<(Vec<ApiKeyModel>, u64)> {
Ok((vec![], 0))
}

async fn update(&self, id: &str, updatable: UpdatableApiKey) -> Result<ApiKeyModel> {
Ok(ApiKeyModel {
id: id.to_string(),
name: updatable.name,
key_prefix: "avr_ab12c".to_string(),
key_hash: "updated-hash".to_string(),
permissions: updatable.permissions,
created_at: "2026-01-01T00:00:00Z".to_string(),
created_by: "admin".to_string(),
updated_at: "2026-01-02T00:00:00Z".to_string(),
updated_by: updatable.updated_by,
})
}

async fn delete(&self, _id: &str) -> Result<bool> {
Ok(true)
}
}

#[tokio::test]
async fn create_generates_plain_secret_and_hash() {
let use_case = ApiKeyUseCase::new(MockApiKeyRepository);
let permissions = vec![ApiKeyPermission {
endpoint: "/api/v1/entities".to_string(),
method: "GET".to_string(),
}];

let (model, plain_secret) = use_case
.create("Billing API".to_string(), permissions, "admin".to_string())
.await
.expect("api key creation should succeed");

assert!(plain_secret.starts_with("avr_"));
assert_eq!(model.name, "Billing API");
assert_eq!(model.created_by, "admin");
assert_eq!(model.key_prefix, plain_secret.chars().take(8).collect::<String>());
assert!(!model.key_hash.is_empty());
}
}
124 changes: 124 additions & 0 deletions crates/avored-core/src/core/application/use_cases/auth_use_case.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,127 @@ where
self.repository.update_password(user_id, &new_hash).await
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::core::{
application::dtos::{ChangePasswordCommand, LoginCommand, UpdateProfileCommand},
domain::{entities::UserModel, extensions::string_extension::StringExtension},
};
use async_trait::async_trait;
use surrealdb::types::Datetime;

#[derive(Clone, Default)]
struct MockAuthRepository {
user: UserModel,
}

impl MockAuthRepository {
fn new() -> Self {
let mut user = UserModel::default();
user.id = "user-1".to_string();
user.name = "Alice".to_string();
user.email = "alice@example.com".to_string();
user.password = "password123".to_string().get_password_hash("test-salt").unwrap();
user.created_at = Datetime::default();
user.updated_at = Datetime::default();
Self { user }
}
}

#[async_trait]
impl AuthRepository for MockAuthRepository {
async fn authenticate(&self, email: &str) -> Result<UserModel> {
if email == self.user.email {
Ok(self.user.clone())
} else {
Err(crate::error::Error::Authentication)
}
}

async fn fetch_by_id(&self, id: &str) -> Result<UserModel> {
if id == self.user.id {
Ok(self.user.clone())
} else {
Err(crate::error::Error::NotFound(id.to_string()))
}
}

async fn update_profile(&self, id: &str, name: &str, email: &str) -> Result<UserModel> {
if id != self.user.id {
return Err(crate::error::Error::NotFound(id.to_string()));
}

let mut user = self.user.clone();
user.name = name.to_string();
user.email = email.to_string();
Ok(user)
}

async fn update_password(&self, id: &str, password_hash: &str) -> Result<bool> {
if id != self.user.id {
return Err(crate::error::Error::NotFound(id.to_string()));
}
assert!(!password_hash.is_empty());
Ok(true)
}
}

#[tokio::test]
async fn auth_returns_token_for_valid_credentials() {
let repository = MockAuthRepository::new();
let use_case = AuthUseCase::new(repository);

let result = use_case
.auth(
LoginCommand {
email: "alice@example.com".to_string(),
password: "password123".to_string(),
},
"secret-key".to_string(),
)
.await
.expect("valid credentials should authenticate");

assert!(result.authenticated);
assert_eq!(result.user.email, "alice@example.com");
assert!(!result.token.trim().is_empty());
}

#[tokio::test]
async fn update_profile_rejects_empty_name() {
let use_case = AuthUseCase::new(MockAuthRepository::new());

let result = use_case
.update_profile(
"user-1",
UpdateProfileCommand {
name: " ".to_string(),
email: "updated@example.com".to_string(),
},
)
.await;

assert!(matches!(result, Err(crate::error::Error::Generic(message)) if message == "Name is required"));
}

#[tokio::test]
async fn change_password_requires_matching_confirmation() {
let use_case = AuthUseCase::new(MockAuthRepository::new());

let result = use_case
.change_password(
"user-1",
ChangePasswordCommand {
current_password: "password123".to_string(),
new_password: "new-password".to_string(),
confirm_password: "different-password".to_string(),
},
"test-salt",
)
.await;

assert!(matches!(result, Err(crate::error::Error::Generic(message)) if message == "New password and confirm password do not match"));
}
}
Loading