Skip to content

Commit

Permalink
refactor app, make ready for authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
glendc committed Oct 22, 2023
1 parent 6f8ab2f commit eaf6039
Show file tree
Hide file tree
Showing 14 changed files with 110 additions and 79 deletions.
28 changes: 4 additions & 24 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,38 +1,18 @@
use std::path::PathBuf;

use axum::Router;
use shuttle_secrets::SecretStore;
use tower::ServiceBuilder;
use tower_http::{
compression::CompressionLayer, normalize_path::NormalizePathLayer, services::ServeDir,
trace::TraceLayer,
};

mod auth;
mod router;
mod services;

#[shuttle_runtime::main]
async fn axum(#[shuttle_secrets::Secrets] secret_store: SecretStore) -> shuttle_axum::ShuttleAxum {
// TODO:
// - add `authorizer to state` ???
// - make it compile again...

let _auth = auth::Auth::new(
let auth = services::Auth::new(
secret_store.get("AUTH_PRIVATE_KEY").unwrap(),
secret_store.get("AUTHORIZED_EMAILS").unwrap(),
secret_store.get("SENDGRID_API_KEY").unwrap(),
);

let router = Router::new()
.nest_service("/static", ServeDir::new(PathBuf::from("static")))
.nest("/", router::new())
.fallback(router::not_found::any)
.layer(
ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
.layer(CompressionLayer::new())
.layer(NormalizePathLayer::trim_trailing_slash()),
);
let state = router::State { auth };
let router = router::new(state);

Ok(router.into())
}
15 changes: 9 additions & 6 deletions src/router/login.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use askama_axum::{IntoResponse, Response};
use axum::{extract::Query, response::Redirect, Form};
use axum::{extract::Query, http::StatusCode, response::Redirect, Form};
use serde::Deserialize;

#[derive(Deserialize)]
Expand All @@ -24,11 +24,14 @@ pub struct PostParams {

pub async fn post(Form(params): Form<PostParams>) -> Response {
if params.email.is_empty() {
return super::shared::ErrorTemplate {
title: "email is required".to_string(),
message: "Please enter your email address.".to_string(),
}
.into_response();
return (
StatusCode::BAD_REQUEST,
super::shared::ErrorTemplate {
title: "email is required".to_string(),
message: "Please enter your email address.".to_string(),
},
)
.into_response();
}
super::shared::InfoTemplate {
title: format!("email sent to {}", params.email),
Expand Down
21 changes: 21 additions & 0 deletions src/router/memory.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use axum::http::HeaderMap;

pub async fn get_robots_txt() -> &'static str {
r"User-agent: *
Allow: /
Sitemap: https://bckt.xyz/sitemap.xml
"
}

pub async fn get_sitemap_xml() -> impl axum::response::IntoResponse {
let body = r#"<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://bckt.xyz/</loc>
</url>
</urlset>"#;

let mut headers = HeaderMap::new();
headers.insert("content-type", "application/xml".parse().unwrap());

(headers, body)
}
54 changes: 29 additions & 25 deletions src/router/mod.rs
Original file line number Diff line number Diff line change
@@ -1,46 +1,50 @@
use std::{path::PathBuf, sync::Arc};

use axum::{
http::HeaderMap,
response::IntoResponse,
routing::{get, post},
Router,
};
use tower::ServiceBuilder;
use tower_http::{
compression::CompressionLayer, normalize_path::NormalizePathLayer, services::ServeDir,
trace::TraceLayer,
};

mod index;
mod link;
mod login;
mod memory;
mod not_found;
mod redirect;
mod shared;

pub mod not_found;

pub async fn get_robots_txt() -> &'static str {
r"User-agent: *
Allow: /
Sitemap: https://bckt.xyz/sitemap.xml
"
}

pub async fn get_sitemap_xml() -> impl IntoResponse {
let body = r#"<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://bckt.xyz/</loc>
</url>
</urlset>"#;

let mut headers = HeaderMap::new();
headers.insert("content-type", "application/xml".parse().unwrap());

(headers, body)
#[derive(Debug, Clone)]
pub struct State {
pub auth: crate::services::Auth,
}

pub fn new() -> Router {
fn new_root(state: State) -> Router {
Router::new()
.route("/", get(index::get))
.route("/robots.txt", get(get_robots_txt))
.route("/sitemap.xml", get(get_sitemap_xml))
.route("/robots.txt", get(memory::get_robots_txt))
.route("/sitemap.xml", get(memory::get_sitemap_xml))
.route("/link", get(link::get))
.route("/link", post(link::post))
.route("/login", get(login::get))
.route("/login", post(login::post))
.route("/:hash", get(redirect::get))
.with_state(Arc::new(state))
}

pub fn new(state: State) -> Router {
Router::new()
.nest_service("/static", ServeDir::new(PathBuf::from("static")))
.nest("/", new_root(state))
.fallback(not_found::any)
.layer(
ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
.layer(CompressionLayer::new())
.layer(NormalizePathLayer::trim_trailing_slash()),
)
}
19 changes: 13 additions & 6 deletions src/router/not_found.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
use askama::Template;
use axum::{
body::Body,
http::{Request, StatusCode},
};

#[derive(Template)]
#[template(path = "../templates/404.html")]
pub struct GetTemplate;
use crate::router::shared::ErrorTemplate;

pub async fn any() -> GetTemplate {
GetTemplate
pub async fn any(request: Request<Body>) -> (StatusCode, ErrorTemplate) {
(
StatusCode::NOT_FOUND,
ErrorTemplate {
title: "404 — Not Found".to_string(),
message: format!("The page '{}' does not exist.", request.uri().path()),
},
)
}
2 changes: 1 addition & 1 deletion src/auth.rs → src/services/auth.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct Auth;

// TODO implement using
Expand Down
2 changes: 2 additions & 0 deletions src/services/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
mod auth;
pub use auth::Auth;
4 changes: 3 additions & 1 deletion static/css/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
--info-fg: #1D3557;
--ok-fg: #457B9D;
--bad-fg: #E63946;
--custom-error-text: #fff1f2;
--warn-fg: #E76F51;
--plain-graphical-fg: #1D3557;
--info-graphical-fg: #457B9D;
Expand Down Expand Up @@ -52,6 +53,7 @@
--info-fg: #F1FAEE;
--ok-fg: #2A9D8F;
--bad-fg: #E63946;
--custom-error-text: #fff1f2;
--warn-fg: #E76F51;
--plain-graphical-fg: #F1FAEE;
--info-graphical-fg: #A8DADC;
Expand All @@ -61,7 +63,7 @@
--plain-bg: #1D3557;
--info-bg: #457B9D;
--ok-bg: #2A9D8F;
--bad-bg: #f88690;
--bad-bg: #f7c1c5;
--warn-bg: #E76F51;
}
}
15 changes: 15 additions & 0 deletions static/js/bckt.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
function init() {
console.log('hello');

document.body.addEventListener('htmx:beforeSwap', (evt) => {
console.log('beforeSwap', evt);
if ([400, 404].includes(evt.detail.xhr.status)) {
evt.detail.shouldSwap = true;
evt.detail.isError = false;
}
});
}

document.addEventListener("DOMContentLoaded", init);

export { };
10 changes: 0 additions & 10 deletions templates/404.html

This file was deleted.

4 changes: 3 additions & 1 deletion templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@
<meta property="og:image" content="/og-image">

<script src="/static/js/htmx.min.js?v=1.9.6"></script>
<script type="module" src="/static/js/bckt.js?v=0.1.0"></script>

<link rel="stylesheet" href="/static/css/missing.min.css?v=1.1.1" />
<link rel="stylesheet" href="/static/css/style.css?t=bucket&v=0.1.0" />
<link rel="stylesheet" href="/static/css/style.css?t=bucket&v=0.1.1" />
</head>

<body>
Expand Down
7 changes: 6 additions & 1 deletion templates/content/login.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@
<div class="table rows spacious">
<p>
<label for="email">email:</label>
<input id="email" name="email" type="email" placeholder="email" style="width: 100%; margin: 0 5px 0 0;">
<input
id="email" name="email"
type="email" placeholder="email"
style="width: 100%; margin: 0 5px 0 0;"
autofocus
>
</p>
</div>
<p>
Expand Down
6 changes: 3 additions & 3 deletions templates/content/shared/error.html
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
{% extends "base.html" %}
{% block content %}
<div class="box bad" style="width: 100%; max-width: 500px;">
<strong class="block titlebar" style="color: var(--bg); text-shadow: none;">{{ title }}</strong>
<p>{{ message }}</p>
<strong class="block titlebar" style="color: var(--custom-error-text); text-shadow: none;">{{ title }}</strong>
<p style="color: var(--bg);">{{ message }}</p>
<p>
<a href="/" class="<button> big" style="margin: 10px 0 0 0; float: right;">↩ go back</a>
<a href="/" class="<button> big" style="margin: 10px 0 0 0; float: right;" autofocus>↩ go back</a>
</p>
</div>
{% endblock %}
2 changes: 1 addition & 1 deletion templates/content/shared/info.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<strong class="block titlebar">{{ title }}</strong>
<p>{{ message }}</p>
<p>
<a href="/" class="<button> good big" style="margin: 10px 0 0 0; float: right;">↩ go back</a>
<a href="/" class="<button> good big" style="margin: 10px 0 0 0; float: right;" autofocus>↩ go back</a>
</p>
</div>
{% endblock %}

0 comments on commit eaf6039

Please sign in to comment.