Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ edition = "2021"
[dependencies]
actix-web = "4"
uuid = { version = "0.8.2", features = ["serde", "v4"] }
diesel = { version = "1.4.5", features = ["postgres", "r2d2", "uuidv07"] }
diesel = { version = "1.4.5", features = ["postgres", "r2d2", "uuidv07", "chrono"] }
dotenv = "0.15.0"
r2d2 = "0.8.8"
serde_json = "1.0.44"
Expand Down
Empty file removed migrations/.gitkeep
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DROP TABLE IF EXISTS email_confirmations CASCADE;
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
CREATE TABLE email_confirmations (
id SERIAL PRIMARY KEY,
id_user UUID NOT NULL,
code INT NOT NULL,
expiration_date TIMESTAMP NOT NULL,
CONSTRAINT fk_user
FOREIGN KEY(id_user)
REFERENCES users(id)
)
12 changes: 6 additions & 6 deletions src/agents/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,12 @@ pub struct AgentName {
}

impl InsertableAgent {
fn from_agent(agent: Agent) -> InsertableAgent {
InsertableAgent {
name: agent.name,
token: agent.token,
}
}
// fn from_agent(agent: Agent) -> InsertableAgent {
// InsertableAgent {
// name: agent.name,
// token: agent.token,
// }
// }
}

impl Agent {
Expand Down
4 changes: 2 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,19 +45,19 @@ async fn main() -> std::io::Result<()> {
App::new()
// set up DB pool to be used with web::Data<Pool> extractor
.app_data(web::Data::new(pool.clone()))
// .wrap(middleware::Compress::new(ContentEncoding::Br))
.wrap(middleware::Logger::default())
.route("/", web::get().to(index))
.service(metrics::add_metrics)
.service(organizations::add_organization)
.service(monitors::add_monitor)
// .service(monitors::get_all_monitors_of_user)
.service(agents::add_agents)
.service(roles::add_role)
.service(roles::get_roles)
.service(users::register)
.service(users::login)
.service(users::email_confirmation)
.service(users::user_informations)
.service(users::verify_email_confirmation)
})
.bind(("0.0.0.0", 8080))?
.run()
Expand Down
3 changes: 0 additions & 3 deletions src/metrics/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
use self::model::{InsertableMetric, Metric};
use super::services::email;
use super::DbPool;
use actix_web::{post, web, Error, HttpResponse};
pub mod model;

/// Inserts new user with name defined in form.
#[post("/metrics")]
pub async fn add_metrics(
pool: web::Data<DbPool>,
Expand All @@ -16,6 +14,5 @@ pub async fn add_metrics(
})
.await?
.map_err(actix_web::error::ErrorInternalServerError)?;
let bool = email::send_alert_email("service-ses@jenoh.dev".to_string()).await;
Ok(HttpResponse::Created().json(metric))
}
22 changes: 11 additions & 11 deletions src/metrics/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,17 @@ pub struct InsertableMetric {
}

impl InsertableMetric {
fn from_metric(metric: Metric) -> InsertableMetric {
InsertableMetric {
load_average_1: metric.load_average_1,
load_average_2: metric.load_average_2,
load_average_3: metric.load_average_3,
memory_used: metric.memory_used,
memory_total: metric.memory_total,
cpu_temp: metric.cpu_temp,
cpu_load: metric.cpu_load,
}
}
// fn from_metric(metric: Metric) -> InsertableMetric {
// InsertableMetric {
// load_average_1: metric.load_average_1,
// load_average_2: metric.load_average_2,
// load_average_3: metric.load_average_3,
// memory_used: metric.memory_used,
// memory_total: metric.memory_total,
// cpu_temp: metric.cpu_temp,
// cpu_load: metric.cpu_load,
// }
// }
}

impl Metric {
Expand Down
34 changes: 23 additions & 11 deletions src/schema.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
table! {
// @generated automatically by Diesel CLI.

diesel::table! {
agents (id) {
id -> Int4,
name -> Varchar,
token -> Varchar,
}
}

table! {
diesel::table! {
email_confirmations (id) {
id -> Int4,
id_user -> Uuid,
code -> Int4,
expiration_date -> Timestamp,
}
}

diesel::table! {
lambdas (id) {
id -> Int4,
aws_lambda_region -> Varchar,
Expand All @@ -15,7 +26,7 @@ table! {
}
}

table! {
diesel::table! {
metrics (id) {
id -> Int4,
load_average_1 -> Nullable<Varchar>,
Expand All @@ -29,7 +40,7 @@ table! {
}
}

table! {
diesel::table! {
monitors (id) {
id -> Int4,
name -> Varchar,
Expand All @@ -45,29 +56,29 @@ table! {
}
}

table! {
diesel::table! {
organizations (id) {
id -> Int4,
name -> Varchar,
}
}

table! {
diesel::table! {
organizations_users (id) {
id -> Int4,
id_organization -> Nullable<Int4>,
id_user -> Nullable<Uuid>,
}
}

table! {
diesel::table! {
roles (id) {
id -> Int4,
name -> Varchar,
}
}

table! {
diesel::table! {
users (id) {
id -> Uuid,
email -> Varchar,
Expand All @@ -77,11 +88,12 @@ table! {
}
}

joinable!(monitors -> lambdas (id_lambda));
joinable!(users -> roles (id_role));
diesel::joinable!(monitors -> lambdas (id_lambda));
diesel::joinable!(users -> roles (id_role));

allow_tables_to_appear_in_same_query!(
diesel::allow_tables_to_appear_in_same_query!(
agents,
email_confirmations,
lambdas,
metrics,
monitors,
Expand Down
32 changes: 17 additions & 15 deletions src/services/email.rs
Original file line number Diff line number Diff line change
@@ -1,32 +1,34 @@
use super::template;
use bytes::Bytes;
use mail_builder::MessageBuilder;
use rusoto_ses::{Ses, SesClient};
use rusoto_core::{Region, RusotoError};
use rusoto_ses::{RawMessage, SendRawEmailError, SendRawEmailRequest, Ses, SesClient};

pub async fn send_alert_email(to: String) -> bool {
println!("{}", template::alert_template());
let sesclient = SesClient::new(rusoto_core::Region::EuWest3);
pub async fn send_confirmation_email(
to: String,
code: i32,
) -> Result<(), RusotoError<SendRawEmailError>> {
let sesclient = SesClient::new(Region::EuWest3);
let data_email = MessageBuilder::new()
.from(("John Doe", "john@jenoh.dev"))
.from(("The squareview team", "john@jenoh.dev"))
.to(to.clone())
.subject("Hello, world!")
.html_body(template::alert_template())
.html_body(template::confirmation_email(code))
.write_to_string()
.unwrap();

let result = sesclient
.send_raw_email(rusoto_ses::SendRawEmailRequest {
raw_message: rusoto_ses::RawMessage {
match sesclient
.send_raw_email(SendRawEmailRequest {
raw_message: RawMessage {
data: Bytes::from(base64::encode(data_email.to_string())),
},
destinations: Some(vec![to]),
source: Some("john@jenoh.dev".to_string()),
..rusoto_ses::SendRawEmailRequest::default()
..SendRawEmailRequest::default()
})
.await;
if result.is_err() {
eprintln!("Couldn't send email : {:?}", result);
return false;
.await
{
Ok(_) => Ok(()),
Err(e) => Err(e),
}
return true;
}
19 changes: 1 addition & 18 deletions src/services/response.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
use crate::users::model::{InsertableUser, User};
use crate::users::model::User;
use serde::{Deserialize, Serialize};

// #[derive(Serialize, Deserialize, Debug, Clone)]
// pub struct RegisterResponse {
// pub already_exist: bool,
// pub user: Option<InsertableUser>,
// }

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CustomResponse {
pub status: bool,
Expand All @@ -24,14 +18,3 @@ pub struct UserResponse {
pub status: bool,
pub user: Option<User>,
}
// impl RegisterResponse {
// pub fn set_register_response(
// already_exist: bool,
// user: Option<InsertableUser>,
// ) -> RegisterResponse {
// RegisterResponse {
// already_exist: already_exist,
// user: user,
// }
// }
// }
7 changes: 4 additions & 3 deletions src/services/template.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
use handlebars::Handlebars;
use serde_json::json;

pub fn alert_template() -> String {
pub fn confirmation_email(code: i32) -> String {
let mut handlebars = Handlebars::new();
handlebars
.register_template_file("alert", "templates/alert.hbs")
.register_template_file("alert", "templates/confirmation_email.hbs")
.unwrap();

let data0 = json!({
"title": "example 0",
"text": "base0"
"text": "base0",
"code": code.to_string()
});

return handlebars.render("alert", &data0).unwrap();
Expand Down
32 changes: 31 additions & 1 deletion src/users/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ pub async fn login(pool: web::Data<DbPool>, user: web::Json<Login>) -> Result<Ht
.await?
.map_err(actix_web::error::ErrorInternalServerError)?;

Ok(HttpResponse::Created().json(user))
Ok(HttpResponse::Ok().json(user))
}

#[get("/user_informations")]
Expand All @@ -47,3 +47,33 @@ pub async fn user_informations(

Ok(HttpResponse::Ok().json(user))
}

#[get("/email_confirmation")]
pub async fn email_confirmation(
_req: HttpRequest,
pool: web::Data<DbPool>,
_: AuthorizationService,
) -> Result<HttpResponse, Error> {
let token = User::get_token_from_request(&_req);
let conn = pool.get().unwrap();
let resp = User::email_confirmation(&token, &conn)
.await
.map_err(actix_web::error::ErrorInternalServerError)?;
Ok(HttpResponse::Ok().json(resp))
}

#[post("/verify_email_confirmation")]
pub async fn verify_email_confirmation(
_req: HttpRequest,
pool: web::Data<DbPool>,
_: AuthorizationService,
) -> Result<HttpResponse, Error> {
let token = User::get_token_from_request(&_req);
let resp = web::block(move || {
let conn = pool.get()?;
User::verify_email_confirmation(&token, &conn)
})
.await?
.map_err(actix_web::error::ErrorInternalServerError)?;
Ok(HttpResponse::Ok().json(resp))
}
Loading