api endpoints migrated to use auth middleware

This commit is contained in:
realaravinth
2021-05-01 23:39:52 +05:30
parent 191e9658ec
commit a82d61ed27
10 changed files with 102 additions and 52 deletions

View File

@@ -24,6 +24,7 @@ use serde::{Deserialize, Serialize};
use super::mcaptcha::get_random; use super::mcaptcha::get_random;
use crate::errors::*; use crate::errors::*;
use crate::CheckLogin;
use crate::Data; use crate::Data;
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
@@ -153,8 +154,6 @@ pub struct Secret {
#[get("/api/v1/account/secret/")] #[get("/api/v1/account/secret/")]
pub async fn get_secret(id: Identity, data: web::Data<Data>) -> ServiceResult<impl Responder> { pub async fn get_secret(id: Identity, data: web::Data<Data>) -> ServiceResult<impl Responder> {
is_authenticated(&id)?;
let username = id.identity().unwrap(); let username = id.identity().unwrap();
let secret = sqlx::query_as!( let secret = sqlx::query_as!(
@@ -168,13 +167,11 @@ pub async fn get_secret(id: Identity, data: web::Data<Data>) -> ServiceResult<im
Ok(HttpResponse::Ok().json(secret)) Ok(HttpResponse::Ok().json(secret))
} }
#[post("/api/v1/account/secret/")] #[post("/api/v1/account/secret/", wrap = "CheckLogin")]
pub async fn update_user_secret( pub async fn update_user_secret(
id: Identity, id: Identity,
data: web::Data<Data>, data: web::Data<Data>,
) -> ServiceResult<impl Responder> { ) -> ServiceResult<impl Responder> {
is_authenticated(&id)?;
let username = id.identity().unwrap(); let username = id.identity().unwrap();
let mut secret; let mut secret;
@@ -211,7 +208,7 @@ pub struct Email {
pub email: String, pub email: String,
} }
#[post("/api/v1/account/email/")] #[post("/api/v1/account/email/", wrap = "CheckLogin")]
pub async fn set_email( pub async fn set_email(
id: Identity, id: Identity,
@@ -219,8 +216,6 @@ pub async fn set_email(
data: web::Data<Data>, data: web::Data<Data>,
) -> ServiceResult<impl Responder> { ) -> ServiceResult<impl Responder> {
is_authenticated(&id)?;
let username = id.identity().unwrap(); let username = id.identity().unwrap();
data.creds.email(&payload.email)?; data.creds.email(&payload.email)?;
@@ -247,25 +242,17 @@ pub async fn set_email(
Ok(HttpResponse::Ok()) Ok(HttpResponse::Ok())
} }
#[get("/logout")] #[get("/logout", wrap = "CheckLogin")]
pub async fn signout(id: Identity) -> impl Responder { pub async fn signout(id: Identity) -> impl Responder {
if let Some(_) = id.identity() { if let Some(_) = id.identity() {
id.forget(); id.forget();
} }
HttpResponse::Found() HttpResponse::Ok()
.set_header(header::LOCATION, "/login") .set_header(header::LOCATION, "/login")
.body("") .body("")
} }
/// Check if user is authenticated #[post("/api/v1/account/delete", wrap = "CheckLogin")]
// TODO use middleware
pub fn is_authenticated(id: &Identity) -> ServiceResult<()> {
// access request identity
id.identity().ok_or(ServiceError::AuthorizationRequired)?;
Ok(())
}
#[post("/api/v1/account/delete")]
pub async fn delete_account( pub async fn delete_account(
id: Identity, id: Identity,
payload: web::Json<Password>, payload: web::Json<Password>,
@@ -274,8 +261,6 @@ pub async fn delete_account(
use argon2_creds::Config; use argon2_creds::Config;
use sqlx::Error::RowNotFound; use sqlx::Error::RowNotFound;
is_authenticated(&id)?;
let username = id.identity().unwrap(); let username = id.identity().unwrap();
let rec = sqlx::query_as!( let rec = sqlx::query_as!(

View File

@@ -19,9 +19,9 @@ use actix_identity::Identity;
use actix_web::{post, web, HttpResponse, Responder}; use actix_web::{post, web, HttpResponse, Responder};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use super::is_authenticated;
use crate::api::v1::mcaptcha::mcaptcha::MCaptchaDetails; use crate::api::v1::mcaptcha::mcaptcha::MCaptchaDetails;
use crate::errors::*; use crate::errors::*;
use crate::CheckLogin;
use crate::Data; use crate::Data;
#[derive(Deserialize, Serialize)] #[derive(Deserialize, Serialize)]
@@ -30,13 +30,12 @@ pub struct UpdateDuration {
pub duration: i32, pub duration: i32,
} }
#[post("/api/v1/mcaptcha/domain/token/duration/update")] #[post("/api/v1/mcaptcha/domain/token/duration/update", wrap = "CheckLogin")]
pub async fn update_duration( pub async fn update_duration(
payload: web::Json<UpdateDuration>, payload: web::Json<UpdateDuration>,
data: web::Data<Data>, data: web::Data<Data>,
id: Identity, id: Identity,
) -> ServiceResult<impl Responder> { ) -> ServiceResult<impl Responder> {
is_authenticated(&id)?;
let username = id.identity().unwrap(); let username = id.identity().unwrap();
if payload.duration > 0 { if payload.duration > 0 {
@@ -69,13 +68,12 @@ pub struct GetDuration {
pub token: String, pub token: String,
} }
#[post("/api/v1/mcaptcha/domain/token/duration/get")] #[post("/api/v1/mcaptcha/domain/token/duration/get", wrap = "CheckLogin")]
pub async fn get_duration( pub async fn get_duration(
payload: web::Json<MCaptchaDetails>, payload: web::Json<MCaptchaDetails>,
data: web::Data<Data>, data: web::Data<Data>,
id: Identity, id: Identity,
) -> ServiceResult<impl Responder> { ) -> ServiceResult<impl Responder> {
is_authenticated(&id)?;
let username = id.identity().unwrap(); let username = id.identity().unwrap();
let duration = sqlx::query_as!( let duration = sqlx::query_as!(

View File

@@ -20,9 +20,9 @@ use actix_web::{post, web, HttpResponse, Responder};
use m_captcha::{defense::Level, DefenseBuilder}; use m_captcha::{defense::Level, DefenseBuilder};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use super::is_authenticated;
use crate::api::v1::mcaptcha::mcaptcha::MCaptchaDetails; use crate::api::v1::mcaptcha::mcaptcha::MCaptchaDetails;
use crate::errors::*; use crate::errors::*;
use crate::CheckLogin;
use crate::Data; use crate::Data;
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
@@ -34,13 +34,12 @@ pub struct AddLevels {
// TODO try for non-existent token names // TODO try for non-existent token names
#[post("/api/v1/mcaptcha/levels/add")] #[post("/api/v1/mcaptcha/levels/add", wrap = "CheckLogin")]
pub async fn add_levels( pub async fn add_levels(
payload: web::Json<AddLevels>, payload: web::Json<AddLevels>,
data: web::Data<Data>, data: web::Data<Data>,
id: Identity, id: Identity,
) -> ServiceResult<impl Responder> { ) -> ServiceResult<impl Responder> {
is_authenticated(&id)?;
let mut defense = DefenseBuilder::default(); let mut defense = DefenseBuilder::default();
let username = id.identity().unwrap(); let username = id.identity().unwrap();
@@ -75,13 +74,12 @@ pub async fn add_levels(
Ok(HttpResponse::Ok()) Ok(HttpResponse::Ok())
} }
#[post("/api/v1/mcaptcha/levels/update")] #[post("/api/v1/mcaptcha/levels/update", wrap = "CheckLogin")]
pub async fn update_levels( pub async fn update_levels(
payload: web::Json<AddLevels>, payload: web::Json<AddLevels>,
data: web::Data<Data>, data: web::Data<Data>,
id: Identity, id: Identity,
) -> ServiceResult<impl Responder> { ) -> ServiceResult<impl Responder> {
is_authenticated(&id)?;
let username = id.identity().unwrap(); let username = id.identity().unwrap();
let mut defense = DefenseBuilder::default(); let mut defense = DefenseBuilder::default();
@@ -134,13 +132,12 @@ pub async fn update_levels(
Ok(HttpResponse::Ok()) Ok(HttpResponse::Ok())
} }
#[post("/api/v1/mcaptcha/levels/delete")] #[post("/api/v1/mcaptcha/levels/delete", wrap = "CheckLogin")]
pub async fn delete_levels( pub async fn delete_levels(
payload: web::Json<AddLevels>, payload: web::Json<AddLevels>,
data: web::Data<Data>, data: web::Data<Data>,
id: Identity, id: Identity,
) -> ServiceResult<impl Responder> { ) -> ServiceResult<impl Responder> {
is_authenticated(&id)?;
let username = id.identity().unwrap(); let username = id.identity().unwrap();
for level in payload.levels.iter() { for level in payload.levels.iter() {
@@ -162,13 +159,12 @@ pub async fn delete_levels(
Ok(HttpResponse::Ok()) Ok(HttpResponse::Ok())
} }
#[post("/api/v1/mcaptcha/levels/get")] #[post("/api/v1/mcaptcha/levels/get", wrap = "CheckLogin")]
pub async fn get_levels( pub async fn get_levels(
payload: web::Json<MCaptchaDetails>, payload: web::Json<MCaptchaDetails>,
data: web::Data<Data>, data: web::Data<Data>,
id: Identity, id: Identity,
) -> ServiceResult<impl Responder> { ) -> ServiceResult<impl Responder> {
is_authenticated(&id)?;
let username = id.identity().unwrap(); let username = id.identity().unwrap();
let levels = get_levels_util(&payload.key, &username, &data).await?; let levels = get_levels_util(&payload.key, &username, &data).await?;

View File

@@ -20,8 +20,9 @@ use actix_identity::Identity;
use actix_web::{post, web, HttpResponse, Responder}; use actix_web::{post, web, HttpResponse, Responder};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use super::{get_random, is_authenticated}; use super::get_random;
use crate::errors::*; use crate::errors::*;
use crate::CheckLogin;
use crate::Data; use crate::Data;
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
@@ -35,9 +36,8 @@ pub struct MCaptchaDetails {
pub key: String, pub key: String,
} }
#[post("/api/v1/mcaptcha/add")] #[post("/api/v1/mcaptcha/add", wrap = "CheckLogin")]
pub async fn add_mcaptcha(data: web::Data<Data>, id: Identity) -> ServiceResult<impl Responder> { pub async fn add_mcaptcha(data: web::Data<Data>, id: Identity) -> ServiceResult<impl Responder> {
is_authenticated(&id)?;
let username = id.identity().unwrap(); let username = id.identity().unwrap();
let mut key; let mut key;
@@ -78,7 +78,7 @@ pub async fn add_mcaptcha(data: web::Data<Data>, id: Identity) -> ServiceResult<
Ok(HttpResponse::Ok().json(resp)) Ok(HttpResponse::Ok().json(resp))
} }
#[post("/api/v1/mcaptcha/update/key")] #[post("/api/v1/mcaptcha/update/key", wrap = "CheckLogin")]
pub async fn update_token( pub async fn update_token(
payload: web::Json<MCaptchaDetails>, payload: web::Json<MCaptchaDetails>,
data: web::Data<Data>, data: web::Data<Data>,
@@ -86,7 +86,6 @@ pub async fn update_token(
) -> ServiceResult<impl Responder> { ) -> ServiceResult<impl Responder> {
use std::borrow::Cow; use std::borrow::Cow;
is_authenticated(&id)?;
let username = id.identity().unwrap(); let username = id.identity().unwrap();
let mut key; let mut key;
@@ -132,13 +131,12 @@ async fn update_token_helper(
Ok(()) Ok(())
} }
#[post("/api/v1/mcaptcha/get")] #[post("/api/v1/mcaptcha/get", wrap = "CheckLogin")]
pub async fn get_token( pub async fn get_token(
payload: web::Json<MCaptchaDetails>, payload: web::Json<MCaptchaDetails>,
data: web::Data<Data>, data: web::Data<Data>,
id: Identity, id: Identity,
) -> ServiceResult<impl Responder> { ) -> ServiceResult<impl Responder> {
is_authenticated(&id)?;
let username = id.identity().unwrap(); let username = id.identity().unwrap();
let res = match sqlx::query_as!( let res = match sqlx::query_as!(
MCaptchaDetails, MCaptchaDetails,
@@ -161,13 +159,12 @@ pub async fn get_token(
Ok(HttpResponse::Ok().json(res)) Ok(HttpResponse::Ok().json(res))
} }
#[post("/api/v1/mcaptcha/delete")] #[post("/api/v1/mcaptcha/delete", wrap = "CheckLogin")]
pub async fn delete_mcaptcha( pub async fn delete_mcaptcha(
payload: web::Json<MCaptchaDetails>, payload: web::Json<MCaptchaDetails>,
data: web::Data<Data>, data: web::Data<Data>,
id: Identity, id: Identity,
) -> ServiceResult<impl Responder> { ) -> ServiceResult<impl Responder> {
is_authenticated(&id)?;
let username = id.identity().unwrap(); let username = id.identity().unwrap();
sqlx::query!( sqlx::query!(

View File

@@ -20,8 +20,6 @@ pub mod levels;
pub mod mcaptcha; pub mod mcaptcha;
pub mod stats; pub mod stats;
pub use super::auth::is_authenticated;
pub fn get_random(len: usize) -> String { pub fn get_random(len: usize) -> String {
use std::iter; use std::iter;

View File

@@ -23,7 +23,6 @@ pub mod verify_pow;
pub mod verify_token; pub mod verify_token;
pub use super::mcaptcha::duration::GetDurationResp; pub use super::mcaptcha::duration::GetDurationResp;
pub use super::mcaptcha::is_authenticated;
pub use super::mcaptcha::levels::I32Levels; pub use super::mcaptcha::levels::I32Levels;
// middleware protected by scope // middleware protected by scope

View File

@@ -130,7 +130,9 @@ async fn auth_works() {
.to_request(), .to_request(),
) )
.await; .await;
assert_eq!(signout_resp.status(), StatusCode::FOUND); assert_eq!(signout_resp.status(), StatusCode::OK);
let headers = signout_resp.headers();
assert_eq!(headers.get(header::LOCATION).unwrap(), "/login");
} }
#[actix_rt::test] #[actix_rt::test]

View File

@@ -16,3 +16,4 @@
*/ */
mod auth; mod auth;
mod protected;

View File

@@ -0,0 +1,75 @@
/*
* 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::StatusCode;
use actix_web::test;
use crate::data::Data;
use crate::*;
use crate::tests::*;
#[actix_rt::test]
async fn protected_routes_work() {
const NAME: &str = "testuser619";
const PASSWORD: &str = "longpassword2";
const EMAIL: &str = "testuser119@a.com2";
let _post_protected_urls = [
"/api/v1/account/secret/",
"/api/v1/account/email/",
"/api/v1/account/delete",
"/api/v1/mcaptcha/levels/add",
"/api/v1/mcaptcha/levels/update",
"/api/v1/mcaptcha/levels/delete",
"/api/v1/mcaptcha/levels/get",
"/api/v1/mcaptcha/domain/token/duration/update",
"/api/v1/mcaptcha/domain/token/duration/get",
"/api/v1/mcaptcha/add",
"/api/v1/mcaptcha/update/key",
"/api/v1/mcaptcha/get",
"/api/v1/mcaptcha/delete",
];
let get_protected_urls = ["/logout"];
{
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;
for url in get_protected_urls.iter() {
let resp =
test::call_service(&mut app, test::TestRequest::get().uri(url).to_request()).await;
assert_eq!(resp.status(), StatusCode::FOUND);
let authenticated_resp = test::call_service(
&mut app,
test::TestRequest::get()
.uri(url)
.cookie(cookies.clone())
.to_request(),
)
.await;
assert_eq!(authenticated_resp.status(), StatusCode::OK);
}
}

View File

@@ -53,9 +53,6 @@ pub enum ServiceError {
#[display(fmt = "Username not found")] #[display(fmt = "Username not found")]
UsernameNotFound, UsernameNotFound,
#[display(fmt = "Authorization required")]
AuthorizationRequired,
/// when the value passed contains profainity /// when the value passed contains profainity
#[display(fmt = "Can't allow profanity in usernames")] #[display(fmt = "Can't allow profanity in usernames")]
ProfainityError, ProfainityError,
@@ -117,7 +114,6 @@ impl ResponseError for ServiceError {
ServiceError::NotAUrl => StatusCode::BAD_REQUEST, ServiceError::NotAUrl => StatusCode::BAD_REQUEST,
ServiceError::WrongPassword => StatusCode::UNAUTHORIZED, ServiceError::WrongPassword => StatusCode::UNAUTHORIZED,
ServiceError::UsernameNotFound => StatusCode::NOT_FOUND, ServiceError::UsernameNotFound => StatusCode::NOT_FOUND,
ServiceError::AuthorizationRequired => StatusCode::UNAUTHORIZED,
ServiceError::ProfainityError => StatusCode::BAD_REQUEST, ServiceError::ProfainityError => StatusCode::BAD_REQUEST,
ServiceError::BlacklistError => StatusCode::BAD_REQUEST, ServiceError::BlacklistError => StatusCode::BAD_REQUEST,
@@ -155,18 +151,21 @@ impl From<CredsError> for ServiceError {
} }
impl From<ValidationErrors> for ServiceError { impl From<ValidationErrors> for ServiceError {
#[cfg(not(tarpaulin_include))]
fn from(_: ValidationErrors) -> ServiceError { fn from(_: ValidationErrors) -> ServiceError {
ServiceError::NotAnEmail ServiceError::NotAnEmail
} }
} }
impl From<ParseError> for ServiceError { impl From<ParseError> for ServiceError {
#[cfg(not(tarpaulin_include))]
fn from(_: ParseError) -> ServiceError { fn from(_: ParseError) -> ServiceError {
ServiceError::NotAUrl ServiceError::NotAUrl
} }
} }
impl From<CaptchaError> for ServiceError { impl From<CaptchaError> for ServiceError {
#[cfg(not(tarpaulin_include))]
fn from(e: CaptchaError) -> ServiceError { fn from(e: CaptchaError) -> ServiceError {
ServiceError::CaptchaError(e) ServiceError::CaptchaError(e)
} }