Init with webapp template

This commit is contained in:
Quentin Boyer 2023-05-19 11:23:44 +02:00
commit 37331cd24d
13 changed files with 2709 additions and 0 deletions

4
.envrc Normal file
View file

@ -0,0 +1,4 @@
if ! has nix_direnv_version || ! nix_direnv_version 2.1.1; then
source_url "https://raw.githubusercontent.com/nix-community/nix-direnv/2.1.1/direnvrc" "sha256-b6qJ4r34rbE23yWjMqbmu3ia2z4b2wIlZUksBke/ol0="
fi
use flake

3
.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
/target
/.direnv
/app/dist

2222
Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

22
Cargo.toml Normal file
View file

@ -0,0 +1,22 @@
[package]
name = "regalade"
version = "0.1.0"
authors = ["traxys <quentin@familleboyer.net>"]
edition = "2021"
[workspace]
members = [".", "api", "app"]
[dependencies]
anyhow = "1.0.71"
axum = "0.6.18"
base64 = "0.21.0"
config = "0.13.3"
jwt-simple = "0.11.5"
serde = { version = "1.0.163", features = ["derive"] }
tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread"] }
tracing = "0.1.37"
tracing-subscriber = "0.3.17"
api = { path = "./api" }
thiserror = "1.0.40"
tower-http = { version = "0.4.0", features = ["cors", "fs"] }

9
api/Cargo.toml Normal file
View file

@ -0,0 +1,9 @@
[package]
name = "api"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
serde = { version = "1.0.163", features = ["derive"] }

12
api/src/lib.rs Normal file
View file

@ -0,0 +1,12 @@
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct LoginRequest {
pub username: String,
pub password: String,
}
#[derive(Serialize, Deserialize)]
pub struct LoginResponse {
pub token: String,
}

13
app/Cargo.toml Normal file
View file

@ -0,0 +1,13 @@
[package]
name = "app"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
api = { version = "0.1.0", path = "../api" }
console_log = { version = "1.0.0", features = ["color"] }
log = "0.4.17"
yew = { version = "0.20.0", features = ["csr"] }
yew-router = "0.17.0"

8
app/index.html Normal file
View file

@ -0,0 +1,8 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body></body>
</html>

40
app/src/main.rs Normal file
View file

@ -0,0 +1,40 @@
use log::Level;
use yew::prelude::*;
use yew_router::prelude::*;
#[derive(Routable, Debug, Clone, Copy, PartialEq, Eq)]
enum Route {
#[at("/")]
Index,
#[at("/404")]
#[not_found]
NotFound,
}
#[function_component]
fn App() -> Html {
html! {
<BrowserRouter>
<main>
<Switch<Route> render={switch} />
</main>
</BrowserRouter>
}
}
fn switch(route: Route) -> Html {
match route {
Route::Index => html! {
"Index"
},
Route::NotFound => html! {
"Page not found"
},
}
}
fn main() {
console_log::init_with_level(Level::Debug).unwrap();
yew::Renderer::<App>::new().render();
}

163
flake.lock generated Normal file
View file

@ -0,0 +1,163 @@
{
"nodes": {
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1681202837,
"narHash": "sha256-H+Rh19JDwRtpVPAWp64F+rlEtxUWBAQW28eAi3SRSzg=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "cfacdce06f30d2b68473a46042957675eebb3401",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"flake-utils_2": {
"inputs": {
"systems": "systems_2"
},
"locked": {
"lastModified": 1681202837,
"narHash": "sha256-H+Rh19JDwRtpVPAWp64F+rlEtxUWBAQW28eAi3SRSzg=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "cfacdce06f30d2b68473a46042957675eebb3401",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"naersk": {
"inputs": {
"nixpkgs": "nixpkgs"
},
"locked": {
"lastModified": 1679567394,
"narHash": "sha256-ZvLuzPeARDLiQUt6zSZFGOs+HZmE+3g4QURc8mkBsfM=",
"owner": "nix-community",
"repo": "naersk",
"rev": "88cd22380154a2c36799fe8098888f0f59861a15",
"type": "github"
},
"original": {
"owner": "nix-community",
"repo": "naersk",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1684393889,
"narHash": "sha256-X4EP3TdpskELgOKGfm7UcLLGheqxYJZuNEEc0HkmrO0=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "9f7d9a55cc9960c029b006444e64e8dfa54a578e",
"type": "github"
},
"original": {
"id": "nixpkgs",
"type": "indirect"
}
},
"nixpkgs_2": {
"locked": {
"lastModified": 1684393889,
"narHash": "sha256-X4EP3TdpskELgOKGfm7UcLLGheqxYJZuNEEc0HkmrO0=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "9f7d9a55cc9960c029b006444e64e8dfa54a578e",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs_3": {
"locked": {
"lastModified": 1681358109,
"narHash": "sha256-eKyxW4OohHQx9Urxi7TQlFBTDWII+F+x2hklDOQPB50=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "96ba1c52e54e74c3197f4d43026b3f3d92e83ff9",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"naersk": "naersk",
"nixpkgs": "nixpkgs_2",
"rust-overlay": "rust-overlay"
}
},
"rust-overlay": {
"inputs": {
"flake-utils": "flake-utils_2",
"nixpkgs": "nixpkgs_3"
},
"locked": {
"lastModified": 1684376381,
"narHash": "sha256-XVFTXADfvBXKwo4boqfg80awUbT+JgQvlQ8uZ+Xgo1s=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "7c9a265c2eaa5783bc18593b1aec39a85653c076",
"type": "github"
},
"original": {
"owner": "oxalica",
"repo": "rust-overlay",
"type": "github"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
},
"systems_2": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",
"version": 7
}

36
flake.nix Normal file
View file

@ -0,0 +1,36 @@
{
description = "A basic flake with a shell";
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
inputs.flake-utils.url = "github:numtide/flake-utils";
inputs.naersk.url = "github:nix-community/naersk";
inputs.rust-overlay.url = "github:oxalica/rust-overlay";
outputs = {
self,
nixpkgs,
flake-utils,
naersk,
rust-overlay,
}:
flake-utils.lib.eachDefaultSystem (system: let
pkgs = import nixpkgs {
inherit system;
overlays = [(import rust-overlay)];
};
rust = pkgs.rust-bin.stable.latest.default.override {
targets = ["wasm32-unknown-unknown"];
};
naersk' = pkgs.callPackage naersk {
cargo = rust;
rustc = rust;
};
in {
devShell = pkgs.mkShell {
nativeBuildInputs = [rust pkgs.trunk pkgs.httpie];
RUST_PATH = "${rust}";
RUST_DOC_PATH = "${rust}/share/doc/rust/html/std/index.html";
};
defaultPackage = naersk'.buildPackage ./.;
});
}

124
src/main.rs Normal file
View file

@ -0,0 +1,124 @@
use std::{net::SocketAddr, path::PathBuf, sync::Arc};
use axum::Router;
use base64::{engine::general_purpose, Engine};
use config::{Config, ConfigError};
use jwt_simple::prelude::HS256Key;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use tower_http::services::ServeDir;
mod routes;
#[derive(Clone)]
pub(crate) struct Base64(pub(crate) HS256Key);
impl std::fmt::Debug for Base64 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
r#"b64"{}""#,
&general_purpose::STANDARD_NO_PAD.encode(self.0.to_bytes())
)
}
}
impl Serialize for Base64 {
fn serialize<S>(&self, ser: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
ser.serialize_str(&general_purpose::STANDARD_NO_PAD.encode(self.0.to_bytes()))
}
}
impl<'de> Deserialize<'de> for Base64 {
fn deserialize<D>(de: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
use serde::de::Visitor;
struct DecodingVisitor;
impl<'de> Visitor<'de> for DecodingVisitor {
type Value = Base64;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("must be a base 64 string")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
general_purpose::STANDARD_NO_PAD
.decode(v)
.map_err(E::custom)
.map(|b| HS256Key::from_bytes(&b))
.map(Base64)
}
}
de.deserialize_str(DecodingVisitor)
}
}
#[derive(Deserialize, Debug)]
struct Settings {
jwt_secret: Base64,
host: String,
port: u16,
api_allowed: Option<String>,
serve_app: Option<PathBuf>,
}
impl Settings {
pub fn new() -> Result<Self, ConfigError> {
let cfg = Config::builder()
.add_source(config::Environment::with_prefix("REGALADE"))
.set_default("host", "127.0.0.1")?
.set_default("port", "8085")?
.set_default("api_allowed", None::<String>)?
.set_default("serve_app", None::<String>)?
.build()?;
cfg.try_deserialize()
}
}
struct AppState {
jwt_secret: Base64,
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.with_test_writer()
.init();
let config = Settings::new()?;
tracing::info!("Settings: {config:?}");
let addr: SocketAddr = format!("{}:{}", config.host, config.port).parse()?;
let state = Arc::new(AppState {
jwt_secret: config.jwt_secret,
});
let router = Router::new()
.nest(
"/api",
routes::router(config.api_allowed.map(|s| s.parse()).transpose()?),
)
.with_state(state);
let router = match config.serve_app {
None => router,
Some(path) => router.fallback_service(ServeDir::new(path)),
};
Ok(axum::Server::bind(&addr)
.serve(router.into_make_service())
.await?)
}

53
src/routes/mod.rs Normal file
View file

@ -0,0 +1,53 @@
use std::sync::Arc;
use api::{LoginRequest, LoginResponse};
use axum::{
extract::State,
http::{header::CONTENT_TYPE, HeaderValue, Method, StatusCode},
response::IntoResponse,
routing::post,
Json, Router,
};
use tower_http::cors::{self, AllowOrigin, CorsLayer};
#[derive(thiserror::Error, Debug)]
enum RouteError {
#[error("This account does not exist")]
UnknownAccount,
}
impl IntoResponse for RouteError {
fn into_response(self) -> axum::response::Response {
match self {
RouteError::UnknownAccount => {
(StatusCode::NOT_FOUND, "Account not found").into_response()
}
}
}
}
type JsonResult<T, E = RouteError> = Result<Json<T>, E>;
type AppState = Arc<crate::AppState>;
async fn login(
State(_state): State<AppState>,
Json(_req): Json<LoginRequest>,
) -> JsonResult<LoginResponse> {
Err(RouteError::UnknownAccount)
}
pub(crate) fn router(api_allowed: Option<HeaderValue>) -> Router<AppState> {
let origin: AllowOrigin = match api_allowed {
Some(n) => n.into(),
None => cors::Any.into(),
};
let cors_base = CorsLayer::new()
.allow_headers([CONTENT_TYPE])
.allow_origin(origin);
let mk_service = |m: Vec<Method>| cors_base.clone().allow_methods(m);
Router::new().route("/login", post(login).layer(mk_service(vec![Method::POST])))
}