feat: delete submission REST API guarded with bearer auth

This commit is contained in:
Aravinth Manivannan 2022-12-29 02:20:55 +05:30
parent 063b2f4b8f
commit 6c947d7b89
Signed by: realaravinth
GPG Key ID: AD9F0F08E855ED88
1 changed files with 50 additions and 0 deletions

View File

@ -33,24 +33,32 @@ pub mod routes {
pub struct Forms {
pub submit: &'static str,
pub get_all: &'static str,
pub delete: &'static str,
}
impl Forms {
pub const fn new() -> Self {
Self {
submit: "/api/v1/forms/submit",
get_all: "/api/v1/forms/list",
delete: "/api/v1/forms/delete/{id}",
}
}
pub fn get_submit(&self, host: &str, path: &str) -> String {
format!("{}?host={}&path={}", self.submit, host, path)
}
pub fn get_delete(&self, id: usize, host: &str, path: &str) -> String {
let del = self.delete.replace("{id}", &id.to_string());
format!("{}?host={}&path={}", del, host, path)
}
}
}
pub fn services(cfg: &mut web::ServiceConfig) {
cfg.service(upload);
cfg.service(list_all);
cfg.service(delete_submission);
}
#[derive(Deserialize, Serialize, Debug)]
@ -87,6 +95,7 @@ pub struct Table {
pub struct FormSubmissionResp {
pub value: Option<serde_json::Value>,
pub time: i64,
pub id: usize,
}
impl From<FormSubmission> for FormSubmissionResp {
@ -94,10 +103,27 @@ impl From<FormSubmission> for FormSubmissionResp {
Self {
value: f.value,
time: f.time.unix_timestamp(),
id: f.id as usize,
}
}
}
#[actix_web_codegen_const_routes::post(
path = "API_V1_ROUTES.forms.delete",
wrap = "HttpAuthentication::bearer(bearerauth)"
)]
#[tracing::instrument(name = "Delete form submissions", skip(ctx))]
async fn delete_submission(
ctx: AppCtx,
payload: web::Json<Table>,
id: web::Path<usize>,
) -> ServiceResult<impl Responder> {
ctx.db
.delete_submission(*id as i32, &payload.host, &payload.path)
.await?;
Ok(HttpResponse::Ok())
}
#[actix_web_codegen_const_routes::post(
path = "API_V1_ROUTES.forms.get_all",
wrap = "HttpAuthentication::bearer(bearerauth)"
@ -250,5 +276,29 @@ pub mod tests {
assert_eq!(subs.len(), 2);
assert_eq!(subs[0].value.as_ref().unwrap(), &foo_as_json_value);
assert_eq!(subs[1].value.as_ref().unwrap(), &foo_as_json_value);
let delete_route = API_V1_ROUTES.forms.get_delete(subs[1].id, host, path);
println!("del: {delete_route}");
let delete_sub = test::call_service(
&app,
test::TestRequest::post()
.set_json(&payload)
.uri(&delete_route)
.insert_header((
header::AUTHORIZATION,
format!("Bearer {}", ctx.settings.dash.api_key),
))
.to_request(),
)
.await;
assert_eq!(delete_sub.status(), StatusCode::OK);
assert_eq!(
ctx.db
.get_form_submissions(0, host, path)
.await
.unwrap()
.len(),
1
)
}
}