li7y/src/main.rs

75 lines
2.5 KiB
Rust
Raw Normal View History

2024-06-24 22:46:04 +02:00
// SPDX-FileCopyrightText: 2024 Simon Bruder <simon@sbruder.de>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
use std::env;
2024-07-13 13:41:23 +02:00
use actix_identity::IdentityMiddleware;
use actix_session::{storage::CookieSessionStore, SessionMiddleware};
use actix_web::middleware::ErrorHandlers;
use actix_web::{cookie::Key, http::StatusCode, web, App, HttpServer};
use base64::prelude::{Engine as _, BASE64_STANDARD};
use log::{debug, info, warn};
2024-06-24 22:46:04 +02:00
#[actix_web::main]
async fn main() -> std::io::Result<()> {
2024-07-13 11:33:46 +02:00
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
2024-06-24 22:46:04 +02:00
2024-07-13 13:41:23 +02:00
// generate a secret key with head -c 64 /dev/urandom | base64 -w0
let secret_key = match env::var("SECRET_KEY") {
Ok(encoded) => Key::from(
&BASE64_STANDARD
.decode(encoded)
.expect("failed to decode base64 in SECRET_KEY"),
),
Err(_) => {
warn!("SECRET_KEY was not specified, using randomly generated key");
Key::generate()
}
};
let pool: sqlx::PgPool = sqlx::Pool::<sqlx::postgres::Postgres>::connect(
&env::var("DATABASE_URL").expect("DATABASE_URL must be set"),
)
.await
.expect("failed to connect to database");
2024-06-24 22:46:04 +02:00
sqlx::migrate!()
.run(&pool)
.await
.expect("failed to run migrations");
2024-06-24 22:46:04 +02:00
let address = env::var("LISTEN_ADDRESS").unwrap_or("::1".to_string());
let port = env::var("LISTEN_PORT").map_or(8080, |s| {
s.parse::<u16>().expect("failed to parse LISTEN_PORT")
});
2024-06-25 13:30:51 +02:00
let static_root = env::var("STATIC_ROOT").unwrap_or("static".to_string());
2024-06-24 22:46:04 +02:00
2024-06-25 13:30:51 +02:00
info!("Starting on {address}:{port} with static files from {static_root}");
debug!("Serving static files from {static_root}");
2024-06-24 22:46:04 +02:00
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(pool.clone()))
2024-07-13 13:41:23 +02:00
.service(
web::scope("/api/v1")
.wrap(li7y::middleware::ForceIdentity)
.configure(li7y::api::v1::config),
)
2024-06-24 22:46:04 +02:00
.service(actix_files::Files::new("/static", &static_root))
2024-07-03 14:19:58 +02:00
.configure(li7y::frontend::config)
2024-07-13 13:41:23 +02:00
.wrap(ErrorHandlers::new().handler(
StatusCode::UNAUTHORIZED,
li7y::middleware::error_handlers::redirect_to_login,
))
.wrap(IdentityMiddleware::default())
.wrap(SessionMiddleware::new(
CookieSessionStore::default(),
secret_key.clone(),
))
2024-06-24 22:46:04 +02:00
})
.bind((address, port))?
.run()
.await
}