nom-nom-nix-gc/src/server/bin/main.rs

73 lines
2.9 KiB
Rust

use std::net::SocketAddr;
use actix_web::{App, web, HttpServer, HttpResponse};
use clap::Parser;
use mime_guess::from_path;
use nom_nom_gc::handlers;
use nom_nom_gc::models::read_config;
use nom_nom_gc::models;
use nom_nom_gc::s3::check_bucket;
use rust_embed::RustEmbed;
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct CLIArgs {
#[arg(short, long)]
bind: String,
#[arg(short, long)]
config: Option<String>
}
#[derive(RustEmbed)]
#[folder = "src/static"]
struct Static;
async fn handle_embedded_file(path: web::Path<String>) -> HttpResponse {
match Static::get(&path) {
Some(content) => HttpResponse::Ok()
.content_type(from_path(&*path).first_or_octet_stream().as_ref())
.body(content.data.into_owned()),
None => HttpResponse::NotFound().body("404 Not Found"),
}
}
#[tokio::main]
async fn main() -> std::io::Result<()> {
let args = CLIArgs::parse();
let addr: SocketAddr = args.bind.parse().unwrap_or_else(|_| panic!("Cannot bind to {}. Please provide a host and port like [::1]:8000", &args.bind));
let config_path = args.config.unwrap_or("/etc/nom-nom-gc/config.json".to_owned());
let config = read_config(&config_path)
.unwrap_or_else(|e| panic!("Cannot read config file: {}", e));
let state = models::AppState::new(config.clone()).await;
println!("Running DB migrations");
state.run_migrations().await.unwrap_or_else(|e| panic!("Db migration error: {}", e));
println!("Checking binary cache bucket");
let bucket = check_bucket(&state.s3_client, &config).await;
match bucket {
Ok(_) => println!("Connection to the bucket successful"),
Err(e) => panic!("Cannot connect to the binary cache bucket: {}", e)
}
println!("Server listening to {}", &args.bind);
HttpServer::new(
move || {
App::new()
.app_data(web::Data::new(state.clone()))
.route("/", web::get().to(handlers::landing_page))
.route("/account/register/{uuid}", web::get().to(handlers::webauthn_registration))
.route("/account/register-init", web::post().to(handlers::start_webauthn_registration))
.route("/account/register-finish", web::post().to(handlers::finish_webauthn_registration))
.route("/login", web::get().to(handlers::webauthn_login))
.route("/login/init", web::post().to(handlers::webauthn_login_init))
.route("/login/finish", web::post().to(handlers::webauthn_login_finish))
.route("/binary-cache/new", web::get().to(handlers::new_binary_cache))
.route("/binary-cache/new", web::post().to(handlers::new_binary_cache_post))
.route("/binary-cache/{id}", web::get().to(handlers::get_binary_cache))
.route("/static/{_:.*}", web::get().to(handle_embedded_file))
})
.bind(addr)
.unwrap()
.run()
.await
}