This commit is contained in:
Alvin-Zilverstand committed 2026-11-22 02:02:18 +01:00
1 parent 9268833a3c
commit 314b7445a1
27 files changed
+1830

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
[package]
name = "chronos-api"
version = { workspace = true }
edition = "2021"
authors = ["Chronos Team"]
license = "MIT OR Apache-2.0"
homepage = "https://github.com/chronos/chronos"
repository = "https://github.com/chronos/chronos"
[dependencies]
axum = "0.7"
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
sqlx = { version = "0.7", features = ["postgres", "runtime-tokio-rustls"] }
chrono = { version = "0.4", features = ["serde"] }
tracing = "0.1"
tracing-subscriber = "0.3"
utoipa = { version = "4.0", features = ["axum_extras"] }
thiserror = "1.0"
anyhow = "1.0"
chronos-core = { path = "../chronos-core" }
chronos-auth = { path = "../chronos-auth" }
chronos-database = { path = "../chronos-database" }
+22
View File
@@ -0,0 +1,22 @@
use chronos_auth::{AuthService, AuthError};
use chronos_core::User;
use sqlx::PgPool;
/// API authentication middleware
pub struct AuthMiddleware {
auth_service: AuthService,
}
impl AuthMiddleware {
pub fn new(pool: PgPool) -> Self {
AuthMiddleware {
auth_service: AuthService::new(pool),
}
}
/// Verify that a request has valid authentication
pub async fn verify_auth(&self, token: &str) -> Result<User, AuthError> {
let session = self.auth_service.validate_session(token).await?;
self.auth_service.get_user_by_username(&session.user_id.to_string()).await
}
}
+4
View File
@@ -0,0 +1,4 @@
// Simple test to make sure the workspace builds correctly
fn main() {
println!("Chronos workspace initialized successfully");
}
+100
View File
@@ -0,0 +1,100 @@
use axum::{
extract::State,
http::StatusCode,
response::IntoResponse,
Json,
};
use serde::{Deserialize, Serialize};
use chronos_auth::{AuthService, AuthError};
use chronos_core::{User, Role};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoginRequest {
pub username: String,
pub password: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoginResponse {
pub token: String,
}
/// Handle user login
pub async fn login(
State(auth_service): State<AuthService>,
Json(request): Json<LoginRequest>,
) -> Result<impl IntoResponse, (StatusCode, Json<ErrorResponse>)> {
let user = auth_service.authenticate(&request.username, &request.password)
.await
.map_err(|e| handle_auth_error(e))?;
let session = auth_service.create_session(user.id)
.await
.map_err(|e| handle_auth_error(e))?;
Ok(Json(LoginResponse {
token: session.token,
}))
}
/// Handle user logout
pub async fn logout(
State(auth_service): State<AuthService>,
token: String,
) -> Result<impl IntoResponse, (StatusCode, Json<ErrorResponse>)> {
auth_service.logout(&token)
.await
.map_err(|e| handle_auth_error(e))?;
Ok(StatusCode::NO_CONTENT)
}
/// Get current user info
pub async fn get_current_user(
State(auth_service): State<AuthService>,
token: String,
) -> Result<impl IntoResponse, (StatusCode, Json<ErrorResponse>)> {
let session = auth_service.validate_session(&token)
.await
.map_err(|e| handle_auth_error(e))?;
let user = auth_service.get_user_by_username(&session.user_id.to_string())
.await
.map_err(|e| handle_auth_error(e))?;
Ok(Json(user))
}
/// Error response structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorResponse {
pub code: String,
pub message: String,
}
fn handle_auth_error(error: AuthError) -> (StatusCode, Json<ErrorResponse>) {
let status = match error {
AuthError::InvalidCredentials => StatusCode::UNAUTHORIZED,
AuthError::UserNotFound => StatusCode::NOT_FOUND,
AuthError::InvalidSession => StatusCode::UNAUTHORIZED,
AuthError::AuthenticationRequired => StatusCode::UNAUTHORIZED,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
let code = match error {
AuthError::InvalidCredentials => "INVALID_CREDENTIALS".to_string(),
AuthError::UserNotFound => "USER_NOT_FOUND".to_string(),
AuthError::InvalidSession => "INVALID_SESSION".to_string(),
AuthError::AuthenticationRequired => "AUTHENTICATION_REQUIRED".to_string(),
_ => "INTERNAL_ERROR".to_string(),
};
(
status,
Json(ErrorResponse {
code,
message: error.to_string(),
})
)
}
+45
View File
@@ -0,0 +1,45 @@
//! Chronos API Server
use axum::{
routing::{get, post},
Router,
};
use chronos_auth::AuthService;
use chronos_database::MigrationManager;
use sqlx::PgPool;
use std::net::SocketAddr;
#[tokio::main]
async fn main() {
// Initialize tracing
tracing_subscriber::fmt::init();
// Connect to database
let database_url = std::env::var("DATABASE_URL")
.expect("DATABASE_URL must be set");
let pool = PgPool::connect(&database_url).await
.expect("Failed to connect to database");
// Run migrations
let migration_manager = MigrationManager::new(pool.clone());
migration_manager.run_migrations().await
.expect("Failed to run migrations");
// Create auth service
let auth_service = AuthService::new(pool.clone());
// Build the API router
let app = Router::new()
.route("/api/v1/auth/login", post(handlers::auth::login))
.route("/api/v1/auth/logout", post(handlers::auth::logout))
.route("/api/v1/auth/me", get(handlers::auth::get_current_user))
.with_state(auth_service);
// Start the server
let addr = SocketAddr::from(([127, 0, 0, 1], 8080));
tracing::info!("Starting server on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.expect("Failed to start server");
}