Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: Add auth config to async client #296

Merged
merged 1 commit into from
Mar 25, 2023
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
27 changes: 26 additions & 1 deletion socketio/src/asynchronous/client/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ pub struct ClientBuilder {
tls_config: Option<TlsConnector>,
opening_headers: Option<HeaderMap>,
transport_type: TransportType,
auth: Option<serde_json::Value>,
}

impl ClientBuilder {
Expand Down Expand Up @@ -73,6 +74,7 @@ impl ClientBuilder {
tls_config: None,
opening_headers: None,
transport_type: TransportType::Any,
auth: None,
}
}

Expand Down Expand Up @@ -227,6 +229,29 @@ impl ClientBuilder {
self
}

/// Sets authentification data sent in the opening request.
/// # Example
/// ```rust
/// use rust_socketio::{asynchronous::ClientBuilder};
/// use serde_json::json;
/// use futures_util::future::FutureExt;
///
/// #[tokio::main]
/// async fn main() {
/// let socket = ClientBuilder::new("http://localhost:4204/")
/// .namespace("/admin")
/// .auth(json!({ "password": "1337" }))
/// .on("error", |err, _| async move { eprintln!("Error: {:#?}", err) }.boxed())
/// .connect()
/// .await;
/// }
/// ```
pub fn auth<T: Into<serde_json::Value>>(mut self, auth: T) -> Self {
self.auth = Some(auth.into());

self
}

/// Specifies which EngineIO [`TransportType`] to use.
///
/// # Example
Expand Down Expand Up @@ -325,7 +350,7 @@ impl ClientBuilder {

let inner_socket = InnerSocket::new(engine_client)?;

let socket = Client::new(inner_socket, &self.namespace, self.on)?;
let socket = Client::new(inner_socket, &self.namespace, self.on, self.auth)?;
socket.connect().await?;

Ok(socket)
Expand Down
37 changes: 36 additions & 1 deletion socketio/src/asynchronous/client/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ pub struct Client {
outstanding_acks: Arc<RwLock<Vec<Ack>>>,
// namespace, for multiplexing messages
nsp: String,
// Data send in the opening packet (commonly used as for auth)
auth: Option<serde_json::Value>,
}

impl Client {
Expand All @@ -39,12 +41,14 @@ impl Client {
socket: InnerSocket,
namespace: T,
on: HashMap<Event, Callback>,
auth: Option<serde_json::Value>,
) -> Result<Self> {
Ok(Client {
socket,
nsp: namespace.into(),
on: Arc::new(RwLock::new(on)),
outstanding_acks: Arc::new(RwLock::new(Vec::new())),
auth,
})
}

Expand All @@ -55,7 +59,8 @@ impl Client {
self.socket.connect().await?;

// construct the opening packet
let open_packet = Packet::new(PacketId::Connect, self.nsp.clone(), None, None, 0, None);
let auth = self.auth.as_ref().map(|data| data.to_string());
let open_packet = Packet::new(PacketId::Connect, self.nsp.clone(), auth, None, 0, None);

self.socket.send(open_packet).await?;

Expand Down Expand Up @@ -588,6 +593,36 @@ mod test {
test_socketio_socket(socket, "/admin".to_owned()).await
}

#[tokio::test]
async fn socket_io_auth_builder_integration() -> Result<()> {
let url = crate::test::socket_io_auth_server();
let nsp = String::from("/admin");
let mut socket = ClientBuilder::new(url)
.namespace(nsp.clone())
.auth(json!({ "password": "123" }))
.connect_manual()
.await?;

// open packet
let _ = socket.next().await.unwrap()?;

println!("Here12");
let packet = socket.next().await.unwrap()?;
assert_eq!(
packet,
Packet::new(
PacketId::Event,
nsp,
Some("[\"auth\",\"success\"]".to_owned()),
None,
0,
None
)
);

Ok(())
}

#[tokio::test]
async fn socketio_polling_integration() -> Result<()> {
let url = crate::test::socket_io_server();
Expand Down
2 changes: 1 addition & 1 deletion socketio/src/client/raw_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ pub struct RawClient {
outstanding_acks: Arc<Mutex<Vec<Ack>>>,
// namespace, for multiplexing messages
nsp: String,
// Data sent in opening header
// Data send in the opening packet (commonly used as for auth)
auth: Option<serde_json::Value>,
}

Expand Down