Restrict Proxy to Reddit Domains

This commit is contained in:
spikecodes 2021-01-02 20:50:23 -08:00
parent f49bff9853
commit 5ea504e6e8
14 changed files with 156 additions and 61 deletions

View file

@ -1,30 +1,40 @@
use actix_web::{client::Client, web, Error, HttpResponse, Result};
use actix_web::{client::Client, error, web, Error, HttpResponse, Result};
use url::Url;
#[cfg(feature = "proxy")]
use base64::decode;
pub async fn handler(web::Path(url): web::Path<String>) -> Result<HttpResponse> {
if cfg!(feature = "proxy") {
#[cfg(feature = "proxy")]
let media: String;
pub async fn handler(web::Path(b64): web::Path<String>) -> Result<HttpResponse> {
let domains = vec![
"a.thumbs.redditmedia.com",
"b.thumbs.redditmedia.com",
"preview.redd.it",
"external-preview.redd.it",
"i.redd.it",
"v.redd.it",
];
#[cfg(not(feature = "proxy"))]
let media = url;
match decode(b64) {
Ok(bytes) => {
let media = String::from_utf8(bytes).unwrap();
#[cfg(feature = "proxy")]
match decode(url) {
Ok(bytes) => media = String::from_utf8(bytes).unwrap(),
Err(_e) => return Ok(HttpResponse::Ok().body("")),
};
match Url::parse(media.as_str()) {
Ok(url) => {
let domain = url.domain().unwrap_or_default();
let client = Client::default();
client
.get(media.replace("&amp;", "&"))
.send()
.await
.map_err(Error::from)
.map(|res| HttpResponse::build(res.status()).streaming(res))
} else {
Ok(HttpResponse::Ok().body(""))
if domains.contains(&domain) {
Client::default()
.get(media.replace("&amp;", "&"))
.send()
.await
.map_err(Error::from)
.map(|res| HttpResponse::build(res.status()).streaming(res))
} else {
Err(error::ErrorForbidden("Resource must be from Reddit"))
}
}
Err(_) => Err(error::ErrorBadRequest("Can't parse encoded base64 URL")),
}
}
Err(_) => Err(error::ErrorBadRequest("Can't decode base64 URL")),
}
}