librepages/src/api/v1/forms.rs

216 lines
6.9 KiB
Rust

/*
* Copyright (C) 2022 Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use actix_identity::Identity;
use actix_web::{web, HttpResponse, Responder};
use libforms::Table;
use serde::{Deserialize, Serialize};
use super::get_auth_middleware;
use crate::{errors::*, AppCtx};
pub mod routes {
pub struct Forms {
pub list_submissions: &'static str,
pub delete_submission: &'static str,
pub get_forms_for_host: &'static str,
}
impl Forms {
pub const fn new() -> Self {
Self {
list_submissions: "/api/v1/forms/submissions/list",
delete_submission: "/api/v1/forms/delete/{id}",
get_forms_for_host: "/api/v1/forms/list",
}
}
pub fn get_list(&self, page: usize) -> String {
format!("{}?page={}", self.list_submissions, page)
}
pub fn get_forms_for_host_route(&self, host: &str) -> String {
format!("{}?host={}", self.get_forms_for_host, host)
}
pub fn get_delete(&self, id: usize, host: &str, path: &str) -> String {
let del = self.delete_submission.replace("{id}", &id.to_string());
format!("{}?host={}&path={}", del, host, path)
}
}
}
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
pub struct Page {
page: usize,
}
#[actix_web_codegen_const_routes::post(
path = "crate::V1_API_ROUTES.forms.list_submissions",
wrap = "get_auth_middleware()"
)]
#[tracing::instrument(name = "List form submission" skip(id, ctx, payload))]
async fn list_submission(
ctx: AppCtx,
id: Identity,
page: web::Query<Page>,
payload: web::Json<Table>,
) -> ServiceResult<impl Responder> {
let owner = id.identity().unwrap();
let resp = ctx
.get_all_form_submission(&owner, page.page, &payload)
.await?;
Ok(HttpResponse::Ok().json(resp))
}
#[actix_web_codegen_const_routes::post(
path = "crate::V1_API_ROUTES.forms.delete_submission",
wrap = "get_auth_middleware()"
)]
#[tracing::instrument(name = "Delete form submission" skip(id, ctx))]
async fn delete_form_submission(
ctx: AppCtx,
id: Identity,
sub_id: web::Path<usize>,
payload: web::Json<Table>,
) -> ServiceResult<impl Responder> {
let owner = id.identity().unwrap();
ctx.delete_form_submission(&owner, *sub_id, &payload)
.await?;
Ok(HttpResponse::Ok())
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Host {
pub host: String,
}
#[actix_web_codegen_const_routes::get(
path = "crate::V1_API_ROUTES.forms.get_forms_for_host",
wrap = "get_auth_middleware()"
)]
#[tracing::instrument(name = "Get forms belonging to hostname", skip(ctx, id))]
async fn list_all_forms(
id: Identity,
ctx: AppCtx,
query: web::Query<Host>,
) -> ServiceResult<impl Responder> {
let owner = id.identity().unwrap();
let forms = ctx.get_all_forms_for_host(&owner, &query.host).await?;
Ok(HttpResponse::Ok().json(forms))
}
pub fn services(cfg: &mut web::ServiceConfig) {
cfg.service(list_submission);
cfg.service(delete_form_submission);
cfg.service(list_all_forms);
}
#[cfg(test)]
mod tests {
use actix_web::{http::StatusCode, test};
use crate::tests;
use crate::*;
use libforms::*;
#[actix_rt::test]
async fn test_api_forms() {
const NAME: &str = "testapiformuser";
const PASSWORD: &str = "longpasswordasdfa2";
const EMAIL: &str = "testapiformuser@a.com";
let (_dir, ctx) = tests::get_ctx().await;
let _ = ctx.delete_user(NAME, PASSWORD).await;
let (_, signin_resp) = ctx.register_and_signin(NAME, EMAIL, PASSWORD).await;
let page = ctx.add_test_site(NAME.into()).await;
let cookies = get_cookie!(signin_resp);
let app = get_app!(ctx).await;
let site_info = Table {
host: page.domain.clone(),
path: format!("/foo/{NAME}"),
};
if let Ok(subs) = ctx.get_all_form_submission(NAME, 0, &site_info).await {
for s in subs.iter() {
let _ = ctx.delete_form_submission(NAME, s.id, &site_info).await;
}
}
ctx.add_form_submission(NAME, &site_info, &serde_json::to_value(&site_info).unwrap())
.await
.unwrap();
// get all forms for host
let list_forms_resp = test::call_service(
&app,
test::TestRequest::get()
.uri(&V1_API_ROUTES.forms.get_forms_for_host_route(&page.domain))
.cookie(cookies.clone())
.to_request(),
)
.await;
assert_eq!(list_forms_resp.status(), StatusCode::OK);
let forms: Vec<String> = test::read_body_json(list_forms_resp).await;
assert_eq!(forms, vec![site_info.path.to_string()]);
// list subs using REST API
let list_form_submissions = test::call_service(
&app,
post_request!(&site_info, &V1_API_ROUTES.forms.get_list(0))
.cookie(cookies.clone())
.to_request(),
)
.await;
assert_eq!(list_form_submissions.status(), StatusCode::OK);
let subs: Vec<FormSubmissionResp> = test::read_body_json(list_form_submissions).await;
assert_eq!(subs.len(), 1);
assert_eq!(
subs[0].value,
Some(serde_json::to_value(&site_info).unwrap())
);
// delete form submission
let delete_form_submission_resp = test::call_service(
&app,
post_request!(
&site_info,
&V1_API_ROUTES
.forms
.get_delete(subs[0].id, &site_info.host, &site_info.path)
)
.cookie(cookies.clone())
.to_request(),
)
.await;
assert_eq!(delete_form_submission_resp.status(), StatusCode::OK);
// list subs using REST API post deletion. Len = 0
let list_form_submissions = test::call_service(
&app,
post_request!(&site_info, &V1_API_ROUTES.forms.get_list(0))
.cookie(cookies.clone())
.to_request(),
)
.await;
assert_eq!(list_form_submissions.status(), StatusCode::OK);
let subs: Vec<FormSubmissionResp> = test::read_body_json(list_form_submissions).await;
assert!(subs.is_empty());
}
}