summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorColin Reeder <vpzomtrrfrt@gmail.com>2020-09-29 16:50:42 -0600
committerColin Reeder <vpzomtrrfrt@gmail.com>2020-09-29 16:50:42 -0600
commit8bc330669e05e63877b97499b373a57a1c0c402e (patch)
treee67981c08d116d05778667fd8e1850200a612560
parent7dfcc4fddda21b34b59ce4a04cc309966414b4ce (diff)
Add CORS headers to responses
-rw-r--r--src/main.rs50
-rw-r--r--src/routes/api/comments.rs18
-rw-r--r--src/routes/api/communities.rs32
-rw-r--r--src/routes/api/forgot_password.rs6
-rw-r--r--src/routes/api/mod.rs37
-rw-r--r--src/routes/api/posts.rs28
-rw-r--r--src/routes/api/users.rs28
7 files changed, 73 insertions, 126 deletions
diff --git a/src/main.rs b/src/main.rs
index ff95d6e..ce96c69 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -368,19 +368,32 @@ pub async fn query_stream(
db.query_raw(statement, params).await
}
+pub fn common_response_builder() -> http::response::Builder {
+ hyper::Response::builder().header(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
+}
+
pub fn empty_response() -> hyper::Response<hyper::Body> {
- let mut res = hyper::Response::new((&[][..]).into());
- *res.status_mut() = hyper::StatusCode::NO_CONTENT;
- res
+ common_response_builder()
+ .status(hyper::StatusCode::NO_CONTENT)
+ .body(Default::default())
+ .unwrap()
}
pub fn simple_response(
code: hyper::StatusCode,
text: impl Into<hyper::Body>,
) -> hyper::Response<hyper::Body> {
- let mut res = hyper::Response::new(text.into());
- *res.status_mut() = code;
- res
+ common_response_builder()
+ .status(code)
+ .body(text.into())
+ .unwrap()
+}
+
+pub fn json_response(body: &impl serde::Serialize) -> Result<hyper::Response<hyper::Body>, Error> {
+ let body = serde_json::to_vec(&body)?;
+ Ok(common_response_builder()
+ .header(hyper::header::CONTENT_TYPE, "application/json")
+ .body(body.into())?)
}
pub async fn res_to_error(
@@ -871,10 +884,29 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let routes = routes.clone();
let context = context.clone();
async move {
- let result = match routes.route(req, context) {
- Ok(fut) => fut.await,
- Err(err) => Err(Error::RoutingError(err)),
+ let result = if req.method() == hyper::Method::OPTIONS
+ && req.uri().path().starts_with("/api")
+ {
+ hyper::Response::builder()
+ .status(hyper::StatusCode::NO_CONTENT)
+ .header(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
+ .header(
+ hyper::header::ACCESS_CONTROL_ALLOW_METHODS,
+ "GET, POST, PUT, PATCH, DELETE",
+ )
+ .header(
+ hyper::header::ACCESS_CONTROL_ALLOW_HEADERS,
+ "Content-Type, Authorization",
+ )
+ .body(Default::default())
+ .map_err(Into::into)
+ } else {
+ match routes.route(req, context) {
+ Ok(fut) => fut.await,
+ Err(err) => Err(Error::RoutingError(err)),
+ }
};
+
Ok::<_, hyper::Error>(match result {
Ok(val) => val,
Err(Error::UserError(res)) => res,
diff --git a/src/routes/api/comments.rs b/src/routes/api/comments.rs
index 546289d..2f9c81b 100644
--- a/src/routes/api/comments.rs
+++ b/src/routes/api/comments.rs
@@ -125,11 +125,7 @@ async fn route_unstable_comments_get(
post,
};
- let output = serde_json::to_vec(&output)?;
-
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(output.into())?)
+ crate::json_response(&output)
}
}
}
@@ -397,11 +393,8 @@ async fn route_unstable_comments_likes_list(
"items": likes,
"next_page": next_page,
});
- let body = serde_json::to_vec(&body)?.into();
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(body)?)
+ crate::json_response(&body)
}
async fn route_unstable_comments_unlike(
@@ -579,12 +572,7 @@ async fn route_unstable_comments_replies_create(
crate::on_post_add_comment(info, ctx);
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(
- serde_json::to_vec(&serde_json::json!({ "id": reply_id, "post": {"id": post} }))?
- .into(),
- )?)
+ crate::json_response(&serde_json::json!({ "id": reply_id, "post": {"id": post} }))
}
pub fn route_comments() -> crate::RouteNode<()> {
diff --git a/src/routes/api/communities.rs b/src/routes/api/communities.rs
index 3ba4bb7..2f193d1 100644
--- a/src/routes/api/communities.rs
+++ b/src/routes/api/communities.rs
@@ -56,9 +56,7 @@ async fn route_unstable_communities_list(
})
.collect();
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(serde_json::to_vec(&output)?.into())?)
+ crate::json_response(&output)
}
async fn route_unstable_communities_create(
@@ -135,11 +133,7 @@ async fn route_unstable_communities_create(
community_id
};
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(
- serde_json::to_vec(&serde_json::json!({"community": {"id": community_id}}))?.into(),
- )?)
+ crate::json_response(&serde_json::json!({"community": {"id": community_id}}))
}
async fn route_unstable_communities_get(
@@ -209,11 +203,7 @@ async fn route_unstable_communities_get(
},
};
- let body = serde_json::to_vec(&info)?;
-
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(body.into())?)
+ crate::json_response(&info)
}
async fn route_unstable_communities_patch(
@@ -335,9 +325,7 @@ async fn route_unstable_communities_follow(
}
};
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(serde_json::to_vec(&output)?.into())?)
+ crate::json_response(&output)
}
async fn route_unstable_communities_moderators_list(
@@ -389,11 +377,7 @@ async fn route_unstable_communities_moderators_list(
})
.collect();
- let output = serde_json::to_vec(&output)?;
-
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(output.into())?)
+ crate::json_response(&output)
}
async fn route_unstable_communities_moderators_add(
@@ -654,11 +638,7 @@ async fn route_unstable_communities_posts_list(
.try_collect()
.await?;
- let body = serde_json::to_vec(&posts)?;
-
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(body.into())?)
+ crate::json_response(&posts)
}
async fn route_unstable_communities_posts_patch(
diff --git a/src/routes/api/forgot_password.rs b/src/routes/api/forgot_password.rs
index 14e1697..dba7f23 100644
--- a/src/routes/api/forgot_password.rs
+++ b/src/routes/api/forgot_password.rs
@@ -111,7 +111,7 @@ async fn route_unstable_forgot_password_keys_create(
Ok(())
});
- Ok(hyper::Response::builder()
+ Ok(crate::common_response_builder()
.header(hyper::header::CONTENT_TYPE, "application/json")
.body("{}".into())?)
}
@@ -134,7 +134,7 @@ async fn route_unstable_forgot_password_keys_get(
};
if found {
- Ok(hyper::Response::builder()
+ Ok(crate::common_response_builder()
.header(hyper::header::CONTENT_TYPE, "application/json")
.body("{}".into())?)
} else {
@@ -202,7 +202,7 @@ async fn route_unstable_forgot_password_keys_reset(
trans.commit().await?;
}
- Ok(hyper::Response::builder()
+ Ok(crate::common_response_builder()
.header(hyper::header::CONTENT_TYPE, "application/json")
.body("{}".into())?)
}
diff --git a/src/routes/api/mod.rs b/src/routes/api/mod.rs
index c86acf5..e204d8e 100644
--- a/src/routes/api/mod.rs
+++ b/src/routes/api/mod.rs
@@ -280,9 +280,9 @@ async fn route_unstable_actors_lookup(
let uri = match uri {
Some(uri) => uri,
None => {
- return Ok(hyper::Response::builder()
+ return Ok(crate::common_response_builder()
.header(hyper::header::CONTENT_TYPE, "application/json")
- .body(serde_json::to_vec(&serde_json::json!([]))?.into())?);
+ .body("[]".into())?);
}
};
@@ -297,9 +297,7 @@ async fn route_unstable_actors_lookup(
}
};
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(serde_json::to_vec(&[info])?.into())?)
+ crate::json_response(&[info])
}
async fn route_unstable_logins_create(
@@ -352,9 +350,7 @@ async fn route_unstable_logins_create(
if correct {
let token = insert_token(id, &db).await?;
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(serde_json::to_vec(&serde_json::json!({"token": token.to_string()}))?.into())?)
+ crate::json_response(&serde_json::json!({"token": token.to_string()}))
} else {
Ok(crate::simple_response(
hyper::StatusCode::FORBIDDEN,
@@ -377,16 +373,9 @@ async fn route_unstable_logins_current_get(
let is_site_admin: bool = row.get(1);
let has_notifications: bool = row.get(2);
- let body = serde_json::to_vec(
- &serde_json::json!({
- "user": {"id": user, "name": username, "is_site_admin": is_site_admin, "has_unread_notifications": has_notifications}
- }),
- )?
- .into();
-
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(body)?)
+ crate::json_response(&serde_json::json!({
+ "user": {"id": user, "name": username, "is_site_admin": is_site_admin, "has_unread_notifications": has_notifications}
+ }))
}
async fn route_unstable_logins_current_delete(
@@ -453,7 +442,7 @@ async fn route_unstable_nodeinfo_20_get(
let body = serde_json::to_vec(&body)?.into();
- Ok(hyper::Response::builder()
+ Ok(crate::common_response_builder()
.header(
hyper::header::CONTENT_TYPE,
"application/json; profile=http://nodeinfo.diaspora.software/ns/schema/2.0#",
@@ -481,9 +470,7 @@ async fn route_unstable_instance_get(
}
});
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(serde_json::to_vec(&body)?.into())?)
+ crate::json_response(&body)
}
async fn route_unstable_instance_patch(
@@ -719,11 +706,7 @@ async fn route_unstable_misc_render_markdown(
let html =
tokio::task::spawn_blocking(move || crate::render_markdown(&body.content_markdown)).await?;
- let output = serde_json::to_vec(&serde_json::json!({ "content_html": html }))?;
-
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(output.into())?)
+ crate::json_response(&serde_json::json!({ "content_html": html }))
}
async fn handle_common_posts_list(
diff --git a/src/routes/api/posts.rs b/src/routes/api/posts.rs
index 89957e2..7c7552d 100644
--- a/src/routes/api/posts.rs
+++ b/src/routes/api/posts.rs
@@ -112,11 +112,7 @@ async fn route_unstable_posts_list(
let posts = super::handle_common_posts_list(stream, &ctx.local_hostname).await?;
- let body = serde_json::to_vec(&posts)?;
-
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(body.into())?)
+ crate::json_response(&posts)
}
async fn route_unstable_posts_create(
@@ -230,11 +226,7 @@ async fn route_unstable_posts_create(
Ok(())
});
- let output = serde_json::to_vec(&serde_json::json!({ "id": id }))?;
-
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(output.into())?)
+ crate::json_response(&serde_json::json!({ "id": id }))
}
async fn route_unstable_posts_get(
@@ -358,11 +350,7 @@ async fn route_unstable_posts_get(
your_vote,
};
- let output = serde_json::to_vec(&output)?;
-
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(output.into())?)
+ crate::json_response(&output)
}
}
}
@@ -625,11 +613,7 @@ async fn route_unstable_posts_likes_list(
"items": likes,
"next_page": next_page,
});
- let body = serde_json::to_vec(&body)?.into();
-
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(body)?)
+ crate::json_response(&body)
}
async fn route_unstable_posts_unlike(
@@ -797,9 +781,7 @@ async fn route_unstable_posts_replies_create(
crate::on_post_add_comment(comment, ctx);
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(serde_json::to_vec(&serde_json::json!({ "id": reply_id }))?.into())?)
+ crate::json_response(&serde_json::json!({ "id": reply_id }))
}
pub fn route_posts() -> crate::RouteNode<()> {
diff --git a/src/routes/api/users.rs b/src/routes/api/users.rs
index 888f7c8..2b6dd1c 100644
--- a/src/routes/api/users.rs
+++ b/src/routes/api/users.rs
@@ -163,9 +163,7 @@ async fn route_unstable_users_create(
serde_json::json!({"user": {"id": user_id}})
};
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(serde_json::to_vec(&output)?.into())?)
+ crate::json_response(&output)
}
async fn route_unstable_users_patch(
@@ -264,11 +262,7 @@ async fn route_unstable_users_following_posts_list(
let posts = handle_common_posts_list(stream, &ctx.local_hostname).await?;
- let body = serde_json::to_vec(&posts)?;
-
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(body.into())?)
+ crate::json_response(&posts)
}
async fn route_unstable_users_notifications_list(
@@ -391,11 +385,7 @@ async fn route_unstable_users_notifications_list(
})
.collect();
- let body = serde_json::to_vec(&notifications)?;
-
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(body.into())?)
+ crate::json_response(&notifications)
}
async fn route_unstable_users_get(
@@ -470,11 +460,7 @@ async fn route_unstable_users_get(
your_note,
};
- let body = serde_json::to_vec(&info)?;
-
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(body.into())?)
+ crate::json_response(&info)
}
async fn route_unstable_users_your_note_put(
@@ -563,11 +549,7 @@ async fn route_unstable_users_things_list(
})
.collect();
- let body = serde_json::to_vec(&things)?;
-
- Ok(hyper::Response::builder()
- .header(hyper::header::CONTENT_TYPE, "application/json")
- .body(body.into())?)
+ crate::json_response(&things)
}
pub fn route_users() -> crate::RouteNode<()> {