Skip to content

Commit

Permalink
update: use import function in super route
Browse files Browse the repository at this point in the history
  • Loading branch information
tobi-bams committed Aug 30, 2024
1 parent bcbd236 commit e8e5527
Showing 1 changed file with 8 additions and 133 deletions.
141 changes: 8 additions & 133 deletions src/bin/super/routes.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
use crate::auth;
use crate::auth_token::VerifySuperToken;
use crate::cmd::{AddSwarmResponse, ChangePasswordInfo, ChildSwarm, Cmd, LoginInfo, SwarmCmd};
use crate::events::{get_event_tx, EventChan};
use crate::logs::{get_log_tx, LogChans, LOGS};
use crate::cmd::{AddSwarmResponse, ChildSwarm, Cmd, SwarmCmd};
use crate::events::EventChan;
use crate::logs::LogChans;
use fs::{relative, FileServer};
use response::stream::{Event, EventStream};
use rocket::http::Status;
use rocket::response::status::Custom;
use rocket::serde::{
json::{json, Json},
Deserialize, Serialize,
};
use rocket::serde::json::Json;
use rocket::*;
use sphinx_swarm::config::SendSwarmDetailsBody;
use sphinx_swarm::config::SendSwarmDetailsResponse;
use sphinx_swarm::rocket_utils::{CmdRequest, Error, Result, CORS};
use sphinx_swarm::routes::{
all_options, events, login, logs, logstream, refresh_jwt, update_password,
};
use std::sync::Arc;
use tokio::sync::{broadcast::error::RecvError, mpsc, Mutex};
use tokio::sync::{mpsc, Mutex};

pub async fn launch_rocket(
tx: mpsc::Sender<CmdRequest>,
Expand Down Expand Up @@ -47,11 +46,6 @@ pub async fn launch_rocket(
.await?)
}

#[options("/<_..>")]
pub fn all_options() {
/* Intentionally left empty */
}

#[get("/cmd?<tag>&<txt>")]
pub async fn cmd(
sender: &State<mpsc::Sender<CmdRequest>>,
Expand All @@ -65,125 +59,6 @@ pub async fn cmd(
Ok(reply)
}

#[get("/events")]
pub async fn events(event_tx: &State<Arc<Mutex<EventChan>>>, mut end: Shutdown) -> EventStream![] {
let event_tx = get_event_tx(event_tx).await;
let mut rx = event_tx.subscribe();
EventStream! {
loop {
let msg = tokio::select! {
msg = rx.recv() => match msg {
Ok(lo) => lo,
Err(RecvError::Closed) => break,
Err(RecvError::Lagged(_)) => continue,
},
_ = &mut end => break,
};

yield Event::json(&msg);
}
}
}

#[get("/logs?<tag>")]
pub async fn logs(tag: &str) -> Result<String> {
let lgs = LOGS.lock().await;
let ret = lgs.get(tag).unwrap_or(&Vec::new()).clone();
Ok(json!(ret).to_string())
}

#[get("/logstream?<tag>")]
pub async fn logstream(
log_txs: &State<Arc<Mutex<LogChans>>>,
mut end: Shutdown,
tag: &str,
) -> EventStream![] {
let log_tx = get_log_tx(tag, log_txs).await;
let mut rx = log_tx.subscribe();
EventStream! {
loop {
let msg = tokio::select! {
msg = rx.recv() => match msg {
Ok(lo) => lo,
Err(RecvError::Closed) => break,
Err(RecvError::Lagged(_)) => continue,
},
_ = &mut end => break,
};

yield Event::json(&msg);
}
}
}

#[derive(Deserialize)]
#[serde(crate = "rocket::serde")]
pub struct LoginData {
pub username: String,
pub password: String,
}
#[derive(Serialize)]
#[serde(crate = "rocket::serde")]
pub struct LoginResult {
pub token: String,
}

#[rocket::post("/login", data = "<body>")]
pub async fn login(
sender: &State<mpsc::Sender<CmdRequest>>,
body: Json<LoginData>,
) -> Result<String> {
let cmd: Cmd = Cmd::Swarm(SwarmCmd::Login(LoginInfo {
username: body.username.clone(),
password: body.password.clone(),
}));
let txt = serde_json::to_string(&cmd)?;
let (request, reply_rx) = CmdRequest::new("SWARM", &txt, None);
let _ = sender.send(request).await.map_err(|_| Error::Fail)?;
let reply = reply_rx.await.map_err(|_| Error::Fail)?;
// empty string means unauthorized
if reply.len() == 0 {
return Err(Error::Unauthorized);
}
Ok(reply)
}

#[rocket::get("/refresh_jwt")]
pub async fn refresh_jwt(claims: auth::AdminJwtClaims) -> Result<Json<LoginResult>> {
Ok(Json(LoginResult {
token: auth::make_jwt(claims.user)?,
}))
}

#[derive(Deserialize)]
#[serde(crate = "rocket::serde")]
pub struct UpdatePasswordData {
pub old_pass: String,
pub password: String,
}

#[rocket::put("/admin/password", data = "<body>")]
pub async fn update_password(
sender: &State<mpsc::Sender<CmdRequest>>,
body: Json<UpdatePasswordData>,
claims: auth::AdminJwtClaims,
) -> Result<String> {
let cmd: Cmd = Cmd::Swarm(SwarmCmd::ChangePassword(ChangePasswordInfo {
user_id: claims.user,
old_pass: body.old_pass.clone(),
password: body.password.clone(),
}));
let txt = serde_json::to_string(&cmd)?;
let (request, reply_rx) = CmdRequest::new("SWARM", &txt, Some(claims.user));
let _ = sender.send(request).await.map_err(|_| Error::Fail)?;
let reply = reply_rx.await.map_err(|_| Error::Fail)?;
// empty string means unauthorized
if reply.len() == 0 {
return Err(Error::Unauthorized);
}
Ok(reply)
}

#[rocket::post("/super/add_new_swarm", data = "<body>")]
pub async fn add_new_swarm(
sender: &State<mpsc::Sender<CmdRequest>>,
Expand Down

0 comments on commit e8e5527

Please sign in to comment.