Copy use lighty_auth::{Authenticator, UserProfile, UserRole, AuthResult, AuthError, AuthProvider};
use lighty_core::hosts::HTTP_CLIENT;
#[cfg(feature = "events")]
use lighty_event::EventBus;
pub struct CustomAuth {
api_url: String,
username: String,
password: String,
}
impl CustomAuth {
pub fn new(api_url: &str, username: &str, password: &str) -> Self {
Self {
api_url: api_url.to_string(),
username: username.to_string(),
password: password.to_string(),
}
}
}
impl Authenticator for CustomAuth {
#[cfg(feature = "events")]
async fn authenticate(
&mut self,
event_bus: Option<&EventBus>,
) -> AuthResult<UserProfile> {
// Emit start event
if let Some(bus) = event_bus {
use lighty_event::{Event, AuthEvent};
bus.emit(Event::Auth(AuthEvent::AuthenticationStarted {
provider: AuthProvider::Custom {
base_url: self.api_url.clone(),
},
}));
}
// Make API request
let response = HTTP_CLIENT
.post(format!("{}/api/login", self.api_url))
.json(&serde_json::json!({
"username": self.username,
"password": self.password,
}))
.send()
.await
.map_err(|e| AuthError::NetworkError(e.to_string()))?;
if !response.status().is_success() {
return Err(AuthError::InvalidCredentials);
}
let data: serde_json::Value = response.json().await
.map_err(|e| AuthError::ParseError(e.to_string()))?;
// Emit success event
if let Some(bus) = event_bus {
use lighty_event::{Event, AuthEvent};
bus.emit(Event::Auth(AuthEvent::AuthenticationSuccess {
username: self.username.clone(),
provider: AuthProvider::Custom {
base_url: self.api_url.clone(),
},
}));
}
Ok(UserProfile {
id: data["id"].as_u64(),
username: self.username.clone(),
uuid: data["uuid"].as_str().unwrap_or("").to_string(),
access_token: data["token"].as_str().map(String::from),
email: data["email"].as_str().map(String::from),
email_verified: data["email_verified"].as_bool().unwrap_or(false),
money: data["money"].as_f64(),
role: data["role"].as_object().map(|r| UserRole {
name: r["name"].as_str().unwrap_or("User").to_string(),
color: r["color"].as_str().map(String::from),
}),
banned: data["banned"].as_bool().unwrap_or(false),
})
}
#[cfg(not(feature = "events"))]
async fn authenticate(&mut self) -> AuthResult<UserProfile> {
// Same implementation without events
// ...
todo!()
}
}