From bc5f721de8996b48550b5069f5592caf2968e822 Mon Sep 17 00:00:00 2001 From: fx Date: Mon, 9 Oct 2023 13:07:54 +0200 Subject: added wol func and bad auth --- src/routes/start.rs | 57 ++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 48 insertions(+), 9 deletions(-) (limited to 'src/routes/start.rs') diff --git a/src/routes/start.rs b/src/routes/start.rs index cda6352..e7d7e0e 100644 --- a/src/routes/start.rs +++ b/src/routes/start.rs @@ -1,18 +1,33 @@ use axum::headers::HeaderMap; +use axum::http::StatusCode; use axum::Json; +use axum::response::{IntoResponse, Response}; use serde::{Deserialize, Serialize}; +use std::error::Error; use serde_json::{json, Value}; -use crate::auth::auth; +use tracing::error; +use crate::auth::{auth, AuthError}; +use crate::config::SETTINGS; +use crate::wol::{create_buffer, send_packet}; -pub async fn start(headers: HeaderMap, Json(payload): Json) -> Json { - let mut res = StartResponse { id: payload.id, boot: false }; - if let Some(secret) = headers.get("authorization") { - if !auth(secret.to_str().unwrap()) { Json(json!(res)) } else { - res.boot = true; - Json(json!(res)) - } +pub async fn start(headers: HeaderMap, Json(payload): Json) -> Result, StartError> { + let secret = headers.get("authorization"); + if auth(secret).map_err(StartError::Auth)? { + let bind_addr = SETTINGS + .get_string("bindaddr") + .map_err(|err| StartError::Server(Box::new(err)))?; + let broadcast_addr = SETTINGS + .get_string("broadcastaddr") + .map_err(|err| StartError::Server(Box::new(err)))?; + let _ = send_packet( + &bind_addr.parse().map_err(|err| StartError::Server(Box::new(err)))?, + &broadcast_addr.parse().map_err(|err| StartError::Server(Box::new(err)))?, + // TODO: MAC saved in DB + create_buffer(std::env::var("MAC").unwrap().as_str()).map_err(|err| StartError::Server(Box::new(err)))? + ).map_err(|err| StartError::Server(Box::new(err))); + Ok(Json(json!(StartResponse { id: payload.id, boot: true }))) } else { - Json(json!(res)) + Err(StartError::Generic) } } @@ -27,3 +42,27 @@ struct StartResponse { id: String, boot: bool, } + +pub enum StartError { + Auth(AuthError), + Generic, + Server(Box), +} + +impl IntoResponse for StartError { + fn into_response(self) -> Response { + let (status, error_message) = match self { + StartError::Auth(err) => err.get(), + StartError::Generic => (StatusCode::INTERNAL_SERVER_ERROR, ""), + StartError::Server(err) => { + error!("server error: {}", err.to_string()); + (StatusCode::INTERNAL_SERVER_ERROR, "Server Error") + }, + + }; + let body = Json(json!({ + "error": error_message, + })); + (status, body).into_response() + } +} \ No newline at end of file -- cgit v1.2.3