login refactored

This commit is contained in:
filipriec
2025-04-18 23:26:48 +02:00
parent dc6c1ce43c
commit d18f7862ab
3 changed files with 93 additions and 92 deletions

View File

@@ -230,50 +230,8 @@ impl EventHandler {
} }
UiContext::Login => { UiContext::Login => {
let login_action_message = match index { let login_action_message = match index {
0 => { // "Login" button pressed 0 => {
let username = login_state.username.clone(); login::initiate_login(login_state, app_state, self.login_result_sender.clone())
let password = login_state.password.clone();
// 1. Client-side validation
if username.trim().is_empty() {
app_state.show_dialog(
"Login Failed",
"Username/Email cannot be empty.",
vec!["OK".to_string()],
DialogPurpose::LoginFailed,
);
// Return a message, no need to modify login_state here
// as it will be cleared when result is processed
"Username cannot be empty.".to_string()
} else {
// 2. Show Loading Dialog
app_state.show_loading_dialog("Logging In", "Please wait...");
// 3. Clone sender for the task (needs sender from ui.rs)
// NOTE: We need access to login_result_sender here.
// This requires passing it into EventHandler or handle_event.
// Let's assume it's added to EventHandler state for now.
let sender = self.login_result_sender.clone(); // Assumes sender is part of EventHandler state
// 4. Spawn the login task
spawn(async move {
let login_outcome = match AuthClient::new().await {
Ok(mut auth_client) => {
match auth_client.login(username.clone(), password).await
.with_context(|| format!("Spawned login task failed for identifier: {}", username))
{
Ok(response) => login::LoginResult::Success(response),
Err(e) => login::LoginResult::Failure(format!("{}", e)),
}
}
Err(e) => login::LoginResult::ConnectionError(format!("Failed to create AuthClient: {}", e)),
};
let _ = sender.send(login_outcome).await; // Handle error?
});
// 5. Return immediately
"Login initiated.".to_string()
}
}, },
1 => login::back_to_main(login_state, app_state, buffer_state).await, 1 => login::back_to_main(login_state, app_state, buffer_state).await,
_ => "Invalid Login Option".to_string(), _ => "Invalid Login Option".to_string(),

View File

@@ -9,6 +9,9 @@ use crate::state::pages::canvas_state::CanvasState;
use crate::ui::handlers::context::DialogPurpose; use crate::ui::handlers::context::DialogPurpose;
use common::proto::multieko2::auth::LoginResponse; use common::proto::multieko2::auth::LoginResponse;
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use tokio::spawn;
use tokio::sync::mpsc;
use tracing::{info, error};
#[derive(Debug)] #[derive(Debug)]
pub enum LoginResult { pub enum LoginResult {
@@ -139,3 +142,87 @@ pub async fn back_to_main(
"Returned to main menu".to_string() "Returned to main menu".to_string()
} }
/// Validates input, shows loading, and spawns the login task.
pub fn initiate_login(
login_state: &LoginState,
app_state: &mut AppState,
sender: mpsc::Sender<LoginResult>,
) -> String {
let username = login_state.username.clone();
let password = login_state.password.clone();
// 1. Client-side validation
if username.trim().is_empty() {
app_state.show_dialog(
"Login Failed",
"Username/Email cannot be empty.",
vec!["OK".to_string()],
DialogPurpose::LoginFailed,
);
"Username cannot be empty.".to_string()
} else {
// 2. Show Loading Dialog
app_state.show_loading_dialog("Logging In", "Please wait...");
// 3. Spawn the login task
spawn(async move {
let login_outcome = match AuthClient::new().await {
Ok(mut auth_client) => {
match auth_client.login(username.clone(), password).await
.with_context(|| format!("Spawned login task failed for identifier: {}", username))
{
Ok(response) => LoginResult::Success(response),
Err(e) => LoginResult::Failure(format!("{}", e)),
}
}
Err(e) => LoginResult::ConnectionError(format!("Failed to create AuthClient: {}", e)),
};
// Send result back to the main UI thread
if let Err(e) = sender.send(login_outcome).await {
error!("Failed to send login result: {}", e);
}
});
// 4. Return immediately
"Login initiated.".to_string()
}
}
/// Handles the result received from the login task.
/// Returns true if a redraw is needed.
pub fn handle_login_result(
result: LoginResult,
app_state: &mut AppState,
auth_state: &mut AuthState,
login_state: &mut LoginState,
) -> bool {
match result {
LoginResult::Success(response) => {
auth_state.auth_token = Some(response.access_token.clone());
auth_state.user_id = Some(response.user_id.clone());
auth_state.role = Some(response.role.clone());
auth_state.decoded_username = Some(response.username.clone());
let success_message = format!(
"Login Successful!\n\nUsername: {}\nUser ID: {}\nRole: {}",
response.username, response.user_id, response.role
);
app_state.update_dialog_content(
&success_message,
vec!["Menu".to_string(), "Exit".to_string()],
DialogPurpose::LoginSuccess,
);
info!(message = %success_message, "Login successful");
}
LoginResult::Failure(err_msg) | LoginResult::ConnectionError(err_msg) => {
app_state.update_dialog_content(&err_msg, vec!["OK".to_string()], DialogPurpose::LoginFailed);
login_state.error_message = Some(err_msg.clone());
error!(error = %err_msg, "Login failed/connection error");
}
}
login_state.username.clear();
login_state.password.clear();
login_state.set_has_unsaved_changes(false);
login_state.current_cursor_pos = 0;
true // Request redraw as dialog content changed
}

View File

@@ -3,7 +3,6 @@
use crate::config::binds::config::Config; use crate::config::binds::config::Config;
use crate::config::colors::themes::Theme; use crate::config::colors::themes::Theme;
use crate::services::grpc_client::GrpcClient; use crate::services::grpc_client::GrpcClient;
// <-- Add AuthClient import
use crate::services::ui_service::UiService; use crate::services::ui_service::UiService;
use crate::modes::common::commands::CommandHandler; use crate::modes::common::commands::CommandHandler;
use crate::modes::handlers::event::{EventHandler, EventOutcome}; use crate::modes::handlers::event::{EventHandler, EventOutcome};
@@ -23,6 +22,7 @@ use crate::tui::terminal::{EventReader, TerminalCore};
use crate::ui::handlers::render::render_ui; use crate::ui::handlers::render::render_ui;
use crate::tui::functions::common::login::LoginResult; use crate::tui::functions::common::login::LoginResult;
use crate::tui::functions::common::register::RegisterResult; use crate::tui::functions::common::register::RegisterResult;
use crate::tui::functions::common::login;
use crate::tui::functions::common::register; use crate::tui::functions::common::register;
use std::time::Instant; use std::time::Instant;
use anyhow::{Context, Result}; use anyhow::{Context, Result};
@@ -192,54 +192,10 @@ pub async fn run_ui() -> Result<()> {
// --- Check for Login Results from Channel --- // --- Check for Login Results from Channel ---
match login_result_receiver.try_recv() { match login_result_receiver.try_recv() {
Ok(login_result) => { Ok(result) => {
// A result arrived from the login task! if login::handle_login_result(result, &mut app_state, &mut auth_state, &mut login_state) {
match login_result { needs_redraw = true;
LoginResult::Success(response) => {
// Update AuthState
auth_state.auth_token = Some(response.access_token.clone());
auth_state.user_id = Some(response.user_id.clone());
auth_state.role = Some(response.role.clone());
auth_state.decoded_username = Some(response.username.clone());
// Update Dialog
let success_message = format!(
"Login Successful!\n\nUsername: {}\nUser ID: {}\nRole: {}",
response.username, response.user_id, response.role
);
// Use update_dialog_content if loading dialog is shown, otherwise show_dialog
app_state.update_dialog_content( // Assuming loading dialog was shown
&success_message,
vec!["Menu".to_string(), "Exit".to_string()],
DialogPurpose::LoginSuccess,
);
info!(message = %success_message, "Login successful");
}
LoginResult::Failure(err_msg) => {
app_state.update_dialog_content( // Update loading dialog
&err_msg,
vec!["OK".to_string()],
DialogPurpose::LoginFailed,
);
login_state.error_message = Some(err_msg.clone()); // Keep error message
error!(error = %err_msg, "Login failed");
}
LoginResult::ConnectionError(err_msg) => {
app_state.update_dialog_content( // Update loading dialog
&err_msg, // Show connection error
vec!["OK".to_string()],
DialogPurpose::LoginFailed,
);
login_state.error_message = Some(err_msg.clone());
error!(error = %err_msg, "Login connection error");
}
} }
// Clear login form state regardless of outcome now that it's processed
login_state.username.clear();
login_state.password.clear();
login_state.set_has_unsaved_changes(false);
login_state.current_cursor_pos = 0;
needs_redraw = true;
} }
Err(mpsc::error::TryRecvError::Empty) => { /* No message waiting */ } Err(mpsc::error::TryRecvError::Empty) => { /* No message waiting */ }
Err(mpsc::error::TryRecvError::Disconnected) => { Err(mpsc::error::TryRecvError::Disconnected) => {