more refactoring
This commit is contained in:
parent
13e17770ca
commit
7268d49b4a
12 changed files with 319 additions and 189 deletions
|
|
@ -1,7 +1,7 @@
|
|||
use axum::{
|
||||
Json, RequestPartsExt,
|
||||
extract::{FromRef, FromRequestParts, Query, State},
|
||||
http::{StatusCode, request::Parts},
|
||||
http::request::Parts,
|
||||
response::IntoResponse,
|
||||
};
|
||||
use axum_extra::{
|
||||
|
|
@ -12,10 +12,9 @@ use axum_extra::{
|
|||
use std::sync::Arc;
|
||||
|
||||
use super::AppState;
|
||||
use crate::domain::auth::Claims;
|
||||
use crate::error::{AppError, AppResult};
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub struct AuthenticatedUser(pub Claims);
|
||||
pub struct AuthenticatedUser(pub crate::domain::auth::Claims);
|
||||
|
||||
#[axum::async_trait]
|
||||
impl<S> FromRequestParts<S> for AuthenticatedUser
|
||||
|
|
@ -23,7 +22,7 @@ where
|
|||
Arc<AppState>: axum::extract::FromRef<S>,
|
||||
S: Send + Sync,
|
||||
{
|
||||
type Rejection = (StatusCode, String);
|
||||
type Rejection = AppError;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
|
||||
let app_state = Arc::<AppState>::from_ref(state);
|
||||
|
|
@ -33,22 +32,22 @@ where
|
|||
{
|
||||
Some(bearer.token().to_string())
|
||||
} else {
|
||||
let jar = parts.extract::<CookieJar>().await.unwrap();
|
||||
let jar = parts
|
||||
.extract::<CookieJar>()
|
||||
.await
|
||||
.map_err(|e| AppError::Internal(e.to_string()))?;
|
||||
jar.get("access_token")
|
||||
.map(|cookie| cookie.value().to_string())
|
||||
};
|
||||
|
||||
let token = token.ok_or((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"Missing or invalid access token".to_string(),
|
||||
))?;
|
||||
let token = token
|
||||
.ok_or_else(|| AppError::Unauthorized("Missing or invalid access token".into()))?;
|
||||
|
||||
let claims = app_state.verifier.verify(&token).await.map_err(|e| {
|
||||
(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
format!("Token verification failed: {}", e),
|
||||
)
|
||||
})?;
|
||||
let claims = app_state
|
||||
.verifier
|
||||
.verify(&token)
|
||||
.await
|
||||
.map_err(|e| AppError::Unauthorized(format!("Token verification failed: {}", e)))?;
|
||||
|
||||
Ok(AuthenticatedUser(claims))
|
||||
}
|
||||
|
|
@ -69,7 +68,7 @@ pub async fn auth_refresh(
|
|||
State(state): State<Arc<AppState>>,
|
||||
jar: CookieJar,
|
||||
Json(payload): Json<RefreshRequest>,
|
||||
) -> Result<impl IntoResponse, (StatusCode, String)> {
|
||||
) -> AppResult<impl IntoResponse> {
|
||||
let refresh_token = payload
|
||||
.refresh_token
|
||||
.filter(|token| !token.is_empty())
|
||||
|
|
@ -77,16 +76,13 @@ pub async fn auth_refresh(
|
|||
jar.get("refresh_token")
|
||||
.map(|cookie| cookie.value().to_string())
|
||||
})
|
||||
.ok_or((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"Missing refresh token".to_string(),
|
||||
))?;
|
||||
.ok_or_else(|| AppError::Unauthorized("Missing refresh token".into()))?;
|
||||
|
||||
let data = state
|
||||
.authenticator
|
||||
.refresh_token(refresh_token)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::UNAUTHORIZED, e.to_string()))?;
|
||||
.map_err(|e| AppError::Unauthorized(e.to_string()))?;
|
||||
|
||||
let jar = update_auth_cookies(jar, &data, &state.config);
|
||||
Ok((jar, Json(data)))
|
||||
|
|
@ -96,17 +92,12 @@ pub async fn auth_callback(
|
|||
State(state): State<Arc<AppState>>,
|
||||
jar: CookieJar,
|
||||
Query(query): Query<AuthCallbackQuery>,
|
||||
) -> Result<impl IntoResponse, (StatusCode, String)> {
|
||||
) -> AppResult<impl IntoResponse> {
|
||||
let data = state
|
||||
.authenticator
|
||||
.exchange_code(query.code, query.redirect_uri)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Token exchange failed: {}", e),
|
||||
)
|
||||
})?;
|
||||
.map_err(|e| AppError::Internal(format!("Token exchange failed: {}", e)))?;
|
||||
|
||||
let jar = update_auth_cookies(jar, &data, &state.config);
|
||||
Ok((jar, Json(data)))
|
||||
|
|
@ -114,7 +105,7 @@ pub async fn auth_callback(
|
|||
|
||||
pub async fn auth_logout(State(state): State<Arc<AppState>>, jar: CookieJar) -> impl IntoResponse {
|
||||
let jar = clear_auth_cookies(jar, &state.config);
|
||||
(jar, StatusCode::NO_CONTENT)
|
||||
(jar, axum::http::StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
pub async fn auth_session(user: AuthenticatedUser) -> Json<serde_json::Value> {
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ use tower_http::cors::{AllowOrigin, CorsLayer};
|
|||
use crate::entities::task::Entity as Task;
|
||||
use crate::scheduler::Scheduler;
|
||||
|
||||
use crate::error::AppResult;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
pub db: DatabaseConnection,
|
||||
|
|
@ -23,37 +25,29 @@ pub struct AppState {
|
|||
pub authenticator: Arc<crate::domain::auth::Authenticator>,
|
||||
}
|
||||
|
||||
pub async fn start(config: crate::config::Config) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let db = Database::connect(&config.database_url).await?;
|
||||
Migrator::up(&db, None).await?;
|
||||
pub async fn start(config: crate::config::Config) -> AppResult<()> {
|
||||
let db = setup_database(&config.database_url).await?;
|
||||
|
||||
let config = Arc::new(config);
|
||||
|
||||
let scheduler = Arc::new(Scheduler::new(db.clone(), config.clone()).await?);
|
||||
let scheduler = Arc::new(
|
||||
Scheduler::new(db.clone(), config.clone())
|
||||
.await
|
||||
.map_err(|e| crate::error::AppError::Internal(e.to_string()))?,
|
||||
);
|
||||
|
||||
// Load existing scheduled tasks
|
||||
let existing_tasks = Task::find().all(&db).await?;
|
||||
let existing_tasks = Task::find()
|
||||
.all(&db)
|
||||
.await
|
||||
.map_err(crate::error::AppError::Database)?;
|
||||
for task in existing_tasks {
|
||||
if let Some(cron) = task.cron {
|
||||
let _ = scheduler.add_task_job(task.id, &cron).await;
|
||||
}
|
||||
}
|
||||
|
||||
let verifier = Arc::new(
|
||||
crate::domain::auth::JwksVerifier::new(
|
||||
config.authentik_issuer.clone(),
|
||||
config.authentik_client_id.clone(),
|
||||
)
|
||||
.await?,
|
||||
);
|
||||
let authenticator = Arc::new(
|
||||
crate::domain::auth::Authenticator::new(
|
||||
config.authentik_issuer.clone(),
|
||||
config.authentik_client_id.clone(),
|
||||
config.authentik_client_secret.clone(),
|
||||
)
|
||||
.await?,
|
||||
);
|
||||
let (verifier, authenticator) = setup_auth(&config).await?;
|
||||
|
||||
let state = Arc::new(AppState {
|
||||
db,
|
||||
|
|
@ -63,9 +57,61 @@ pub async fn start(config: crate::config::Config) -> Result<(), Box<dyn std::err
|
|||
authenticator,
|
||||
});
|
||||
|
||||
let cors = build_cors_layer(&config);
|
||||
let app = build_app(state, &config);
|
||||
|
||||
let app = Router::new()
|
||||
let addr = format!("0.0.0.0:{}", config.port);
|
||||
let listener = tokio::net::TcpListener::bind(&addr)
|
||||
.await
|
||||
.map_err(|e| crate::error::AppError::Internal(e.to_string()))?;
|
||||
println!("Server running on http://localhost:{}", config.port);
|
||||
axum::serve(listener, app)
|
||||
.await
|
||||
.map_err(|e| crate::error::AppError::Internal(e.to_string()))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn setup_database(database_url: &str) -> AppResult<DatabaseConnection> {
|
||||
let db = Database::connect(database_url)
|
||||
.await
|
||||
.map_err(crate::error::AppError::Database)?;
|
||||
Migrator::up(&db, None)
|
||||
.await
|
||||
.map_err(crate::error::AppError::Database)?;
|
||||
Ok(db)
|
||||
}
|
||||
|
||||
async fn setup_auth(
|
||||
config: &crate::config::Config,
|
||||
) -> AppResult<(
|
||||
Arc<crate::domain::auth::JwksVerifier>,
|
||||
Arc<crate::domain::auth::Authenticator>,
|
||||
)> {
|
||||
let verifier = Arc::new(
|
||||
crate::domain::auth::JwksVerifier::new(
|
||||
config.authentik_issuer.clone(),
|
||||
config.authentik_client_id.clone(),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| crate::error::AppError::Internal(e.to_string()))?,
|
||||
);
|
||||
let authenticator = Arc::new(
|
||||
crate::domain::auth::Authenticator::new(
|
||||
config.authentik_issuer.clone(),
|
||||
config.authentik_client_id.clone(),
|
||||
config.authentik_client_secret.clone(),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| crate::error::AppError::Internal(e.to_string()))?,
|
||||
);
|
||||
|
||||
Ok((verifier, authenticator))
|
||||
}
|
||||
|
||||
fn build_app(state: Arc<AppState>, config: &crate::config::Config) -> Router {
|
||||
let cors = build_cors_layer(config);
|
||||
|
||||
Router::new()
|
||||
.route("/api/tasks", post(tasks::create_task).get(tasks::list_tasks))
|
||||
.route("/api/tasks/:id", get(tasks::get_task).put(tasks::update_task))
|
||||
.route("/api/tasks/:id/runs", post(tasks::rerun_task))
|
||||
|
|
@ -88,14 +134,7 @@ pub async fn start(config: crate::config::Config) -> Result<(), Box<dyn std::err
|
|||
HeaderValue::from_static("strict-origin-when-cross-origin"),
|
||||
))
|
||||
.layer(tower_http::limit::RequestBodyLimitLayer::new(1024 * 1024)) // 1MB limit
|
||||
.with_state(state);
|
||||
|
||||
let addr = format!("0.0.0.0:{}", config.port);
|
||||
let listener = tokio::net::TcpListener::bind(&addr).await?;
|
||||
println!("Server running on http://localhost:{}", config.port);
|
||||
axum::serve(listener, app).await?;
|
||||
|
||||
Ok(())
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
fn build_cors_layer(config: &crate::config::Config) -> CorsLayer {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
use axum::{
|
||||
Json,
|
||||
extract::{Path, State},
|
||||
http::StatusCode,
|
||||
};
|
||||
use sea_orm::{EntityTrait, QueryOrder, QuerySelect};
|
||||
use std::sync::Arc;
|
||||
|
|
@ -13,16 +12,17 @@ use crate::domain::tasks::{
|
|||
self, CreateTaskRequest, RecentRunResponse, TaskResponse, UpdateTaskRequest,
|
||||
};
|
||||
|
||||
use crate::error::AppResult;
|
||||
|
||||
pub async fn list_tasks(
|
||||
_user: AuthenticatedUser,
|
||||
State(state): State<Arc<AppState>>,
|
||||
) -> Result<Json<Vec<TaskResponse>>, (StatusCode, String)> {
|
||||
) -> AppResult<Json<Vec<TaskResponse>>> {
|
||||
let tasks = crate::entities::task::Entity::find()
|
||||
.find_with_related(crate::entities::task_run::Entity)
|
||||
.order_by_desc(crate::entities::task::Column::CreatedAt)
|
||||
.all(&state.db)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
.await?;
|
||||
|
||||
let response = tasks
|
||||
.into_iter()
|
||||
|
|
@ -54,7 +54,7 @@ pub async fn create_task(
|
|||
_user: AuthenticatedUser,
|
||||
State(state): State<Arc<AppState>>,
|
||||
Json(payload): Json<CreateTaskRequest>,
|
||||
) -> Result<Json<TaskResponse>, (StatusCode, String)> {
|
||||
) -> AppResult<Json<TaskResponse>> {
|
||||
let task_id = Uuid::new_v4();
|
||||
|
||||
let new_task = crate::entities::task::ActiveModel {
|
||||
|
|
@ -65,10 +65,7 @@ pub async fn create_task(
|
|||
};
|
||||
|
||||
use sea_orm::ActiveModelTrait;
|
||||
new_task
|
||||
.insert(&state.db)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
new_task.insert(&state.db).await?;
|
||||
|
||||
if let Some(cron) = &payload.cron {
|
||||
let _ = state.scheduler.add_task_job(task_id, cron).await;
|
||||
|
|
@ -79,19 +76,18 @@ pub async fn create_task(
|
|||
tasks::get_task_inner(task_id, &state.db)
|
||||
.await
|
||||
.map(Json)
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
|
||||
.map_err(|e| crate::error::AppError::Internal(e.to_string()))
|
||||
}
|
||||
|
||||
pub async fn rerun_task(
|
||||
_user: AuthenticatedUser,
|
||||
State(state): State<Arc<AppState>>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<TaskResponse>, (StatusCode, String)> {
|
||||
) -> AppResult<Json<TaskResponse>> {
|
||||
let task = crate::entities::task::Entity::find_by_id(id)
|
||||
.one(&state.db)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
|
||||
.ok_or((StatusCode::NOT_FOUND, "Task not found".to_string()))?;
|
||||
.await?
|
||||
.ok_or_else(|| crate::error::AppError::NotFound("Task not found".to_string()))?;
|
||||
|
||||
tasks::execute_agent_run(
|
||||
&state.db,
|
||||
|
|
@ -102,7 +98,7 @@ pub async fn rerun_task(
|
|||
)
|
||||
.await
|
||||
.map(Json)
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
|
||||
.map_err(|e| crate::error::AppError::Internal(e.to_string()))
|
||||
}
|
||||
|
||||
pub async fn update_task(
|
||||
|
|
@ -110,22 +106,19 @@ pub async fn update_task(
|
|||
State(state): State<Arc<AppState>>,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(payload): Json<UpdateTaskRequest>,
|
||||
) -> Result<Json<TaskResponse>, (StatusCode, String)> {
|
||||
let mut task: crate::entities::task::ActiveModel =
|
||||
crate::entities::task::Entity::find_by_id(id)
|
||||
.one(&state.db)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
|
||||
.ok_or((StatusCode::NOT_FOUND, "Task not found".to_string()))?
|
||||
.into();
|
||||
) -> AppResult<Json<TaskResponse>> {
|
||||
let task: crate::entities::task::ActiveModel = crate::entities::task::Entity::find_by_id(id)
|
||||
.one(&state.db)
|
||||
.await?
|
||||
.ok_or_else(|| crate::error::AppError::NotFound("Task not found".to_string()))?
|
||||
.into();
|
||||
|
||||
let mut task = task;
|
||||
task.goal = sea_orm::Set(payload.goal.clone());
|
||||
task.cron = sea_orm::Set(payload.cron.clone());
|
||||
|
||||
use sea_orm::ActiveModelTrait;
|
||||
task.update(&state.db)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
task.update(&state.db).await?;
|
||||
|
||||
if let Some(cron) = &payload.cron {
|
||||
let _ = state.scheduler.add_task_job(id, cron).await;
|
||||
|
|
@ -136,31 +129,30 @@ pub async fn update_task(
|
|||
tasks::get_task_inner(id, &state.db)
|
||||
.await
|
||||
.map(Json)
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
|
||||
.map_err(|e| crate::error::AppError::Internal(e.to_string()))
|
||||
}
|
||||
|
||||
pub async fn get_task(
|
||||
_user: AuthenticatedUser,
|
||||
Path(id): Path<Uuid>,
|
||||
State(state): State<Arc<AppState>>,
|
||||
) -> Result<Json<TaskResponse>, (StatusCode, String)> {
|
||||
) -> AppResult<Json<TaskResponse>> {
|
||||
tasks::get_task_inner(id, &state.db)
|
||||
.await
|
||||
.map(Json)
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
|
||||
.map_err(|e| crate::error::AppError::Internal(e.to_string()))
|
||||
}
|
||||
|
||||
pub async fn get_recent_runs(
|
||||
_user: AuthenticatedUser,
|
||||
State(state): State<Arc<AppState>>,
|
||||
) -> Result<Json<Vec<RecentRunResponse>>, (StatusCode, String)> {
|
||||
) -> AppResult<Json<Vec<RecentRunResponse>>> {
|
||||
let results = crate::entities::task_run::Entity::find()
|
||||
.find_also_related(crate::entities::task::Entity)
|
||||
.order_by_desc(crate::entities::task_run::Column::CreatedAt)
|
||||
.limit(50)
|
||||
.all(&state.db)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
.await?;
|
||||
|
||||
let response = results
|
||||
.into_iter()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue