using constants for routes

This commit is contained in:
realaravinth 2021-05-02 12:39:37 +05:30
parent c7bac9e623
commit 4f27e1ab8d
No known key found for this signature in database
GPG key ID: AD9F0F08E855ED88
10 changed files with 587 additions and 363 deletions

247
src/api/v1/account.rs Normal file
View file

@ -0,0 +1,247 @@
/*
* Copyright (C) 2021 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 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<Password>,
data: web::Data<Data>,
) -> ServiceResult<impl Responder> {
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<AccountCheckPayload>,
data: web::Data<Data>,
) -> ServiceResult<impl Responder> {
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<AccountCheckPayload>,
data: web::Data<Data>,
) -> ServiceResult<impl Responder> {
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<Data>) -> ServiceResult<impl Responder> {
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<Data>,
) -> ServiceResult<impl Responder> {
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<Email>,
data: web::Data<Data>,
) -> ServiceResult<impl Responder> {
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())
}

View file

@ -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<Data>) -> ServiceResult<impl Responder> {
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<Data>,
) -> ServiceResult<impl Responder> {
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<Email>,
data: web::Data<Data>,
) -> ServiceResult<impl Responder> {
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<Password>,
data: web::Data<Data>,
) -> ServiceResult<impl Responder> {
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<AccountCheckPayload>,
data: web::Data<Data>,
) -> ServiceResult<impl Responder> {
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<AccountCheckPayload>,
data: web::Data<Data>,
) -> ServiceResult<impl Responder> {
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))
}

View file

@ -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(),
)

View file

@ -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<Level>,
@ -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(),
)

View file

@ -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<String>,
@ -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<Data>, id: Identity) -> ServiceResult<impl Responder> {
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(),
)

View file

@ -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);

37
src/api/v1/routes.rs Normal file
View file

@ -0,0 +1,37 @@
/*
* Copyright (C) 2021 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 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,
}

148
src/api/v1/tests/account.rs Normal file
View file

@ -0,0 +1,148 @@
/*
* Copyright (C) 2021 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_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);
}

View file

@ -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!(&register_msg, SIGNUP).to_request()).await;
let resp = test::call_service(
&mut app,
post_request!(&register_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);
}

View file

@ -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(),
)