summaryrefslogtreecommitdiff
path: root/src/routes/start.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/routes/start.rs')
-rw-r--r--src/routes/start.rs57
1 files changed, 48 insertions, 9 deletions
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 @@
1use axum::headers::HeaderMap; 1use axum::headers::HeaderMap;
2use axum::http::StatusCode;
2use axum::Json; 3use axum::Json;
4use axum::response::{IntoResponse, Response};
3use serde::{Deserialize, Serialize}; 5use serde::{Deserialize, Serialize};
6use std::error::Error;
4use serde_json::{json, Value}; 7use serde_json::{json, Value};
5use crate::auth::auth; 8use tracing::error;
9use crate::auth::{auth, AuthError};
10use crate::config::SETTINGS;
11use crate::wol::{create_buffer, send_packet};
6 12
7pub async fn start(headers: HeaderMap, Json(payload): Json<StartPayload>) -> Json<Value> { 13pub async fn start(headers: HeaderMap, Json(payload): Json<StartPayload>) -> Result<Json<Value>, StartError> {
8 let mut res = StartResponse { id: payload.id, boot: false }; 14 let secret = headers.get("authorization");
9 if let Some(secret) = headers.get("authorization") { 15 if auth(secret).map_err(StartError::Auth)? {
10 if !auth(secret.to_str().unwrap()) { Json(json!(res)) } else { 16 let bind_addr = SETTINGS
11 res.boot = true; 17 .get_string("bindaddr")
12 Json(json!(res)) 18 .map_err(|err| StartError::Server(Box::new(err)))?;
13 } 19 let broadcast_addr = SETTINGS
20 .get_string("broadcastaddr")
21 .map_err(|err| StartError::Server(Box::new(err)))?;
22 let _ = send_packet(
23 &bind_addr.parse().map_err(|err| StartError::Server(Box::new(err)))?,
24 &broadcast_addr.parse().map_err(|err| StartError::Server(Box::new(err)))?,
25 // TODO: MAC saved in DB
26 create_buffer(std::env::var("MAC").unwrap().as_str()).map_err(|err| StartError::Server(Box::new(err)))?
27 ).map_err(|err| StartError::Server(Box::new(err)));
28 Ok(Json(json!(StartResponse { id: payload.id, boot: true })))
14 } else { 29 } else {
15 Json(json!(res)) 30 Err(StartError::Generic)
16 } 31 }
17} 32}
18 33
@@ -27,3 +42,27 @@ struct StartResponse {
27 id: String, 42 id: String,
28 boot: bool, 43 boot: bool,
29} 44}
45
46pub enum StartError {
47 Auth(AuthError),
48 Generic,
49 Server(Box<dyn Error>),
50}
51
52impl IntoResponse for StartError {
53 fn into_response(self) -> Response {
54 let (status, error_message) = match self {
55 StartError::Auth(err) => err.get(),
56 StartError::Generic => (StatusCode::INTERNAL_SERVER_ERROR, ""),
57 StartError::Server(err) => {
58 error!("server error: {}", err.to_string());
59 (StatusCode::INTERNAL_SERVER_ERROR, "Server Error")
60 },
61
62 };
63 let body = Json(json!({
64 "error": error_message,
65 }));
66 (status, body).into_response()
67 }
68} \ No newline at end of file