Skip to content

Commit

Permalink
Load static files as part of jinja templates
Browse files Browse the repository at this point in the history
  • Loading branch information
dormant-user committed Feb 17, 2024
1 parent 467f7c5 commit 758688f
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 23 deletions.
8 changes: 4 additions & 4 deletions src/jinja.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ use std::sync::{Arc, Mutex};
/// # Returns
///
/// String representation of the file content.
pub fn get_content(filename: &str) -> String {
fn get_content(filename: &str) -> String {
let filepath = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("src")
.join("templates")
.join(format!("{}.html", filename))
.to_string_lossy()
.to_string();
std::fs::read_to_string(&filepath).unwrap_or_else(|_| String::new())
std::fs::read_to_string(filepath).unwrap_or_else(|_| String::new())
}

/// Reads all the HTML files in templates directory and loads the content into a Jinja Environment
Expand All @@ -31,8 +31,8 @@ pub fn get_content(filename: &str) -> String {
/// - Unauthorized page template that is served as HTML response after failed authentication.
pub fn environment() -> Arc<Mutex<minijinja::Environment<'static>>> {
let mut env = minijinja::Environment::new();
for html in ["landing", "listing", "logout", "session"] {
let content = get_content(&html);
for html in ["index", "landing", "listing", "logout", "session", "unauthorized"] {
let content = get_content(html);
env.add_template_owned(html, content).unwrap();
}
let mutex = Mutex::new(env.to_owned());
Expand Down
33 changes: 18 additions & 15 deletions src/routes/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ use actix_web::cookie::Cookie;
use actix_web::cookie::time::{Duration, OffsetDateTime};
use actix_web::http::StatusCode;
use itertools::Itertools;
use minijinja::{context, Environment};
use minijinja;
use serde::Serialize;

use crate::{constant, routes, squire, jinja};
use crate::{constant, routes, squire};
use crate::routes::authenticator::AuthToken;

/// Struct for representing a JSON Response with a redirect URL.
Expand Down Expand Up @@ -70,7 +70,7 @@ pub async fn login(config: web::Data<Arc<squire::settings::Config>>, request: Ht
/// * `request` - Actix HttpRequest containing information about the incoming request.
#[get("/logout")]
pub async fn logout(config: web::Data<Arc<squire::settings::Config>>,
environment: web::Data<Arc<Mutex<Environment<'static>>>>,
environment: web::Data<Arc<Mutex<minijinja::Environment<'static>>>>,
request: HttpRequest) -> HttpResponse {
let host = request.connection_info().host().to_owned();
let template = environment.lock().unwrap();
Expand All @@ -93,7 +93,7 @@ pub async fn logout(config: web::Data<Arc<squire::settings::Config>>,
} else {
log::warn!("Session information for {} was not stored or no video was played", host);
}
rendered = logout_template.render(context!(detail => "You have been logged out successfully.")).unwrap();
rendered = logout_template.render(minijinja::context!(detail => "You have been logged out successfully.")).unwrap();

// Set to the lowest possible second since deletion is not an option
let age = Duration::new(0, 1);
Expand All @@ -103,7 +103,7 @@ pub async fn logout(config: web::Data<Arc<squire::settings::Config>>,
} else {
log::debug!("No stored session found for {}", host);
rendered = logout_template.render(
context!(detail => "You are not logged in. Please click the button below to proceed.",
minijinja::context!(detail => "You are not logged in. Please click the button below to proceed.",
show_login => true)
).unwrap();
}
Expand All @@ -119,7 +119,7 @@ pub async fn logout(config: web::Data<Arc<squire::settings::Config>>,
/// * `request` - Actix HttpRequest containing information about the incoming request.
#[get("/home")]
pub async fn home(config: web::Data<Arc<squire::settings::Config>>,
environment: web::Data<Arc<Mutex<Environment<'static>>>>,
environment: web::Data<Arc<Mutex<minijinja::Environment<'static>>>>,
request: HttpRequest) -> HttpResponse {
let auth_response = routes::authenticator::verify_token(&request, &config);
if !auth_response.ok {
Expand All @@ -142,11 +142,13 @@ pub async fn home(config: web::Data<Arc<squire::settings::Config>>,
let template = environment.lock().unwrap();
let listing = template.get_template("listing").unwrap();

return HttpResponse::build(StatusCode::OK)
HttpResponse::build(StatusCode::OK)
.content_type("text/html; charset=utf-8")
.body(listing.render(context!(
files => listing_page.files, directories => listing_page.directories)).unwrap()
);
.body(
listing.render(minijinja::context!(
files => listing_page.files, directories => listing_page.directories)
).unwrap()
)
}

/// Handles the error endpoint, rendering the appropriate HTML page based on session issues.
Expand All @@ -155,21 +157,22 @@ pub async fn home(config: web::Data<Arc<squire::settings::Config>>,
///
/// * `request` - Actix HttpRequest containing information about the incoming request.
#[get("/error")]
pub async fn error(environment: web::Data<Arc<Mutex<Environment<'static>>>>,
pub async fn error(environment: web::Data<Arc<Mutex<minijinja::Environment<'static>>>>,
request: HttpRequest) -> HttpResponse {
let template = environment.lock().unwrap();
if let Some(detail) = request.cookie("detail") {
log::info!("Error response for /error: {}", detail.value());
let template = environment.lock().unwrap();
let session = template.get_template("session").unwrap();
return HttpResponse::build(StatusCode::OK)
.content_type("text/html; charset=utf-8")
.body(session.render(context!(reason => detail.value())).unwrap());
.body(session.render(minijinja::context!(reason => detail.value())).unwrap());
}

log::info!("Sending unauthorized response for /error");
return HttpResponse::build(StatusCode::OK)
let unauthorized = template.get_template("unauthorized").unwrap();
HttpResponse::build(StatusCode::OK)
.content_type("text/html; charset=utf-8")
.body(jinja::get_content("unauthorized"));
.body(unauthorized.render(minijinja::context!()).unwrap()) // no arguments to render
}

/// Constructs an `HttpResponse` for failed `session_token` verification.
Expand Down
13 changes: 9 additions & 4 deletions src/routes/basics.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use actix_web::{HttpRequest, HttpResponse};
use std::sync::{Arc, Mutex};

use actix_web::{HttpRequest, HttpResponse, web};
use actix_web::http::StatusCode;

use crate::{squire, jinja};
use crate::squire;

/// Handles the health endpoint, returning a JSON response indicating the server is healthy.
///
Expand All @@ -26,11 +28,14 @@ pub async fn health() -> HttpResponse {
///
/// Returns an `HttpResponse` with the index page as its body.
#[get("/")]
pub async fn root(request: HttpRequest) -> HttpResponse {
pub async fn root(environment: web::Data<Arc<Mutex<minijinja::Environment<'static>>>>,
request: HttpRequest) -> HttpResponse {
// Log the connection using the squire::logger::log_connection function.
squire::logger::log_connection(&request);

let template = environment.lock().unwrap();
let index = template.get_template("index").unwrap();
HttpResponse::build(StatusCode::OK)
.content_type("text/html; charset=utf-8")
.body(jinja::get_content("index"))
.body(index.render(minijinja::context!()).unwrap()) // no arguments to render
}

0 comments on commit 758688f

Please sign in to comment.