Skip to content

Commit

Permalink
feat: allow origin for http server;
Browse files Browse the repository at this point in the history
  • Loading branch information
Mr.Panda committed Jan 6, 2023
1 parent 798e0c7 commit f42dbbe
Show file tree
Hide file tree
Showing 7 changed files with 73 additions and 8 deletions.
1 change: 1 addition & 0 deletions turn-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ clap = { version = "4", features = ["derive", "env"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
reqwest = { version = "0.11.13", features = ["json"] }
tower-http = { version = "0.3.5", features = ["cors"] }
async-trait = "0.1.52"
serde_json = "1.0.61"
simple_logger = "4"
Expand Down
25 changes: 23 additions & 2 deletions turn-server/src/api/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,12 @@ pub struct AddrParams {
addr: SocketAddr,
}

#[derive(Debug, Deserialize)]
pub struct Qiter {
skip: Option<usize>,
limit: Option<usize>,
}

/// controller
///
/// It is possible to control the turn server and obtain server internal
Expand Down Expand Up @@ -240,8 +246,17 @@ impl Controller {
/// ```
pub async fn get_users(
State(this): State<&Self>,
Query(pars): Query<Qiter>,
) -> Json<HashMap<String, Vec<SocketAddr>>> {
Json(this.router.get_users().await.into_iter().collect())
let skip = pars.skip.unwrap_or(0);
let limit = pars.limit.unwrap_or(20);
Json(
this.router
.get_users(skip, limit)
.await
.into_iter()
.collect(),
)
}

/// Get node information
Expand Down Expand Up @@ -289,10 +304,16 @@ impl Controller {
/// let addr = "127.0.0.1:8080".parse().unwrap();
/// // let remove_node_js = ctr.remove_user(addr).await;
/// ```
#[rustfmt::skip]
pub async fn remove_node(
State(this): State<&Self>,
Query(pars): Query<AddrParams>,
) -> Json<bool> {
Json(this.router.remove(&Arc::new(pars.addr)).await.is_some())
Json(
this.router
.remove(&Arc::new(pars.addr))
.await
.is_some()
)
}
}
16 changes: 15 additions & 1 deletion turn-server/src/api/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
pub mod controller;
pub mod hooks;

use tower_http::cors::CorsLayer;
use controller::Controller;
use crate::config::Config;
use http::Request;
use http::{
HeaderValue,
Request,
};

use axum::{
routing::delete,
routing::get,
Expand Down Expand Up @@ -105,6 +110,15 @@ pub async fn start(cfg: &Config, ctr: &Controller) -> anyhow::Result<()> {
.route("/users", get(Controller::get_users))
.route("/node", get(Controller::get_node))
.route("/node", delete(Controller::remove_node))
.layer(
CorsLayer::new().allow_origin(
cfg.controller
.allow_origin
.as_str()
.parse::<HeaderValue>()
.unwrap(),
),
)
.layer(LogLayer)
.with_state(ctr);

Expand Down
13 changes: 13 additions & 0 deletions turn-server/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,18 +84,30 @@ pub struct Controller {
/// environment.
#[serde(default = "Controller::listen")]
pub listen: SocketAddr,

/// Set the value of the Access-Control-Allow-Origin header.
///
/// Access-Control-Allow-Origin is a header request that states whether the
/// response is shared with requesting code.
#[serde(default = "Controller::allow_origin")]
pub allow_origin: String,
}

impl Controller {
fn listen() -> SocketAddr {
"127.0.0.1:3000".parse().unwrap()
}

fn allow_origin() -> String {
"*".to_string()
}
}

impl Default for Controller {
fn default() -> Self {
Self {
listen: Self::listen(),
allow_origin: Self::allow_origin(),
}
}
}
Expand Down Expand Up @@ -194,6 +206,7 @@ pub struct Config {
/// verification. Note: this is a high-priority authentication method, turn
/// The server will try to use static authentication first, and then use
/// external control service authentication.
#[serde(default)]
pub auth: HashMap<String, String>,
}

Expand Down
10 changes: 7 additions & 3 deletions turn/src/router/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,14 @@ impl Router {
/// ```ignore
/// let router = Router::new(/* ... */);
///
/// assert!(router.get_users().len() == 0);
/// assert!(router.get_users(0, 10).len() == 0);
/// ```
pub async fn get_users(&self) -> Vec<(String, Vec<SocketAddr>)> {
self.nodes.get_users().await
pub async fn get_users(
&self,
skip: usize,
limit: usize,
) -> Vec<(String, Vec<SocketAddr>)> {
self.nodes.get_users(skip, limit).await
}

/// get node.
Expand Down
10 changes: 8 additions & 2 deletions turn/src/router/nodes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,13 +150,19 @@ impl Nodes {
///
/// ```ignore
/// let node = Nodes::new();
/// assert_eq!(!node.get_users().len(), 0);
/// assert_eq!(!node.get_users(0, 10).len(), 0);
/// ```
pub async fn get_users(&self) -> Vec<(String, Vec<SocketAddr>)> {
pub async fn get_users(
&self,
skip: usize,
limit: usize,
) -> Vec<(String, Vec<SocketAddr>)> {
self.addrs
.read()
.await
.iter()
.skip(skip)
.take(limit)
.map(|(k, v)| (k.clone(), v.iter().map(|v| *v.clone()).collect()))
.collect()
}
Expand Down
6 changes: 6 additions & 0 deletions turn_server.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ threads = 12
# environment.
listen = "127.0.0.1:3000"

# Set the value of the Access-Control-Allow-Origin header.
#
# Access-Control-Allow-Origin is a header request that states whether the
# response is shared with requesting code.
allow_origin = "localhost"

[hooks]
# hooks bind uri
#
Expand Down

0 comments on commit f42dbbe

Please sign in to comment.