pub mod model;
use self::model::HourEntry;
use rocket::{self, http::Status};
use rocket_contrib::json::{Json, JsonValue};
use serde::{Deserialize, Serialize};
use crate::users::auth::ApiKey;
use crate::users::model::User;
use crate::db;
#[derive(Serialize, Deserialize)]
struct RequestDetails {
email: String,
}
#[post("/all", format = "application/json", data = "<request_details>")]
fn all_entries(
request_details: Json<RequestDetails>,
key: ApiKey,
connection: db::DbConn,
) -> Result<Json<JsonValue>, Status> {
let email = request_details.email.to_string();
match User::get_by_email(email.clone(), &connection) {
Some(user) => {
// Check if the key is owned by the email given
if key.0 == email {
let entries = HourEntry::get_all(user.id, &connection);
match entries {
Ok(entries) => Ok(Json(json!(entries))),
Err(_) => Err(Status::InternalServerError),
}
} else {
// Key is not owned by the email given
Err(Status::Unauthorized)
}
}
// User not found
None => Err(Status::NotFound),
}
}
#[derive(Serialize, Deserialize)]
struct InsertDetails {
email: String,
hours: i32,
date_worked: String,
}
#[post("/insert", format = "application/json", data = "<insert_details>")]
fn insert_entry(
insert_details: Json<InsertDetails>,
key: ApiKey,
connection: db::DbConn,
) -> Result<Json<JsonValue>, Status> {
let email = insert_details.email.to_string();
let hours = insert_details.hours;
let date_worked = insert_details.date_worked.to_string();
match User::get_by_email(email.clone(), &connection) {
Some(user) => {
if key.0 == email {
let entry = HourEntry::create(user.id, hours, date_worked, &connection);
// Return entry
match entry {
Ok(entry) => Ok(Json(json!(entry))),
Err(_) => Err(Status::InternalServerError),
}
} else {
Err(Status::Unauthorized)
}
}
None => Err(Status::NotFound),
}
}
#[derive(Serialize, Deserialize)]
struct DeleteDetails {
email: String,
id: i32,
}
#[post("/delete", format = "application/json", data = "<delete_details>")]
fn delete_entry(
delete_details: Json<DeleteDetails>,
key: ApiKey,
connection: db::DbConn,
) -> Json<JsonValue> {
let email = delete_details.email.to_string();
let id = delete_details.id;
match User::get_by_email(email.clone(), &connection) {
Some(_) => {
if key.0 == email {
match HourEntry::get_by_id(id, &connection) {
Ok(_) => match HourEntry::delete(id, &connection) {
Ok(_) => Json(json!(
{
"success": false,
"message": "Entry deletion failed"
})),
Err(_) => Json(json!(
{
"success": true,
"message": "Entry deleted succesfully"
})),
},
Err(_) => Json(json!(
{
"success": false,
"message": "Entry not found"
})),
}
} else {
Json(json!(
{
"success": false,
"message": "You are not authorized to delete this entry"
}))
}
}
None => Json(json!(
{
"success": false,
"message": "User not found"
})),
}
}
pub fn mount(rocket: rocket::Rocket) -> rocket::Rocket {
rocket.mount(
"/api/hours",
routes![all_entries, insert_entry, delete_entry],
)
}