From 4f27e1ab8d6ebc51c307192fa10d5c4e5bc3c532 Mon Sep 17 00:00:00 2001 From: realaravinth Date: Sun, 2 May 2021 12:39:37 +0530 Subject: [PATCH] using constants for routes --- src/api/v1/account.rs | 247 ++++++++++++++++++++++++++++++++ src/api/v1/auth.rs | 209 +++------------------------ src/api/v1/mcaptcha/duration.rs | 25 +++- src/api/v1/mcaptcha/levels.rs | 39 +++-- src/api/v1/mcaptcha/mcaptcha.rs | 33 ++++- src/api/v1/mod.rs | 18 ++- src/api/v1/routes.rs | 37 +++++ src/api/v1/tests/account.rs | 148 +++++++++++++++++++ src/api/v1/tests/auth.rs | 169 ++++------------------ src/tests/mod.rs | 25 ++-- 10 files changed, 587 insertions(+), 363 deletions(-) create mode 100644 src/api/v1/account.rs create mode 100644 src/api/v1/routes.rs create mode 100644 src/api/v1/tests/account.rs diff --git a/src/api/v1/account.rs b/src/api/v1/account.rs new file mode 100644 index 00000000..275ffc76 --- /dev/null +++ b/src/api/v1/account.rs @@ -0,0 +1,247 @@ +/* +* Copyright (C) 2021 Aravinth Manivannan +* +* 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 . +*/ +use std::borrow::Cow; + +use actix_identity::Identity; +use actix_web::{get, post, web, HttpResponse, Responder}; +use serde::{Deserialize, Serialize}; + +use super::auth::Password; +use super::mcaptcha::get_random; +use crate::errors::*; +use crate::CheckLogin; +use crate::Data; + +pub mod routes { + + pub struct Account { + pub delete: &'static str, + pub email_exists: &'static str, + pub update_email: &'static str, + pub get_secret: &'static str, + pub update_secret: &'static str, + pub username_exists: &'static str, + } + + impl Default for Account { + fn default() -> Self { + let get_secret = "/api/v1/account/secret/"; + let update_secret = "/api/v1/account/secret"; + let delete = "/api/v1/account/delete"; + let email_exists = "/api/v1/account/email/exists"; + let username_exists = "/api/v1/account/username/exists"; + let update_email = "/api/v1/account/email"; + Self { + get_secret, + update_secret, + username_exists, + update_email, + delete, + email_exists, + } + } + } +} + +#[post("/api/v1/account/delete", wrap = "CheckLogin")] +pub async fn delete_account( + id: Identity, + payload: web::Json, + data: web::Data, +) -> ServiceResult { + use argon2_creds::Config; + use sqlx::Error::RowNotFound; + + let username = id.identity().unwrap(); + + let rec = sqlx::query_as!( + Password, + r#"SELECT password FROM mcaptcha_users WHERE name = ($1)"#, + &username, + ) + .fetch_one(&data.db) + .await; + + id.forget(); + + match rec { + Ok(s) => { + if Config::verify(&s.password, &payload.password)? { + sqlx::query!("DELETE FROM mcaptcha_users WHERE name = ($1)", &username) + .execute(&data.db) + .await?; + Ok(HttpResponse::Ok()) + } else { + Err(ServiceError::WrongPassword) + } + } + Err(RowNotFound) => return Err(ServiceError::UsernameNotFound), + Err(_) => return Err(ServiceError::InternalServerError)?, + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct AccountCheckPayload { + pub val: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct AccountCheckResp { + pub exists: bool, +} + +#[post("/api/v1/account/username/exists")] +pub async fn username_exists( + payload: web::Json, + data: web::Data, +) -> ServiceResult { + let res = sqlx::query!( + "SELECT EXISTS (SELECT 1 from mcaptcha_users WHERE name = $1)", + &payload.val, + ) + .fetch_one(&data.db) + .await?; + + let mut resp = AccountCheckResp { exists: false }; + + if let Some(x) = res.exists { + if x { + resp.exists = true; + } + } + + Ok(HttpResponse::Ok().json(resp)) +} + +#[post("/api/v1/account/email/exists")] +pub async fn email_exists( + payload: web::Json, + data: web::Data, +) -> ServiceResult { + let res = sqlx::query!( + "SELECT EXISTS (SELECT 1 from mcaptcha_users WHERE email = $1)", + &payload.val, + ) + .fetch_one(&data.db) + .await?; + + let mut resp = AccountCheckResp { exists: false }; + + if let Some(x) = res.exists { + if x { + resp.exists = true; + } + } + + Ok(HttpResponse::Ok().json(resp)) +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Secret { + pub secret: String, +} + +#[get("/api/v1/account/secret/", wrap = "CheckLogin")] +pub async fn get_secret(id: Identity, data: web::Data) -> ServiceResult { + let username = id.identity().unwrap(); + + let secret = sqlx::query_as!( + Secret, + r#"SELECT secret FROM mcaptcha_users WHERE name = ($1)"#, + &username, + ) + .fetch_one(&data.db) + .await?; + + Ok(HttpResponse::Ok().json(secret)) +} + +#[post("/api/v1/account/secret/", wrap = "CheckLogin")] +pub async fn update_user_secret( + id: Identity, + data: web::Data, +) -> ServiceResult { + let username = id.identity().unwrap(); + + let mut secret; + + loop { + secret = get_random(32); + let res = sqlx::query!( + "UPDATE mcaptcha_users set secret = $1 + WHERE name = $2", + &secret, + &username, + ) + .execute(&data.db) + .await; + if res.is_ok() { + break; + } else { + if let Err(sqlx::Error::Database(err)) = res { + if err.code() == Some(Cow::from("23505")) + && err.message().contains("mcaptcha_users_secret_key") + { + continue; + } else { + Err(sqlx::Error::Database(err))?; + } + }; + } + } + Ok(HttpResponse::Ok()) +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Email { + pub email: String, +} + +/// update email +#[post("/api/v1/account/email/", wrap = "CheckLogin")] +pub async fn set_email( + id: Identity, + + payload: web::Json, + + data: web::Data, +) -> ServiceResult { + let username = id.identity().unwrap(); + + data.creds.email(&payload.email)?; + + let res = sqlx::query!( + "UPDATE mcaptcha_users set email = $1 + WHERE name = $2", + &payload.email, + &username, + ) + .execute(&data.db) + .await; + if !res.is_ok() { + if let Err(sqlx::Error::Database(err)) = res { + if err.code() == Some(Cow::from("23505")) + && err.message().contains("mcaptcha_users_email_key") + { + Err(ServiceError::EmailTaken)? + } else { + Err(sqlx::Error::Database(err))? + } + }; + } + Ok(HttpResponse::Ok()) +} diff --git a/src/api/v1/auth.rs b/src/api/v1/auth.rs index 817cfd91..1aa9e872 100644 --- a/src/api/v1/auth.rs +++ b/src/api/v1/auth.rs @@ -27,6 +27,27 @@ use crate::errors::*; use crate::CheckLogin; use crate::Data; +pub mod routes { + pub struct Auth { + pub login: &'static str, + pub logout: &'static str, + pub register: &'static str, + } + + impl Default for Auth { + fn default() -> Self { + let login = "/api/v1/signin"; + let logout = "/logout"; + let register = "/api/v1/signup"; + Self { + login, + logout, + register, + } + } + } +} + #[derive(Clone, Debug, Deserialize, Serialize)] pub struct Register { pub username: String, @@ -146,101 +167,6 @@ pub async fn signin( } } -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Secret { - pub secret: String, -} - -#[get("/api/v1/account/secret/")] -pub async fn get_secret(id: Identity, data: web::Data) -> ServiceResult { - let username = id.identity().unwrap(); - - let secret = sqlx::query_as!( - Secret, - r#"SELECT secret FROM mcaptcha_users WHERE name = ($1)"#, - &username, - ) - .fetch_one(&data.db) - .await?; - - Ok(HttpResponse::Ok().json(secret)) -} - -#[post("/api/v1/account/secret/", wrap = "CheckLogin")] -pub async fn update_user_secret( - id: Identity, - data: web::Data, -) -> ServiceResult { - let username = id.identity().unwrap(); - - let mut secret; - - loop { - secret = get_random(32); - let res = sqlx::query!( - "UPDATE mcaptcha_users set secret = $1 - WHERE name = $2", - &secret, - &username, - ) - .execute(&data.db) - .await; - if res.is_ok() { - break; - } else { - if let Err(sqlx::Error::Database(err)) = res { - if err.code() == Some(Cow::from("23505")) - && err.message().contains("mcaptcha_users_secret_key") - { - continue; - } else { - Err(sqlx::Error::Database(err))?; - } - }; - } - } - Ok(HttpResponse::Ok()) -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Email { - pub email: String, -} - -#[post("/api/v1/account/email/", wrap = "CheckLogin")] -pub async fn set_email( - id: Identity, - - payload: web::Json, - - data: web::Data, -) -> ServiceResult { - let username = id.identity().unwrap(); - - data.creds.email(&payload.email)?; - - let res = sqlx::query!( - "UPDATE mcaptcha_users set email = $1 - WHERE name = $2", - &payload.email, - &username, - ) - .execute(&data.db) - .await; - if !res.is_ok() { - if let Err(sqlx::Error::Database(err)) = res { - if err.code() == Some(Cow::from("23505")) - && err.message().contains("mcaptcha_users_email_key") - { - Err(ServiceError::EmailTaken)? - } else { - Err(sqlx::Error::Database(err))? - } - }; - } - Ok(HttpResponse::Ok()) -} - #[get("/logout", wrap = "CheckLogin")] pub async fn signout(id: Identity) -> impl Responder { if let Some(_) = id.identity() { @@ -250,96 +176,3 @@ pub async fn signout(id: Identity) -> impl Responder { .set_header(header::LOCATION, "/login") .body("") } - -#[post("/api/v1/account/delete", wrap = "CheckLogin")] -pub async fn delete_account( - id: Identity, - payload: web::Json, - data: web::Data, -) -> ServiceResult { - use argon2_creds::Config; - use sqlx::Error::RowNotFound; - - let username = id.identity().unwrap(); - - let rec = sqlx::query_as!( - Password, - r#"SELECT password FROM mcaptcha_users WHERE name = ($1)"#, - &username, - ) - .fetch_one(&data.db) - .await; - - id.forget(); - - match rec { - Ok(s) => { - if Config::verify(&s.password, &payload.password)? { - sqlx::query!("DELETE FROM mcaptcha_users WHERE name = ($1)", &username) - .execute(&data.db) - .await?; - Ok(HttpResponse::Ok()) - } else { - Err(ServiceError::WrongPassword) - } - } - Err(RowNotFound) => return Err(ServiceError::UsernameNotFound), - Err(_) => return Err(ServiceError::InternalServerError)?, - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct AccountCheckPayload { - pub val: String, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct AccountCheckResp { - pub exists: bool, -} - -#[post("/api/v1/account/username/exists")] -pub async fn username_exists( - payload: web::Json, - data: web::Data, -) -> ServiceResult { - let res = sqlx::query!( - "SELECT EXISTS (SELECT 1 from mcaptcha_users WHERE name = $1)", - &payload.val, - ) - .fetch_one(&data.db) - .await?; - - let mut resp = AccountCheckResp { exists: false }; - - if let Some(x) = res.exists { - if x { - resp.exists = true; - } - } - - Ok(HttpResponse::Ok().json(resp)) -} - -#[post("/api/v1/account/email/exists")] -pub async fn email_exists( - payload: web::Json, - data: web::Data, -) -> ServiceResult { - let res = sqlx::query!( - "SELECT EXISTS (SELECT 1 from mcaptcha_users WHERE email = $1)", - &payload.val, - ) - .fetch_one(&data.db) - .await?; - - let mut resp = AccountCheckResp { exists: false }; - - if let Some(x) = res.exists { - if x { - resp.exists = true; - } - } - - Ok(HttpResponse::Ok().json(resp)) -} diff --git a/src/api/v1/mcaptcha/duration.rs b/src/api/v1/mcaptcha/duration.rs index 6973f42b..b91ac45b 100644 --- a/src/api/v1/mcaptcha/duration.rs +++ b/src/api/v1/mcaptcha/duration.rs @@ -24,6 +24,22 @@ use crate::errors::*; use crate::CheckLogin; use crate::Data; +pub mod routes { + pub struct Duration { + pub update: &'static str, + pub get: &'static str, + } + + impl Default for Duration { + fn default() -> Self { + Self { + update: "/api/v1/mcaptcha/domain/token/duration/update", + get: "/api/v1/mcaptcha/domain/token/duration/get", + } + } + } +} + #[derive(Deserialize, Serialize)] pub struct UpdateDuration { pub key: String, @@ -94,6 +110,7 @@ mod tests { use actix_web::test; use super::*; + use crate::api::v1::ROUTES; use crate::tests::*; use crate::*; @@ -102,8 +119,6 @@ mod tests { const NAME: &str = "testuserduration"; const PASSWORD: &str = "longpassworddomain"; const EMAIL: &str = "testuserduration@a.com"; - const GET_URL: &str = "/api/v1/mcaptcha/domain/token/duration/get"; - const UPDATE_URL: &str = "/api/v1/mcaptcha/domain/token/duration/update"; { let data = Data::new().await; @@ -124,7 +139,7 @@ mod tests { let get_level_resp = test::call_service( &mut app, - post_request!(&token_key, GET_URL) + post_request!(&token_key, ROUTES.duration.get) .cookie(cookies.clone()) .to_request(), ) @@ -137,7 +152,7 @@ mod tests { let update_duration = test::call_service( &mut app, - post_request!(&update, UPDATE_URL) + post_request!(&update, ROUTES.duration.update) .cookie(cookies.clone()) .to_request(), ) @@ -145,7 +160,7 @@ mod tests { assert_eq!(update_duration.status(), StatusCode::OK); let get_level_resp = test::call_service( &mut app, - post_request!(&token_key, GET_URL) + post_request!(&token_key, ROUTES.duration.get) .cookie(cookies.clone()) .to_request(), ) diff --git a/src/api/v1/mcaptcha/levels.rs b/src/api/v1/mcaptcha/levels.rs index 8ccee607..21813634 100644 --- a/src/api/v1/mcaptcha/levels.rs +++ b/src/api/v1/mcaptcha/levels.rs @@ -25,6 +25,31 @@ use crate::errors::*; use crate::CheckLogin; use crate::Data; +pub mod routes { + + pub struct Levels { + pub add: &'static str, + pub update: &'static str, + pub delete: &'static str, + pub get: &'static str, + } + + impl Default for Levels { + fn default() -> Self { + let add = "/api/v1/mcaptcha/levels/add"; + let update = "/api/v1/mcaptcha/levels/update"; + let delete = "/api/v1/mcaptcha/levels/delete"; + let get = "/api/v1/mcaptcha/levels/get"; + Self { + add, + get, + update, + delete, + } + } + } +} + #[derive(Serialize, Deserialize)] pub struct AddLevels { pub levels: Vec, @@ -206,6 +231,7 @@ mod tests { use actix_web::test; use super::*; + use crate::api::v1::ROUTES; use crate::tests::*; use crate::*; @@ -214,9 +240,6 @@ mod tests { const NAME: &str = "testuserlevelroutes"; const PASSWORD: &str = "longpassworddomain"; const EMAIL: &str = "testuserlevelrouts@a.com"; - const UPDATE_URL: &str = "/api/v1/mcaptcha/levels/update"; - const DEL_URL: &str = "/api/v1/mcaptcha/levels/delete"; - const GET_URL: &str = "/api/v1/mcaptcha/levels/get"; { let data = Data::new().await; @@ -251,7 +274,7 @@ mod tests { let get_level_resp = test::call_service( &mut app, - post_request!(&key, GET_URL) + post_request!(&key, ROUTES.levels.get) .cookie(cookies.clone()) .to_request(), ) @@ -277,7 +300,7 @@ mod tests { }; let add_token_resp = test::call_service( &mut app, - post_request!(&add_level, UPDATE_URL) + post_request!(&add_level, ROUTES.levels.update) .cookie(cookies.clone()) .to_request(), ) @@ -285,7 +308,7 @@ mod tests { assert_eq!(add_token_resp.status(), StatusCode::OK); let get_level_resp = test::call_service( &mut app, - post_request!(&key, GET_URL) + post_request!(&key, ROUTES.levels.get) .cookie(cookies.clone()) .to_request(), ) @@ -310,7 +333,7 @@ mod tests { }; let add_token_resp = test::call_service( &mut app, - post_request!(&add_level, DEL_URL) + post_request!(&add_level, ROUTES.levels.delete) .cookie(cookies.clone()) .to_request(), ) @@ -318,7 +341,7 @@ mod tests { assert_eq!(add_token_resp.status(), StatusCode::OK); let get_level_resp = test::call_service( &mut app, - post_request!(&key, GET_URL) + post_request!(&key, ROUTES.levels.get) .cookie(cookies.clone()) .to_request(), ) diff --git a/src/api/v1/mcaptcha/mcaptcha.rs b/src/api/v1/mcaptcha/mcaptcha.rs index 64ee6dd2..611195bc 100644 --- a/src/api/v1/mcaptcha/mcaptcha.rs +++ b/src/api/v1/mcaptcha/mcaptcha.rs @@ -25,6 +25,26 @@ use crate::errors::*; use crate::CheckLogin; use crate::Data; +pub mod routes { + pub struct MCaptcha { + pub add: &'static str, + pub delete: &'static str, + pub get_token: &'static str, + pub update_key: &'static str, + } + + impl Default for MCaptcha { + fn default() -> Self { + Self { + add: "/api/v1/mcaptcha/add", + update_key: "/api/v1/mcaptcha/update/key", + get_token: "/api/v1/mcaptcha/get", + delete: "/api/v1/mcaptcha/delete", + } + } + } +} + #[derive(Clone, Debug, Deserialize, Serialize)] pub struct MCaptchaID { pub name: Option, @@ -36,6 +56,7 @@ pub struct MCaptchaDetails { pub key: String, } +// this should be called from within add levels #[post("/api/v1/mcaptcha/add", wrap = "CheckLogin")] pub async fn add_mcaptcha(data: web::Data, id: Identity) -> ServiceResult { let username = id.identity().unwrap(); @@ -193,6 +214,7 @@ mod tests { use actix_web::test; use super::*; + use crate::api::v1::ROUTES; use crate::tests::*; use crate::*; @@ -201,7 +223,6 @@ mod tests { const NAME: &str = "testusermcaptcha"; const PASSWORD: &str = "longpassworddomain"; const EMAIL: &str = "testusermcaptcha@a.com"; - const DEL_URL: &str = "/api/v1/mcaptcha/delete"; { let data = Data::new().await; @@ -221,7 +242,7 @@ mod tests { // 4. delete token let del_token = test::call_service( &mut app, - post_request!(&token_key, DEL_URL) + post_request!(&token_key, ROUTES.mcaptcha.delete) .cookie(cookies.clone()) .to_request(), ) @@ -234,8 +255,6 @@ mod tests { const NAME: &str = "updateusermcaptcha"; const PASSWORD: &str = "longpassworddomain"; const EMAIL: &str = "testupdateusermcaptcha@a.com"; - const UPDATE_URL: &str = "/api/v1/mcaptcha/update/key"; - const GET_URL: &str = "/api/v1/mcaptcha/get"; { let data = Data::new().await; @@ -251,7 +270,7 @@ mod tests { // 2. update token key let update_token_resp = test::call_service( &mut app, - post_request!(&token_key, UPDATE_URL) + post_request!(&token_key, ROUTES.mcaptcha.update_key) .cookie(cookies.clone()) .to_request(), ) @@ -262,7 +281,7 @@ mod tests { // get token key with updated key let get_token_resp = test::call_service( &mut app, - post_request!(&updated_token, GET_URL) + post_request!(&updated_token, ROUTES.mcaptcha.get_token) .cookie(cookies.clone()) .to_request(), ) @@ -277,7 +296,7 @@ mod tests { let get_nonexistent_token_resp = test::call_service( &mut app, - post_request!(&get_token_key, GET_URL) + post_request!(&get_token_key, ROUTES.mcaptcha.get_token) .cookie(cookies.clone()) .to_request(), ) diff --git a/src/api/v1/mod.rs b/src/api/v1/mod.rs index 658ba635..c2f6f8a7 100644 --- a/src/api/v1/mod.rs +++ b/src/api/v1/mod.rs @@ -17,10 +17,14 @@ use actix_web::web::ServiceConfig; +pub mod account; pub mod auth; pub mod mcaptcha; pub mod meta; pub mod pow; +mod routes; + +pub use routes::ROUTES; pub fn services(cfg: &mut ServiceConfig) { // meta @@ -31,12 +35,14 @@ pub fn services(cfg: &mut ServiceConfig) { cfg.service(auth::signout); cfg.service(auth::signin); cfg.service(auth::signup); - cfg.service(auth::delete_account); - cfg.service(auth::username_exists); - cfg.service(auth::email_exists); - cfg.service(auth::get_secret); - cfg.service(auth::update_user_secret); - cfg.service(auth::set_email); + + // account + cfg.service(account::delete_account); + cfg.service(account::username_exists); + cfg.service(account::email_exists); + cfg.service(account::get_secret); + cfg.service(account::update_user_secret); + cfg.service(account::set_email); // mcaptcha cfg.service(mcaptcha::mcaptcha::add_mcaptcha); diff --git a/src/api/v1/routes.rs b/src/api/v1/routes.rs new file mode 100644 index 00000000..764c8c97 --- /dev/null +++ b/src/api/v1/routes.rs @@ -0,0 +1,37 @@ +/* +* Copyright (C) 2021 Aravinth Manivannan +* +* 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 . +*/ + +use lazy_static::lazy_static; + +use super::account::routes::Account; +use super::auth::routes::Auth; +use super::mcaptcha::duration::routes::Duration; +use super::mcaptcha::levels::routes::Levels; +use super::mcaptcha::mcaptcha::routes::MCaptcha; + +lazy_static! { + pub static ref ROUTES: Routes = Routes::default(); +} + +#[derive(Default)] +pub struct Routes { + pub auth: Auth, + pub account: Account, + pub levels: Levels, + pub mcaptcha: MCaptcha, + pub duration: Duration, +} diff --git a/src/api/v1/tests/account.rs b/src/api/v1/tests/account.rs new file mode 100644 index 00000000..7ca7b968 --- /dev/null +++ b/src/api/v1/tests/account.rs @@ -0,0 +1,148 @@ +/* +* Copyright (C) 2021 Aravinth Manivannan +* +* 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 . +*/ + +use actix_web::http::{header, StatusCode}; +use actix_web::test; + +use crate::api::v1::account::*; +use crate::api::v1::auth::*; +use crate::api::v1::ROUTES; +use crate::data::Data; +use crate::errors::*; +use crate::*; + +use crate::tests::*; + +#[actix_rt::test] +async fn uname_email_exists_works() { + const NAME: &str = "testuserexists"; + const PASSWORD: &str = "longpassword2"; + const EMAIL: &str = "testuserexists@a.com2"; + + { + let data = Data::new().await; + delete_user(NAME, &data).await; + } + + let (data, _, signin_resp) = register_and_signin(NAME, EMAIL, PASSWORD).await; + let cookies = get_cookie!(signin_resp); + let mut app = get_app!(data).await; + + // chech if get user secret works + let resp = test::call_service( + &mut app, + test::TestRequest::get() + .cookie(cookies.clone()) + .uri(ROUTES.account.get_secret) + .to_request(), + ) + .await; + assert_eq!(resp.status(), StatusCode::OK); + + let mut payload = AccountCheckPayload { val: NAME.into() }; + + let user_exists_resp = test::call_service( + &mut app, + post_request!(&payload, ROUTES.account.username_exists) + .cookie(cookies.clone()) + .to_request(), + ) + .await; + assert_eq!(user_exists_resp.status(), StatusCode::OK); + let mut resp: AccountCheckResp = test::read_body_json(user_exists_resp).await; + assert!(resp.exists); + + payload.val = PASSWORD.into(); + + let user_doesnt_exist = test::call_service( + &mut app, + post_request!(&payload, ROUTES.account.username_exists) + .cookie(cookies.clone()) + .to_request(), + ) + .await; + assert_eq!(user_doesnt_exist.status(), StatusCode::OK); + resp = test::read_body_json(user_doesnt_exist).await; + assert!(!resp.exists); + + let email_doesnt_exist = test::call_service( + &mut app, + post_request!(&payload, ROUTES.account.email_exist) + .cookie(cookies.clone()) + .to_request(), + ) + .await; + assert_eq!(email_doesnt_exist.status(), StatusCode::OK); + resp = test::read_body_json(email_doesnt_exist).await; + assert!(!resp.exists); + + payload.val = EMAIL.into(); + + let email_exist = test::call_service( + &mut app, + post_request!(&payload, ROUTES.account.email_exist) + .cookie(cookies.clone()) + .to_request(), + ) + .await; + assert_eq!(email_exist.status(), StatusCode::OK); + resp = test::read_body_json(email_exist).await; + assert!(resp.exists); +} + +#[actix_rt::test] +async fn email_udpate_password_validation_del_userworks() { + const NAME: &str = "testuser2"; + const PASSWORD: &str = "longpassword2"; + const EMAIL: &str = "testuser1@a.com2"; + + { + let data = Data::new().await; + delete_user(NAME, &data).await; + } + + let (data, creds, signin_resp) = register_and_signin(NAME, EMAIL, PASSWORD).await; + let cookies = get_cookie!(signin_resp); + let mut app = get_app!(data).await; + + let email_payload = Email { + email: EMAIL.into(), + }; + let email_update_resp = test::call_service( + &mut app, + post_request!(&email_payload, ROUTES.account.update_email) + .cookie(cookies.clone()) + .to_request(), + ) + .await; + + assert_eq!(email_update_resp.status(), StatusCode::OK); + + let payload = Password { + password: creds.password, + }; + + let delete_user_resp = test::call_service( + &mut app, + post_request!(&payload, ROUTES.account.delete) + .cookie(cookies) + .to_request(), + ) + .await; + + assert_eq!(delete_user_resp.status(), StatusCode::OK); +} diff --git a/src/api/v1/tests/auth.rs b/src/api/v1/tests/auth.rs index ef83cae9..4b9cc357 100644 --- a/src/api/v1/tests/auth.rs +++ b/src/api/v1/tests/auth.rs @@ -19,6 +19,7 @@ use actix_web::http::{header, StatusCode}; use actix_web::test; use crate::api::v1::auth::*; +use crate::api::v1::ROUTES; use crate::data::Data; use crate::errors::*; use crate::*; @@ -31,9 +32,6 @@ async fn auth_works() { const NAME: &str = "testuser"; const PASSWORD: &str = "longpassword"; const EMAIL: &str = "testuser1@a.com"; - const SIGNIN: &str = "/api/v1/signin"; - const SIGNUP: &str = "/api/v1/signup"; - const GET_SECRET: &str = "/api/v1/account/secret/"; let mut app = get_app!(data).await; @@ -46,7 +44,11 @@ async fn auth_works() { confirm_password: PASSWORD.into(), email: None, }; - let resp = test::call_service(&mut app, post_request!(&msg, SIGNUP).to_request()).await; + let resp = test::call_service( + &mut app, + post_request!(&msg, ROUTES.auth.register).to_request(), + ) + .await; assert_eq!(resp.status(), StatusCode::OK); // delete user delete_user(NAME, &data).await; @@ -55,27 +57,16 @@ async fn auth_works() { let (_, _, signin_resp) = register_and_signin(NAME, EMAIL, PASSWORD).await; let cookies = get_cookie!(signin_resp); - // chech if get user secret works - let resp = test::call_service( - &mut app, - test::TestRequest::get() - .cookie(cookies.clone()) - .uri(GET_SECRET) - .to_request(), - ) - .await; - assert_eq!(resp.status(), StatusCode::OK); - - // check if update user secret works - let resp = test::call_service( - &mut app, - test::TestRequest::post() - .cookie(cookies.clone()) - .uri(GET_SECRET) - .to_request(), - ) - .await; - assert_eq!(resp.status(), StatusCode::OK); + // // check if update user secret works + // let resp = test::call_service( + // &mut app, + // test::TestRequest::post() + // .cookie(cookies.clone()) + // .uri(GET_SECRET) + // .to_request(), + // ) + // .await; + // assert_eq!(resp.status(), StatusCode::OK); // 2. check if duplicate username is allowed let msg = Register { @@ -87,7 +78,7 @@ async fn auth_works() { bad_post_req_test( NAME, PASSWORD, - SIGNUP, + ROUTES.auth.register, &msg, ServiceError::UsernameTaken, StatusCode::BAD_REQUEST, @@ -102,7 +93,7 @@ async fn auth_works() { bad_post_req_test( NAME, PASSWORD, - SIGNIN, + ROUTES.auth.login, &login, ServiceError::UsernameNotFound, StatusCode::NOT_FOUND, @@ -116,7 +107,7 @@ async fn auth_works() { bad_post_req_test( NAME, PASSWORD, - SIGNIN, + ROUTES.auth.login, &login, ServiceError::WrongPassword, StatusCode::UNAUTHORIZED, @@ -127,61 +118,26 @@ async fn auth_works() { let signout_resp = test::call_service( &mut app, test::TestRequest::get() - .uri("/logout") + .uri(ROUTES.auth.logout) .cookie(cookies) .to_request(), ) .await; assert_eq!(signout_resp.status(), StatusCode::OK); let headers = signout_resp.headers(); - assert_eq!(headers.get(header::LOCATION).unwrap(), "/login"); + assert_eq!(headers.get(header::LOCATION).unwrap(), "/login") } #[actix_rt::test] -async fn email_udpate_password_validation_del_userworks() { - const NAME: &str = "testuser2"; +async fn serverside_password_validation_works() { + const NAME: &str = "testuser542"; const PASSWORD: &str = "longpassword2"; - const EMAIL: &str = "testuser1@a.com2"; - const DEL_URL: &str = "/api/v1/account/delete"; - const EMAIL_UPDATE: &str = "/api/v1/account/email/"; - const SIGNUP: &str = "/api/v1/signup"; - { - let data = Data::new().await; - delete_user(NAME, &data).await; - } + let data = Data::new().await; + delete_user(NAME, &data).await; - let (data, creds, signin_resp) = register_and_signin(NAME, EMAIL, PASSWORD).await; - let cookies = get_cookie!(signin_resp); let mut app = get_app!(data).await; - let email_payload = Email { - email: EMAIL.into(), - }; - let email_update_resp = test::call_service( - &mut app, - post_request!(&email_payload, EMAIL_UPDATE) - .cookie(cookies.clone()) - .to_request(), - ) - .await; - - assert_eq!(email_update_resp.status(), StatusCode::OK); - - let payload = Password { - password: creds.password, - }; - - let delete_user_resp = test::call_service( - &mut app, - post_request!(&payload, DEL_URL) - .cookie(cookies) - .to_request(), - ) - .await; - - assert_eq!(delete_user_resp.status(), StatusCode::OK); - // checking to see if server-side password validation (password == password_config) // works let register_msg = Register { @@ -190,77 +146,12 @@ async fn email_udpate_password_validation_del_userworks() { confirm_password: NAME.into(), email: None, }; - let resp = - test::call_service(&mut app, post_request!(®ister_msg, SIGNUP).to_request()).await; + let resp = test::call_service( + &mut app, + post_request!(®ister_msg, ROUTES.auth.register).to_request(), + ) + .await; assert_eq!(resp.status(), StatusCode::BAD_REQUEST); let txt: ErrorToResponse = test::read_body_json(resp).await; assert_eq!(txt.error, format!("{}", ServiceError::PasswordsDontMatch)); } - -#[actix_rt::test] -async fn uname_email_exists_works() { - const NAME: &str = "testuserexists"; - const PASSWORD: &str = "longpassword2"; - const EMAIL: &str = "testuserexists@a.com2"; - const UNAME_CHECK: &str = "/api/v1/account/username/exists"; - const EMAIL_CHECK: &str = "/api/v1/account/email/exists"; - - { - let data = Data::new().await; - delete_user(NAME, &data).await; - } - - let (data, _, signin_resp) = register_and_signin(NAME, EMAIL, PASSWORD).await; - let cookies = get_cookie!(signin_resp); - let mut app = get_app!(data).await; - - let mut payload = AccountCheckPayload { val: NAME.into() }; - - let user_exists_resp = test::call_service( - &mut app, - post_request!(&payload, UNAME_CHECK) - .cookie(cookies.clone()) - .to_request(), - ) - .await; - assert_eq!(user_exists_resp.status(), StatusCode::OK); - let mut resp: AccountCheckResp = test::read_body_json(user_exists_resp).await; - assert!(resp.exists); - - payload.val = PASSWORD.into(); - - let user_doesnt_exist = test::call_service( - &mut app, - post_request!(&payload, UNAME_CHECK) - .cookie(cookies.clone()) - .to_request(), - ) - .await; - assert_eq!(user_doesnt_exist.status(), StatusCode::OK); - resp = test::read_body_json(user_doesnt_exist).await; - assert!(!resp.exists); - - let email_doesnt_exist = test::call_service( - &mut app, - post_request!(&payload, EMAIL_CHECK) - .cookie(cookies.clone()) - .to_request(), - ) - .await; - assert_eq!(email_doesnt_exist.status(), StatusCode::OK); - resp = test::read_body_json(email_doesnt_exist).await; - assert!(!resp.exists); - - payload.val = EMAIL.into(); - - let email_exist = test::call_service( - &mut app, - post_request!(&payload, EMAIL_CHECK) - .cookie(cookies.clone()) - .to_request(), - ) - .await; - assert_eq!(email_exist.status(), StatusCode::OK); - resp = test::read_body_json(email_exist).await; - assert!(resp.exists); -} diff --git a/src/tests/mod.rs b/src/tests/mod.rs index a30e4984..2a546ab8 100644 --- a/src/tests/mod.rs +++ b/src/tests/mod.rs @@ -2,6 +2,7 @@ use actix_web::test; use actix_web::{ dev::ServiceResponse, http::{header, StatusCode}, + middleware as actix_middleware, }; use m_captcha::defense::Level; use serde::Serialize; @@ -10,6 +11,7 @@ use super::*; use crate::api::v1::auth::{Login, Register}; use crate::api::v1::mcaptcha::levels::AddLevels; use crate::api::v1::mcaptcha::mcaptcha::MCaptchaDetails; +use crate::api::v1::ROUTES; use crate::data::Data; use crate::errors::*; @@ -50,6 +52,9 @@ macro_rules! get_app { test::init_service( App::new() .wrap(get_identity_service()) + .wrap(actix_middleware::NormalizePath::new( + actix_middleware::normalize::TrailingSlash::Trim, + )) .configure(crate::api::v1::pow::services) .configure(crate::api::v1::services) .data($data.clone()), @@ -79,8 +84,11 @@ pub async fn register<'a>(name: &'a str, email: &str, password: &str) { confirm_password: password.into(), email: Some(email.into()), }; - let resp = - test::call_service(&mut app, post_request!(&msg, "/api/v1/signup").to_request()).await; + let resp = test::call_service( + &mut app, + post_request!(&msg, ROUTES.auth.register).to_request(), + ) + .await; assert_eq!(resp.status(), StatusCode::OK); } @@ -96,7 +104,7 @@ pub async fn signin<'a>(name: &'a str, password: &str) -> (data::Data, Login, Se }; let signin_resp = test::call_service( &mut app, - post_request!(&creds, "/api/v1/signin").to_request(), + post_request!(&creds, ROUTES.auth.login).to_request(), ) .await; assert_eq!(signin_resp.status(), StatusCode::OK); @@ -107,10 +115,6 @@ pub async fn add_token_util( name: &str, password: &str, ) -> (data::Data, Login, ServiceResponse, MCaptchaDetails) { - // use crate::api::v1::mcaptcha::mcaptcha::MCaptchaID; - - const ADD_URL: &str = "/api/v1/mcaptcha/add"; - let (data, creds, signin_resp) = signin(name, password).await; let cookies = get_cookie!(signin_resp); let mut app = get_app!(data).await; @@ -121,7 +125,9 @@ pub async fn add_token_util( // }; let add_token_resp = test::call_service( &mut app, - post_request!(ADD_URL).cookie(cookies.clone()).to_request(), + post_request!(ROUTES.mcaptcha.add) + .cookie(cookies.clone()) + .to_request(), ) .await; // let status = add_token_resp.status(); @@ -174,7 +180,6 @@ pub async fn add_levels_util( name: &str, password: &str, ) -> (data::Data, Login, ServiceResponse, MCaptchaDetails) { - const ADD_URL: &str = "/api/v1/mcaptcha/levels/add"; let (data, creds, signin_resp, token_key) = add_token_util(name, password).await; let cookies = get_cookie!(signin_resp); let mut app = get_app!(data).await; @@ -189,7 +194,7 @@ pub async fn add_levels_util( // 1. add level let add_token_resp = test::call_service( &mut app, - post_request!(&add_level, ADD_URL) + post_request!(&add_level, ROUTES.levels.add) .cookie(cookies.clone()) .to_request(), )