Files
narlblog/backend/src/main.rs

329 lines
9.8 KiB
Rust

use axum::{
extract::{DefaultBodyLimit, Multipart, Path, State},
http::{HeaderMap, StatusCode},
response::{IntoResponse, Json},
routing::{get, post, delete},
Router,
};
use serde::{Deserialize, Serialize};
use std::{env, fs, path::PathBuf, sync::Arc};
use tower_http::{
cors::{Any, CorsLayer},
services::ServeDir,
};
use tracing::{error, info};
#[derive(Clone)]
struct AppState {
admin_token: String,
data_dir: PathBuf,
}
#[derive(Serialize, Deserialize, Clone)]
struct SiteConfig {
title: String,
subtitle: String,
footer: String,
favicon: String,
theme: String,
custom_css: String,
}
impl Default for SiteConfig {
fn default() -> Self {
Self {
title: "Narlblog".to_string(),
subtitle: "A clean, modern blog".to_string(),
footer: "Built with Rust & Astro".to_string(),
favicon: "/favicon.svg".to_string(),
theme: "mocha".to_string(),
custom_css: "".to_string(),
}
}
}
#[derive(Serialize)]
struct PostInfo {
slug: String,
}
#[derive(Serialize)]
struct PostDetail {
slug: String,
content: String,
}
#[derive(Deserialize)]
struct CreatePostRequest {
slug: String,
content: String,
}
#[derive(Serialize)]
struct ErrorResponse {
error: String,
}
#[derive(Serialize)]
struct UploadResponse {
url: String,
}
#[derive(Serialize)]
struct FileInfo {
name: String,
url: String,
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
dotenvy::dotenv().ok();
let port = env::var("PORT").unwrap_or_else(|_| "3000".to_string());
let admin_token = env::var("ADMIN_TOKEN").unwrap_or_else(|_| "secret".to_string());
let data_dir_str = env::var("DATA_DIR").unwrap_or_else(|_| "../data".to_string());
let data_dir = PathBuf::from(data_dir_str);
// Ensure directories exist
let posts_dir = data_dir.join("posts");
let uploads_dir = data_dir.join("uploads");
fs::create_dir_all(&posts_dir).expect("Failed to create posts directory");
fs::create_dir_all(&uploads_dir).expect("Failed to create uploads directory");
let state = Arc::new(AppState {
admin_token,
data_dir,
});
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods(Any)
.allow_headers(Any);
let app = Router::new()
.route("/api/config", get(get_config).post(update_config))
.route("/api/posts", get(list_posts).post(create_post))
.route("/api/posts/{slug}", get(get_post).delete(delete_post))
.route("/api/uploads", get(list_uploads))
.route("/api/upload", post(upload_file))
.nest_service("/uploads", ServeDir::new(uploads_dir))
.layer(DefaultBodyLimit::max(50 * 1024 * 1024)) // 50MB limit
.layer(cors)
.with_state(state);
let addr = format!("0.0.0.0:{}", port);
info!("Starting server on {}", addr);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
axum::serve(listener, app).await.unwrap();
}
fn check_auth(headers: &HeaderMap, admin_token: &str) -> Result<(), (StatusCode, Json<ErrorResponse>)> {
let auth_header = headers.get("Authorization").and_then(|h| h.to_str().ok());
if auth_header != Some(&format!("Bearer {}", admin_token)) {
return Err((
StatusCode::UNAUTHORIZED,
Json(ErrorResponse { error: "Unauthorized".to_string() }),
));
}
Ok(())
}
async fn get_config(State(state): State<Arc<AppState>>) -> impl IntoResponse {
let config_path = state.data_dir.join("config.json");
let config = fs::read_to_string(&config_path)
.ok()
.and_then(|c| serde_json::from_str::<SiteConfig>(&c).ok())
.unwrap_or_default();
Json(config)
}
async fn update_config(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
Json(payload): Json<SiteConfig>,
) -> Result<Json<SiteConfig>, (StatusCode, Json<ErrorResponse>)> {
check_auth(&headers, &state.admin_token)?;
let config_path = state.data_dir.join("config.json");
let config_str = serde_json::to_string_pretty(&payload).map_err(|_| {
(StatusCode::INTERNAL_SERVER_ERROR, Json(ErrorResponse { error: "Serialization error".to_string() }))
})?;
fs::write(&config_path, config_str).map_err(|_| {
(StatusCode::INTERNAL_SERVER_ERROR, Json(ErrorResponse { error: "Write error".to_string() }))
})?;
Ok(Json(payload))
}
async fn create_post(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
Json(payload): Json<CreatePostRequest>,
) -> Result<Json<PostDetail>, (StatusCode, Json<ErrorResponse>)> {
check_auth(&headers, &state.admin_token)?;
// Validate slug to prevent directory traversal
if payload.slug.contains('/') || payload.slug.contains('\\') || payload.slug.contains("..") {
return Err((
StatusCode::BAD_REQUEST,
Json(ErrorResponse { error: "Invalid slug".to_string() }),
));
}
let file_path = state.data_dir.join("posts").join(format!("{}.md", payload.slug));
fs::write(&file_path, &payload.content).map_err(|_| {
(StatusCode::INTERNAL_SERVER_ERROR, Json(ErrorResponse { error: "Write error".to_string() }))
})?;
Ok(Json(PostDetail {
slug: payload.slug,
content: payload.content,
}))
}
async fn delete_post(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
Path(slug): Path<String>,
) -> Result<StatusCode, (StatusCode, Json<ErrorResponse>)> {
check_auth(&headers, &state.admin_token)?;
let file_path = state.data_dir.join("posts").join(format!("{}.md", slug));
// Security check to prevent directory traversal
if file_path.parent() != Some(&state.data_dir.join("posts")) {
return Err((
StatusCode::BAD_REQUEST,
Json(ErrorResponse { error: "Invalid slug".to_string() }),
));
}
if file_path.exists() {
fs::remove_file(file_path).map_err(|_| {
(StatusCode::INTERNAL_SERVER_ERROR, Json(ErrorResponse { error: "Delete error".to_string() }))
})?;
Ok(StatusCode::NO_CONTENT)
} else {
Err((
StatusCode::NOT_FOUND,
Json(ErrorResponse { error: "Post not found".to_string() }),
))
}
}
async fn list_uploads(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
) -> Result<Json<Vec<FileInfo>>, (StatusCode, Json<ErrorResponse>)> {
check_auth(&headers, &state.admin_token)?;
let uploads_dir = state.data_dir.join("uploads");
let mut files = Vec::new();
if let Ok(entries) = fs::read_dir(uploads_dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() {
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
files.push(FileInfo {
name: name.to_string(),
url: format!("/uploads/{}", name),
});
}
}
}
}
Ok(Json(files))
}
async fn list_posts(State(state): State<Arc<AppState>>) -> impl IntoResponse {
let posts_dir = state.data_dir.join("posts");
let mut posts = Vec::new();
if let Ok(entries) = fs::read_dir(posts_dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) == Some("md") {
if let Some(slug) = path.file_stem().and_then(|s| s.to_str()) {
posts.push(PostInfo {
slug: slug.to_string(),
});
}
}
}
}
Json(posts)
}
async fn get_post(
State(state): State<Arc<AppState>>,
Path(slug): Path<String>,
) -> Result<Json<PostDetail>, (StatusCode, Json<ErrorResponse>)> {
let file_path = state.data_dir.join("posts").join(format!("{}.md", slug));
// Security check to prevent directory traversal
if file_path.parent() != Some(&state.data_dir.join("posts")) {
return Err((
StatusCode::BAD_REQUEST,
Json(ErrorResponse { error: "Invalid slug".to_string() }),
));
}
match fs::read_to_string(&file_path) {
Ok(content) => Ok(Json(PostDetail { slug, content })),
Err(_) => Err((
StatusCode::NOT_FOUND,
Json(ErrorResponse { error: "Post not found".to_string() }),
)),
}
}
async fn upload_file(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
mut multipart: Multipart,
) -> Result<Json<UploadResponse>, (StatusCode, Json<ErrorResponse>)> {
check_auth(&headers, &state.admin_token)?;
while let Ok(Some(field)) = multipart.next_field().await {
if let Some(file_name) = field.file_name() {
let file_name = slug::slugify(file_name);
let uploads_dir = state.data_dir.join("uploads");
let file_path = uploads_dir.join(&file_name);
// Simple conflict resolution
let final_path = if file_path.exists() {
let timestamp = chrono::Utc::now().timestamp();
uploads_dir.join(format!("{}_{}", timestamp, file_name))
} else {
file_path
};
let final_name = final_path.file_name().unwrap().to_str().unwrap().to_string();
let data = field.bytes().await.map_err(|_| {
(StatusCode::INTERNAL_SERVER_ERROR, Json(ErrorResponse { error: "Read error".to_string() }))
})?;
fs::write(&final_path, &data).map_err(|_| {
(StatusCode::INTERNAL_SERVER_ERROR, Json(ErrorResponse { error: "Write error".to_string() }))
})?;
return Ok(Json(UploadResponse {
url: format!("/uploads/{}", final_name),
}));
}
}
Err((
StatusCode::BAD_REQUEST,
Json(ErrorResponse { error: "No file found".to_string() }),
))
}