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

Server-side rendered pages with progressive enhancement #604

Draft
wants to merge 17 commits into
base: master
Choose a base branch
from
Draft
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
348 changes: 323 additions & 25 deletions Cargo.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ license = "AGPL-3.0-only"

[profile.dev]
codegen-units = 16
incremental = true
7 changes: 6 additions & 1 deletion dim-web/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,20 @@ nightfall = { git = "https://github.com/Dusk-Labs/nightfall", tag = "0.3.12-rc4"
] }

axum = { version = "0.6.20", features = ["ws", "http2", "macros", "multipart"] }
axum-extra = { version = "0.9.0", features = ["cookie"] }
axum-flash = "0.7.0"
cfg-if = "1.0.0"
chrono = { version = "0.4.19", features = ["serde"] }
displaydoc = "0.2.3"
dominant_color = "0.3.0"
futures = "0.3.14"
fuzzy-matcher = "0.3.7"
hex = "0.4.3"
http = "^0.2.3"
image = "0.24.3"
once_cell = "1.8.0"
percent-encoding = "2.1.0"
rust-embed = "^5.9.0"
rust-embed = "8.1.0"
serde = { version = "^1.0.125", default-features = false, features = [
"derive",
"std",
Expand All @@ -54,3 +57,5 @@ tower = { version = "0.4.13", features = ["tokio", "util"] }
dim-extern-api = { version = "0.4.0-dev", path = "../dim-extern-api" }
tokio-stream = { version = "0.1.14", features = ["full"] }
tower-http = { version = "0.4.4", features = ["full"] }
askama = { version = "0.12.1", features = ["with-axum"] }
askama_axum = "0.3.0"
67 changes: 67 additions & 0 deletions dim-web/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use askama::Template;
use axum::response::Html;
use axum::response::IntoResponse;
use axum::response::Response;
use dim_core::errors::DimError;
use dim_core::errors::StreamingErrors;
use dim_database::DatabaseError;
use http::StatusCode;

Expand Down Expand Up @@ -54,3 +57,67 @@ impl IntoResponse for DimErrorWrapper {
(status, serde_json::to_string(&resp).unwrap()).into_response()
}
}

pub struct DimHtmlErrorWrapper(pub(crate) DimError);

impl From<DimError> for DimHtmlErrorWrapper {
fn from(value: DimError) -> Self {
Self(value)
}
}

impl From<StreamingErrors> for DimHtmlErrorWrapper {
fn from(value: StreamingErrors) -> Self {
Self(DimError::StreamingError(value))
}
}

impl From<DatabaseError> for DimHtmlErrorWrapper {
fn from(value: DatabaseError) -> Self {
Self(DimError::DatabaseError {
description: value.to_string(),
})
}
}

#[derive(Template)]
#[template(path = "error.html")]
pub struct ErrorTemplate {
message: String,
}

impl IntoResponse for DimHtmlErrorWrapper {
fn into_response(self) -> Response {
use DimError as E;

let status = match self.0 {
E::LibraryNotFound | E::NoneError | E::NotFoundError | E::ExternalSearchError(_) => {
StatusCode::NOT_FOUND
}
E::StreamingError(_)
| E::DatabaseError { .. }
| E::UnknownError
| E::IOError
| E::InternalServerError
| E::UploadFailed
| E::ScannerError(_) => StatusCode::INTERNAL_SERVER_ERROR,
E::Unauthenticated
| E::Unauthorized
| E::InvalidCredentials
| E::CookieError(_)
| E::NoToken
| E::UserNotFound => StatusCode::UNAUTHORIZED,
E::UsernameNotAvailable => StatusCode::BAD_REQUEST,
E::UnsupportedFile | E::InvalidMediaType | E::MissingFieldInBody { .. } => {
StatusCode::NOT_ACCEPTABLE
}
};

(
status,
Html(ErrorTemplate {
message: self.0.to_string(),
}.render().unwrap()).into_response()
).into_response()
}
}
58 changes: 52 additions & 6 deletions dim-web/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ pub mod tree;
pub use axum;
use axum::extract::ConnectInfo;
use axum::extract::DefaultBodyLimit;
use axum::extract::FromRef;
use axum::extract::State;
use axum::response::Response;
use axum::routing::delete;
use axum::routing::get;
use axum::routing::patch;
use axum::routing::post;
use axum::Router;
use axum_flash::Key;

use dim_core::core::EventTx;
use dim_core::stream_tracking::StreamTracking;
Expand All @@ -27,7 +29,7 @@ pub mod error;
pub use error::DimErrorWrapper;

pub mod middleware;
pub use middleware::verify_cookie_token;
pub use middleware::verify_token;

#[derive(Debug, Clone)]
pub struct AppState {
Expand All @@ -36,6 +38,13 @@ pub struct AppState {
event_tx: EventTx,
state: StateManager,
stream_tracking: StreamTracking,
flash_config: axum_flash::Config,
}

impl FromRef<AppState> for axum_flash::Config {
fn from_ref(state: &AppState) -> axum_flash::Config {
state.flash_config.clone()
}
}

fn library_routes() -> Router<AppState> {
Expand Down Expand Up @@ -297,10 +306,6 @@ fn user_routes() -> Router<AppState> {

fn static_routes() -> Router<AppState> {
Router::new()
.route(
"/",
get(routes::statik::react_routes),
)
.route(
"/*path",
get(routes::statik::react_routes),
Expand All @@ -315,6 +320,42 @@ fn static_routes() -> Router<AppState> {
)
}

fn public_html_routes() -> Router<AppState> {
Router::new()
.route(
"/login",
get(routes::html::login),
)
.route(
"/login",
post(routes::html::handle_login),
)
.route(
"/logout",
get(routes::html::handle_logout),
)
.route(
"/register",
get(routes::html::register),
)
.route(
"/register",
post(routes::html::handle_register),
)
}

fn html_routes() -> Router<AppState> {
Router::new()
.route(
"/",
get(routes::html::index),
)
.route(
"/play/:id",
get(routes::html::play),
)
}

pub async fn start_webserver(
address: SocketAddr,
event_tx: EventTx,
Expand Down Expand Up @@ -364,6 +405,9 @@ pub async fn start_webserver(
event_tx: event_tx.clone(),
state,
stream_tracking,
flash_config: axum_flash::Config::new(
Key::generate()
).use_secure_cookies(false),
};

let router = Router::new()
Expand All @@ -383,13 +427,15 @@ pub async fn start_webserver(
)
.merge(settings_routes())
.merge(stream_routes())
.merge(html_routes())
.route_layer(axum::middleware::from_fn_with_state(
app.clone(),
verify_cookie_token,
verify_token,
))
// --- End of routes authenticated by Axum middleware ---
.merge(public_auth_routes())
.merge(static_routes())
.merge(public_html_routes())
.route("/ws", get(ws_handler))
.with_state(app)
.layer(tower_http::trace::TraceLayer::new_for_http())
Expand Down
136 changes: 112 additions & 24 deletions dim-web/src/middleware.rs
Original file line number Diff line number Diff line change
@@ -1,36 +1,124 @@
use crate::AppState;
use axum::body::Body;
use axum::http::Request;
use axum::extract::State;
use axum::response::Redirect;
use axum::response::IntoResponse;
use axum_extra::extract::cookie::Cookie;
use axum_flash::Flash;
use dim_core::errors::DimError;
use dim_database::user::UserID;

use crate::DimErrorWrapper;

pub async fn verify_cookie_token<B>(
pub fn get_cookie_token_value(
request: &Request<Body>,
) -> Option<String> {
request
.headers()
.get_all("Cookie")
.iter()
.filter_map(|cookie| {
cookie
.to_str()
.ok()
.and_then(|cookie| cookie.parse::<Cookie>().ok())
})
.find_map(|cookie| {
(cookie.name() == "token").then(move || cookie.value().to_owned())
})
}

pub async fn verify_token(
State(AppState { conn, .. }): State<AppState>,
mut req: axum::http::Request<B>,
next: axum::middleware::Next<B>,
flash: Flash,
mut req: axum::http::Request<Body>,
next: axum::middleware::Next<Body>,
) -> Result<axum::response::Response, DimErrorWrapper> {
match req.headers().get(axum::http::header::AUTHORIZATION) {
Some(token) => {
let mut tx = match conn.read().begin().await {
Ok(tx) => tx,
Err(_) => {
return Err(DimErrorWrapper(DimError::DatabaseError {
description: String::from("Failed to start transaction"),
}))
let is_html_request: bool = if let Some(accept_str) = req.headers().get(axum::http::header::ACCEPT) {
accept_str.to_str().unwrap().contains("text/html")
} else {
false
};
let id: UserID;
if let Some(token) = get_cookie_token_value(&req) {
id = match dim_database::user::Login::verify_cookie(token) {
Ok(id) => id,
Err(e) => {
let error = DimError::CookieError(e);
if is_html_request {
return Ok(
(
flash.error(error.to_string()),
Redirect::to("/login").into_response()
).into_response()
);
}
};
let id = dim_database::user::Login::verify_cookie(token.to_str().unwrap().to_string())
.map_err(|e| DimError::CookieError(e))
.map_err(|e| DimErrorWrapper(e))?;

let current_user = dim_database::user::User::get_by_id(&mut tx, id)
.await
.map_err(|_| DimError::UserNotFound)
.map_err(|e| DimErrorWrapper(e))?;

req.extensions_mut().insert(current_user);
Ok(next.run(req).await)
return Err(DimErrorWrapper(error));
}
};
} else if let Some(token) = req.headers().get(axum::http::header::AUTHORIZATION) {
id = match dim_database::user::Login::verify_cookie(token.to_str().unwrap().to_string()) {
Ok(id) => id,
Err(e) => {
let error = DimError::CookieError(e);
if is_html_request {
return Ok(
(
flash.error(error.to_string()),
Redirect::to("/login").into_response()
).into_response()
);
}
return Err(DimErrorWrapper(error));
}
};
} else {
let error = DimError::NoToken;
if is_html_request {
return Ok(
(
flash.error(error.to_string()),
Redirect::to("/login").into_response()
).into_response()
);
}
None => Err(DimErrorWrapper(DimError::NoToken)),
return Err(DimErrorWrapper(error));
}

let mut tx = match conn.read().begin().await {
Ok(tx) => tx,
Err(_) => {
let error = DimError::DatabaseError {
description: String::from("Failed to start transaction"),
};
if is_html_request {
return Ok(
(
flash.error(error.to_string()),
Redirect::to("/login").into_response()
).into_response()
);
}
return Err(DimErrorWrapper(error))
}
};
let current_user = match dim_database::user::User::get_by_id(&mut tx, id).await {
Ok(current_user) => current_user,
Err(_) => {
let error = DimError::UserNotFound;
if is_html_request {
return Ok(
(
flash.error(error.to_string()),
Redirect::to("/login").into_response()
).into_response()
);
}
return Err(DimErrorWrapper(error));
}
};

req.extensions_mut().insert(current_user);
Ok(next.run(req).await)
}
Loading