FrostByte/server/src/main.rs

77 lines
2.3 KiB
Rust
Raw Normal View History

2023-11-28 04:20:00 +01:00
use actix_cors::Cors;
use actix_files::Files;
use actix_web::middleware;
2023-10-10 19:45:18 +02:00
use actix_web::web::Data;
2023-10-09 19:21:55 +02:00
use actix_web::{web::scope, App, HttpServer};
2023-10-10 00:03:04 +02:00
use log::info;
2023-10-09 19:21:55 +02:00
2023-10-20 06:06:55 +02:00
mod db;
2023-10-10 17:12:47 +02:00
mod jwt;
2023-10-09 19:21:55 +02:00
mod routes;
2023-10-10 00:03:04 +02:00
mod state;
mod types;
2023-11-15 16:05:07 +01:00
mod util;
2023-10-09 19:21:55 +02:00
use jwt::Authentication;
use routes::{get_comments, get_posts, login, new_comment, new_post, post_by_id, register};
2023-10-21 05:11:42 +02:00
use state::CaptchaState;
use state::ServerState;
2023-11-15 16:05:07 +01:00
use util::hex_string;
2023-10-10 00:03:04 +02:00
2023-10-09 19:21:55 +02:00
#[actix_web::main]
async fn main() -> std::io::Result<()> {
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("debug")).init();
let data = ServerState::new().await;
2023-10-21 05:11:42 +02:00
let capt_db = CaptchaState::new();
let auth = Authentication::new("secret".as_bytes());
2023-10-09 19:21:55 +02:00
2023-11-15 16:05:07 +01:00
#[cfg(debug_assertions)]
{
for _ in 0..10 {
let s = hex_string(10);
info!("Adding captcha key: {}", &s);
capt_db.capthca_db.lock().unwrap().insert(s);
}
}
2023-10-10 00:03:04 +02:00
info!("Spinning up server on http://localhost:8080");
2023-10-09 19:21:55 +02:00
HttpServer::new(move || {
2023-11-28 04:20:00 +01:00
let cors = Cors::default()
.allowed_origin("https://shitpost.se")
.allowed_methods(vec!["GET", "POST"])
.max_age(3600);
// In debug mode, allow localhost
#[cfg(debug_assertions)]
let cors = cors.allowed_origin("http://localhost:8080");
App::new()
2023-12-18 14:39:05 +01:00
.wrap(cors)
.wrap(middleware::Compress::default())
.wrap(middleware::Logger::default())
.wrap(middleware::NormalizePath::trim())
.service(
scope("/api")
.service(get_posts)
.service(new_post)
.service(new_comment)
.service(get_comments)
2023-10-27 16:05:12 +02:00
.service(post_by_id)
.service(login)
.service(register)
2023-10-21 05:11:42 +02:00
.app_data(Data::new(data.clone()))
.app_data(Data::new(capt_db.clone()))
.app_data(Data::new(auth.clone())),
)
.service(
Files::new("/", "./public")
.index_file("index.html")
.default_handler(actix_files::NamedFile::open("./public/index.html").unwrap()),
)
2023-10-09 19:21:55 +02:00
})
.bind("0.0.0.0:8080")?
2023-10-09 19:21:55 +02:00
.run()
.await
}