summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2021-03-16 14:19:42 +0100
committerGitHub <noreply@github.com>2021-03-16 14:19:42 +0100
commit896ab2a9fb4a34d82c70792a1114ac1a0f4ad6c0 (patch)
tree6884cfe0cb85ffee94095d1e9db3864476c24de4 /src
parentb950072a3109d2c13881611a3950baa191caf097 (diff)
parentfc28f445d4cfbfcd597438ab2cdd137fa2021dbc (diff)
Merge pull request #13 from gico-net/feat/add-emails
Manage emails and their hashes for Gravatar
Diffstat (limited to 'src')
-rw-r--r--src/email/mod.rs2
-rw-r--r--src/email/models.rs111
-rw-r--r--src/email/routes.rs75
-rw-r--r--src/main.rs2
-rw-r--r--src/repository/models.rs7
-rw-r--r--src/repository/routes.rs1
6 files changed, 193 insertions, 5 deletions
diff --git a/src/email/mod.rs b/src/email/mod.rs
new file mode 100644
index 0000000..a0e1883
--- /dev/null
+++ b/src/email/mod.rs
@@ -0,0 +1,2 @@
+pub mod models;
+pub mod routes;
diff --git a/src/email/models.rs b/src/email/models.rs
new file mode 100644
index 0000000..ed46026
--- /dev/null
+++ b/src/email/models.rs
@@ -0,0 +1,111 @@
+use crate::db::get_client;
+use crate::errors::{AppError, AppErrorType};
+
+use deadpool_postgres::Pool;
+use serde::{Deserialize, Serialize};
+use tokio_pg_mapper::FromTokioPostgresRow;
+use tokio_pg_mapper_derive::PostgresMapper;
+
+use hex;
+use md5::{Digest, Md5};
+
+#[derive(Serialize, Deserialize, PostgresMapper)]
+#[pg_mapper(table = "email")]
+/// Emails model
+pub struct Email {
+ pub email: String,
+ pub hash_md5: String,
+}
+
+// Struct used to creare a new email
+#[derive(Serialize, Deserialize)]
+pub struct EmailData {
+ pub email: String,
+}
+
+impl Email {
+ /// Find all emails, returns email and its MD5 hash
+ pub async fn find_all(pool: Pool) -> Result<Vec<Email>, AppError> {
+ let client = get_client(pool.clone()).await.unwrap();
+ let statement = client.prepare("SELECT * FROM email").await?;
+
+ let emails = client
+ .query(&statement, &[])
+ .await?
+ .iter()
+ .map(|row| Email::from_row_ref(row).unwrap())
+ .collect::<Vec<Email>>();
+
+ Ok(emails)
+ }
+
+ /// Search an email
+ pub async fn search(
+ pool: Pool,
+ email: &String,
+ ) -> Result<Email, AppError> {
+ let client = get_client(pool.clone()).await.unwrap();
+
+ let statement =
+ client.prepare("SELECT * FROM email WHERE email=$1").await?;
+
+ let email = client
+ .query_opt(&statement, &[&email])
+ .await?
+ .map(|row| Email::from_row_ref(&row).unwrap());
+
+ match email {
+ Some(email) => Ok(email),
+ None => Err(AppError {
+ error_type: AppErrorType::NotFoundError,
+ cause: None,
+ message: Some("Email not found".to_string()),
+ }),
+ }
+ }
+
+ /// Create new email
+ pub async fn create(
+ pool: Pool,
+ data: &EmailData,
+ ) -> Result<Email, AppError> {
+ // Search an email that matches with that string, because if it's
+ // exists, the server cannot create a clone
+ match Email::search(pool.clone(), &data.email).await {
+ Ok(_) => {
+ return Err(AppError {
+ message: Some("Email already exists".to_string()),
+ cause: Some("".to_string()),
+ error_type: AppErrorType::AuthorizationError,
+ });
+ }
+ Err(_) => {}
+ };
+
+ let client = get_client(pool.clone()).await.unwrap();
+
+ let mut hasher = Md5::new();
+ hasher.update(&data.email.as_bytes());
+ let hash_final = hasher.finalize();
+
+ let digest = hex::encode(&hash_final.as_slice());
+
+ let statement = client
+ .prepare("INSERT INTO email VALUES ($1, $2) RETURNING *")
+ .await?;
+
+ let email = client
+ .query_opt(&statement, &[&data.email, &digest])
+ .await?
+ .map(|row| Email::from_row_ref(&row).unwrap());
+
+ match email {
+ Some(email) => Ok(email),
+ None => Err(AppError {
+ message: Some("Error creating a new email".to_string()),
+ cause: Some("Unknown error".to_string()),
+ error_type: AppErrorType::DbError,
+ }),
+ }
+ }
+}
diff --git a/src/email/routes.rs b/src/email/routes.rs
new file mode 100644
index 0000000..14299eb
--- /dev/null
+++ b/src/email/routes.rs
@@ -0,0 +1,75 @@
+use std::collections::HashMap;
+
+use crate::config::AppState;
+use crate::email::models::{Email, EmailData};
+use crate::errors::AppErrorResponse;
+use actix_web::{web, HttpRequest, HttpResponse, Responder};
+use slog::info;
+
+/// Endpoint used for retrieve all emails
+async fn index(state: web::Data<AppState>) -> impl Responder {
+ let result = Email::find_all(state.pool.clone()).await;
+ info!(state.log, "GET /email/");
+
+ match result {
+ Ok(emails) => HttpResponse::Ok().json(emails),
+ _ => HttpResponse::BadRequest().json(AppErrorResponse {
+ detail: "Error trying to read all emails from database"
+ .to_string(),
+ }),
+ }
+}
+
+// Endpoint used for create new email
+async fn create_email(
+ payload: web::Json<EmailData>,
+ state: web::Data<AppState>,
+) -> impl Responder {
+ info!(state.log, "POST /email/");
+ let result = Email::create(state.pool.clone(), &payload).await;
+
+ result
+ .map(|email| HttpResponse::Created().json(email))
+ .map_err(|e| e)
+}
+
+// Endpoint used for email search
+async fn search_email(
+ req: HttpRequest,
+ state: web::Data<AppState>,
+) -> impl Responder {
+ let query =
+ web::Query::<HashMap<String, String>>::from_query(req.query_string())
+ .unwrap();
+ let email = match query.get("q") {
+ Some(x) => x,
+ None => {
+ return HttpResponse::NotFound().json(AppErrorResponse {
+ detail: "No email found".to_string(),
+ });
+ }
+ };
+ let result = Email::search(state.pool.clone(), email).await;
+ info!(state.log, "GET /email/search?q={}", email);
+
+ match result {
+ Ok(email) => HttpResponse::Ok().json(email),
+ _ => HttpResponse::NotFound().json(AppErrorResponse {
+ detail: "No email found".to_string(),
+ }),
+ }
+}
+pub fn config(cfg: &mut web::ServiceConfig) {
+ cfg.service(
+ web::scope("/email")
+ .service(
+ web::resource("{_:/?}")
+ .route(web::get().to(index))
+ .route(web::post().to(create_email)),
+ )
+ .service(
+ web::resource("/search{_:/?}")
+ .route(web::get().to(search_email)),
+ ),
+ );
+}
diff --git a/src/main.rs b/src/main.rs
index 2c5532a..63f48fa 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -3,6 +3,7 @@ mod db;
mod errors;
mod helpers;
+mod email;
mod repository;
use actix_web::{middleware, App, HttpServer};
@@ -35,6 +36,7 @@ async fn main() -> std::io::Result<()> {
})
.wrap(middleware::Logger::default())
.configure(repository::routes::config)
+ .configure(email::routes::config)
})
.bind(format!("{}:{}", config.server.host, config.server.port))?
.run()
diff --git a/src/repository/models.rs b/src/repository/models.rs
index 1cbf3bb..e3d8456 100644
--- a/src/repository/models.rs
+++ b/src/repository/models.rs
@@ -180,12 +180,9 @@ impl Repository {
};
let repo = client
- .query(&statement, &[&uuid, &repo_name, &user_ip])
+ .query_opt(&statement, &[&uuid, &repo_name, &user_ip])
.await?
- .iter()
- .map(|row| Repository::from_row_ref(row).unwrap())
- .collect::<Vec<Repository>>()
- .pop();
+ .map(|row| Repository::from_row_ref(&row).unwrap());
match repo {
Some(repo) => Ok(repo),
diff --git a/src/repository/routes.rs b/src/repository/routes.rs
index a0f4db5..abf77b6 100644
--- a/src/repository/routes.rs
+++ b/src/repository/routes.rs
@@ -80,6 +80,7 @@ async fn delete_repo(
.map_err(|e| e)
}
+/// Endpoint used for create new repository
async fn create_repo(
req: HttpRequest,
payload: web::Json<RepositoryData>,