use rocketmq_error::AuthError;
use crate::authentication::strategy::AuthenticationStrategy;
use crate::authorization::context::authentication_context::AuthenticationContext;
pub struct AuthenticationEvaluator<S>
where
S: AuthenticationStrategy,
{
authentication_strategy: S,
}
impl<S> AuthenticationEvaluator<S>
where
S: AuthenticationStrategy,
{
pub fn new(authentication_strategy: S) -> Self {
Self {
authentication_strategy,
}
}
pub fn evaluate(&self, context: &dyn AuthenticationContext) -> Result<(), AuthError> {
self.authentication_strategy.authenticate(context)
}
pub fn strategy(&self) -> &S {
&self.authentication_strategy
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::authentication::context::default_authentication_context::DefaultAuthenticationContext;
use crate::authentication::strategy::allow_all::AllowAllAuthenticationStrategy;
struct TestStrategy {
should_succeed: bool,
}
impl AuthenticationStrategy for TestStrategy {
fn authenticate(&self, _context: &dyn AuthenticationContext) -> Result<(), AuthError> {
if self.should_succeed {
Ok(())
} else {
Err(AuthError::AuthenticationFailed(
"Test authentication failed".to_string(),
))
}
}
}
#[test]
fn test_evaluator_creation() {
let strategy = AllowAllAuthenticationStrategy;
let evaluator = AuthenticationEvaluator::new(strategy);
assert!(std::ptr::eq(&evaluator.authentication_strategy, evaluator.strategy()));
}
#[test]
fn test_evaluate_success() {
let strategy = TestStrategy { should_succeed: true };
let evaluator = AuthenticationEvaluator::new(strategy);
let context = DefaultAuthenticationContext::new();
let result = evaluator.evaluate(&context);
assert!(result.is_ok());
}
#[test]
fn test_evaluate_failure() {
let strategy = TestStrategy { should_succeed: false };
let evaluator = AuthenticationEvaluator::new(strategy);
let context = DefaultAuthenticationContext::new();
let result = evaluator.evaluate(&context);
assert!(result.is_err());
if let Err(AuthError::AuthenticationFailed(msg)) = result {
assert_eq!(msg, "Test authentication failed");
} else {
panic!("Expected AuthenticationFailed error");
}
}
#[test]
fn test_evaluate_with_allow_all_strategy() {
let strategy = AllowAllAuthenticationStrategy;
let evaluator = AuthenticationEvaluator::new(strategy);
let context = DefaultAuthenticationContext::new();
let result = evaluator.evaluate(&context);
assert!(result.is_ok());
}
}