mirror of
https://github.com/infinilabs/coco-app.git
synced 2025-12-28 16:06:28 +01:00
refactor: refactoring login (#173)
* chore: add tips to login * refactor: refactoring login * chore: update release notes
This commit is contained in:
@@ -7,9 +7,9 @@ use crate::server::search::CocoSearchSource;
|
||||
use crate::server::servers::{get_server_by_id, persist_servers, persist_servers_token, save_access_token, save_server};
|
||||
use reqwest::{Client, StatusCode};
|
||||
use tauri::{AppHandle, Manager, Runtime};
|
||||
fn request_access_token_url(request_id: &str) -> String {
|
||||
fn request_access_token_url(request_id: &str, code: &str) -> String {
|
||||
// Remove the endpoint part and keep just the path for the request
|
||||
format!("/auth/request_access_token?request_id={}", request_id)
|
||||
format!("/auth/request_access_token?request_id={}&token={}", request_id, code)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -24,8 +24,8 @@ pub async fn handle_sso_callback<R: Runtime>(
|
||||
|
||||
if let Some(mut server) = server {
|
||||
// Prepare the URL for requesting the access token (endpoint is base URL, path is relative)
|
||||
save_access_token(server_id.clone(), ServerAccessToken::new(server_id.clone(), code.clone(), 60 * 15));
|
||||
let path = request_access_token_url(&request_id);
|
||||
// save_access_token(server_id.clone(), ServerAccessToken::new(server_id.clone(), code.clone(), 60 * 15));
|
||||
let path = request_access_token_url(&request_id, &code);
|
||||
|
||||
// Send the request for the access token using the util::http::HttpClient::get method
|
||||
let response = HttpClient::get(&server_id, &path)
|
||||
@@ -47,7 +47,7 @@ pub async fn handle_sso_callback<R: Runtime>(
|
||||
token.access_token.clone(),
|
||||
token.expire_at,
|
||||
);
|
||||
dbg!(&server_id, &request_id, &code, &token);
|
||||
// dbg!(&server_id, &request_id, &code, &token);
|
||||
save_access_token(server_id.clone(), access_token);
|
||||
persist_servers_token(&app_handle)?;
|
||||
|
||||
|
||||
@@ -29,8 +29,6 @@ pub fn get_connector_by_id(server_id: &str, connector_id: &str) -> Option<Connec
|
||||
}
|
||||
|
||||
pub async fn refresh_all_connectors<R: Runtime>(app_handle: &AppHandle<R>) -> Result<(), String> {
|
||||
// dbg!("Attempting to refresh all connectors");
|
||||
|
||||
let servers = get_all_servers();
|
||||
|
||||
// Collect all the tasks for fetching and refreshing connectors
|
||||
@@ -47,13 +45,11 @@ pub async fn refresh_all_connectors<R: Runtime>(app_handle: &AppHandle<R>) -> Re
|
||||
connectors_map
|
||||
}
|
||||
Err(_e) => {
|
||||
// dbg!("Failed to get connectors for server {}: {}", &server.id, e);
|
||||
HashMap::new() // Return empty map on failure
|
||||
}
|
||||
};
|
||||
|
||||
server_map.insert(server.id.clone(), connectors);
|
||||
// dbg!("end fetch connectors for server: {}", &server.id);
|
||||
}
|
||||
|
||||
// After all tasks have finished, perform a read operation on the cache
|
||||
@@ -66,8 +62,6 @@ pub async fn refresh_all_connectors<R: Runtime>(app_handle: &AppHandle<R>) -> Re
|
||||
cache.len()
|
||||
};
|
||||
|
||||
// dbg!("finished refresh connectors: {:?}", cache_size);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -101,8 +95,6 @@ pub async fn get_connectors_from_cache_or_remote(
|
||||
}
|
||||
|
||||
pub async fn fetch_connectors_by_server(id: &str) -> Result<Vec<Connector>, String> {
|
||||
// dbg!("start get_connectors_by_server: id =", &id);
|
||||
|
||||
// Use the generic GET method from HttpClient
|
||||
let resp = HttpClient::get(&id, "/connector/_search")
|
||||
.await
|
||||
@@ -111,34 +103,15 @@ pub async fn fetch_connectors_by_server(id: &str) -> Result<Vec<Connector>, Stri
|
||||
format!("Error fetching connector: {}", e)
|
||||
})?;
|
||||
|
||||
// // Log the raw response status and headers
|
||||
// dbg!("Response status: {:?}", resp.status());
|
||||
// dbg!("Response headers: {:?}", resp.headers());
|
||||
|
||||
// Ensure the response body is not empty or invalid
|
||||
if resp.status().is_success() {
|
||||
dbg!("Received successful response for id: {}", &id);
|
||||
} else {
|
||||
dbg!(
|
||||
"Failed to fetch connectors. Response status: {}",
|
||||
resp.status()
|
||||
);
|
||||
}
|
||||
|
||||
// Parse the search results directly from the response body
|
||||
let datasources: Vec<Connector> = parse_search_results(resp).await.map_err(|e| {
|
||||
// dbg!("Error parsing search results for id {}: {}", &id, &e);
|
||||
let datasource: Vec<Connector> = parse_search_results(resp).await.map_err(|e| {
|
||||
e.to_string()
|
||||
})?;
|
||||
|
||||
// Log the parsed results
|
||||
// dbg!("Parsed connectors: {:?}", &datasources);
|
||||
|
||||
// Save the connectors to the cache
|
||||
save_connectors_to_cache(&id, datasources.clone());
|
||||
save_connectors_to_cache(&id, datasource.clone());
|
||||
|
||||
// dbg!("end get_connectors_by_server: id =", &id);
|
||||
return Ok(datasources);
|
||||
Ok(datasource)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -146,8 +119,6 @@ pub async fn get_connectors_by_server<R: Runtime>(
|
||||
_app_handle: AppHandle<R>,
|
||||
id: String,
|
||||
) -> Result<Vec<Connector>, String> {
|
||||
//fetch_connectors_by_server
|
||||
|
||||
let connectors = fetch_connectors_by_server(&id).await?;
|
||||
Ok(connectors)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// use std::future::Future;
|
||||
use std::time::Duration;
|
||||
// use lazy_static::lazy_static;
|
||||
// use tauri::AppHandle;
|
||||
use crate::server::servers::{get_server_by_id, get_server_token};
|
||||
// use std::future::Future;
|
||||
use std::time::Duration;
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
use reqwest::{Client, Method, RequestBuilder};
|
||||
@@ -84,9 +84,6 @@ impl HttpClient {
|
||||
// Construct the URL
|
||||
let url = HttpClient::join_url(&s.endpoint, path);
|
||||
|
||||
// dbg!(&url);
|
||||
// dbg!(&server_id);
|
||||
|
||||
// Retrieve the token for the server (token is optional)
|
||||
let token = get_server_token(server_id).map(|t| t.access_token.clone());
|
||||
|
||||
@@ -99,6 +96,8 @@ impl HttpClient {
|
||||
);
|
||||
}
|
||||
|
||||
// dbg!(&server_id);
|
||||
// dbg!(&url);
|
||||
// dbg!(&headers);
|
||||
|
||||
Self::send_raw_request(method, &url, Some(headers), body).await
|
||||
|
||||
@@ -56,32 +56,22 @@ pub async fn connect_to_server(
|
||||
state: tauri::State<'_, WebSocketManager>,
|
||||
app_handle: tauri::AppHandle,
|
||||
) -> Result<(), String> {
|
||||
dbg!("Connecting to server",id.as_str());
|
||||
|
||||
// Disconnect any existing connection first
|
||||
disconnect(state.clone()).await?;
|
||||
|
||||
dbg!("Disconnected from previous server",id.as_str());
|
||||
|
||||
// Retrieve server details
|
||||
let server = get_server_by_id(id.as_str())
|
||||
.ok_or_else(|| format!("Server with ID {} not found", id))?;
|
||||
let mut endpoint = convert_to_websocket(server.endpoint.as_str())?;
|
||||
|
||||
dbg!("Server endpoint",endpoint.as_str());
|
||||
let endpoint = convert_to_websocket(server.endpoint.as_str())?;
|
||||
|
||||
// Retrieve the token for the server (token is optional)
|
||||
let token = get_server_token(id.as_str()).map(|t| t.access_token.clone());
|
||||
|
||||
dbg!("Server token",token.as_ref().unwrap_or(&"".to_string()).as_str());
|
||||
|
||||
// Create the WebSocket request
|
||||
let mut request = tokio_tungstenite::tungstenite::client::IntoClientRequest::into_client_request(
|
||||
&endpoint
|
||||
).map_err(|e| format!("Failed to create WebSocket request: {}", e))?;
|
||||
|
||||
dbg!("WebSocket request");
|
||||
|
||||
// Add necessary headers
|
||||
request.headers_mut().insert("Connection", "Upgrade".parse().unwrap());
|
||||
request.headers_mut().insert("Upgrade", "websocket".parse().unwrap());
|
||||
@@ -91,20 +81,15 @@ pub async fn connect_to_server(
|
||||
generate_key().parse().unwrap(),
|
||||
);
|
||||
|
||||
dbg!("WebSocket headers",request.headers().iter().map(|(k, v)| format!("{}: {}", k.as_str(), v.to_str().unwrap())).collect::<Vec<String>>().join("\n"));
|
||||
|
||||
// If a token exists, add it to the headers
|
||||
if let Some(token) = token {
|
||||
request.headers_mut().insert("X-API-TOKEN", token.parse().unwrap());
|
||||
}
|
||||
|
||||
dbg!("WebSocket headers with token",request.headers().iter().map(|(k, v)| format!("{}: {}", k.as_str(), v.to_str().unwrap())).collect::<Vec<String>>().join("\n"));
|
||||
|
||||
// Establish the WebSocket connection
|
||||
dbg!(&request);
|
||||
// dbg!(&request);
|
||||
let (mut ws_remote, _) = connect_async(request).await
|
||||
.map_err(|e| {
|
||||
dbg!("WebSocket connection error",&e);
|
||||
match e {
|
||||
Error::ConnectionClosed => "WebSocket connection was closed".to_string(),
|
||||
Error::Protocol(protocol_error) => format!("Protocol error: {}", protocol_error),
|
||||
@@ -113,19 +98,12 @@ pub async fn connect_to_server(
|
||||
}
|
||||
})?;
|
||||
|
||||
dbg!("Connected to server1234",id.as_str());
|
||||
|
||||
// Create cancellation channel
|
||||
let (cancel_tx, mut cancel_rx) = mpsc::channel(1);
|
||||
|
||||
dbg!("try to lock Connected to server",id.as_str());
|
||||
|
||||
// Store connection and cancellation sender
|
||||
*state.ws_connection.lock().await = Some(ws_remote);
|
||||
*state.cancel_tx.lock().await = Some(cancel_tx);
|
||||
|
||||
dbg!("locked Connected to server",id.as_str());
|
||||
|
||||
// Spawn listener task with cancellation
|
||||
let app_handle_clone = app_handle.clone();
|
||||
let connection_clone = state.ws_connection.clone();
|
||||
@@ -133,8 +111,6 @@ pub async fn connect_to_server(
|
||||
let mut connection = connection_clone.lock().await;
|
||||
if let Some(ws) = connection.as_mut() {
|
||||
loop {
|
||||
dbg!("try to select Connected to server",id.as_str());
|
||||
|
||||
tokio::select! {
|
||||
msg = ws.next() => {
|
||||
match msg {
|
||||
@@ -153,8 +129,6 @@ pub async fn connect_to_server(
|
||||
}
|
||||
});
|
||||
|
||||
dbg!("END Connected to server");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -138,7 +138,7 @@ fn _register_shortcut_upon_start(app: &App, shortcut: Shortcut) {
|
||||
if window.is_visible().unwrap() {
|
||||
window.hide().unwrap();
|
||||
} else {
|
||||
dbg!("showing window");
|
||||
// dbg!("showing window");
|
||||
move_window_to_active_monitor(&window);
|
||||
window.set_visible_on_all_workspaces(true).unwrap();
|
||||
window.set_always_on_top(true).unwrap();
|
||||
|
||||
Reference in New Issue
Block a user