Vastly improved error handling

Vastly improved error handling in some functions.
Rest will be done later.
Code cleanup and fixed typos.
Removed actix_htttp crate as dependency
This commit is contained in:
Rohan Sircar 2020-08-19 13:42:02 +05:30
parent 8d8cdfe267
commit 5618d043bc
8 changed files with 89 additions and 1116 deletions

1
.env
View File

@ -1,2 +1,3 @@
DATABASE_URL=test.db
BIND_ADDRESS=127.0.0.1:7800
HASH_COST=8

1087
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -23,7 +23,6 @@ validator_derive = '0.10'
jsonwebtoken = '7'
actix-identity = '0.2.1'
actix-web-httpauth = '0.4.1'
actix-http = '1.0.1'
rand = '0.7.3'
nanoid = '0.3.0'
bcrypt = '0.7'
@ -41,9 +40,9 @@ actix-threadpool = '0.3.1'
version = '1.0.106'
features = ['derive']
[dependencies.yarte]
version = '0.9.0'
features = ['html-min']
# [dependencies.yarte]
# version = '0.9.0'
# features = ['html-min']
[dependencies.diesel]
version = '1.4.4'
@ -67,7 +66,7 @@ features = ['bundled']
[dependencies.chrono]
version = '0.4.11'
features = ['serde']
[build-dependencies.yarte_helpers]
version = '0.9.0'
default-features = false
features = ['config']
# [build-dependencies.yarte_helpers]
# version = '0.9.0'
# default-features = false
# features = ['config']

View File

@ -24,7 +24,7 @@ use std::convert::From;
// }
custom_error! { #[derive(new)] pub DomainError
PwdHashError {source: BcryptError} = "Failed to has password",
PwdHashError {source: BcryptError} = "Failed to hash password",
DbError {source: diesel::result::Error} = "Database error",
DbPoolError {source: r2d2::Error} = "Failed to get connection from pool",
PasswordError {cause: String} = "Failed to validate password - {cause}",
@ -53,10 +53,10 @@ impl ResponseError for DomainError {
reason: format!("{} {}", err.to_string(), source).as_str(),
})
}
DomainError::PasswordError { cause } => HttpResponse::BadRequest()
DomainError::PasswordError { cause: _ } => HttpResponse::BadRequest()
.json(ErrorModel {
error_code: 400,
reason: format!("{} {}, ", err.to_string(), cause.clone())
reason: format!("{}", err.to_string())
.as_str(),
}),
DomainError::GenericError { cause } => HttpResponse::BadRequest()

View File

@ -7,11 +7,10 @@ extern crate custom_error;
extern crate regex;
extern crate validator;
use actix_web::{middleware, web, App, HttpServer};
use actix_web::{middleware, web, App, HttpServer, cookie::SameSite};
use actix_web_httpauth::middleware::HttpAuthentication;
use actix_http::cookie::SameSite;
use actix_identity::{CookieIdentityPolicy, IdentityService};
use rand::Rng;
@ -80,7 +79,7 @@ async fn main() -> std::io::Result<()> {
CookieIdentityPolicy::new(&private_key)
.name("my-app-auth")
.secure(false)
.same_site(SameSite::Lax),
.same_site(SameSite::Lax)
))
.wrap(middleware::Logger::default())
.service(

View File

@ -4,7 +4,6 @@ use crate::schema::users;
use crate::utils::regexs;
use validator::Validate;
use validator_derive::*;
use yarte::Template;
#[derive(Debug, Clone, Queryable, Identifiable, Deserialize)]
pub struct User {
@ -28,10 +27,3 @@ pub struct UserDTO {
pub registration_date: chrono::NaiveDateTime,
}
#[derive(Template)]
#[template(path = "hello.hbs")]
pub struct CardTemplate<'a> {
pub title: &'a str,
pub body: String,
pub num: u32,
}

View File

@ -1,4 +1,4 @@
use actix_web::{web, ResponseError};
use actix_web::web;
use actix_web_httpauth::extractors::basic::BasicAuth;
use crate::actions::users;
@ -11,7 +11,7 @@ pub async fn login(
id: Identity,
credentials: BasicAuth,
config: web::Data<AppConfig>,
) -> Result<HttpResponse, impl ResponseError> {
) -> Result<HttpResponse, Error> {
let maybe_identity = id.identity();
let response = if let Some(identity) = maybe_identity {
Ok(HttpResponse::Found()
@ -20,30 +20,21 @@ pub async fn login(
.json(format!("Already logged in as {}", identity)))
} else {
let credentials2 = credentials.clone();
web::block(move || validate_basic_auth(credentials2, &config))
.await
.and_then(|valid| {
if valid {
id.remember(credentials.user_id().to_string());
Ok(HttpResponse::Found().header("location", "/").finish())
} else {
// Err(BlockingError::Error(
// errors::DomainError::new_password_error(
// "Wrong password or account does not exist"
// .to_string(),
// ),
// ))
Ok(HttpResponse::BadRequest().json(
crate::models::errors::ErrorModel::new(
20,
"Wrong password or account does not exist",
),
))
}
})
let valid =
web::block(move || validate_basic_auth(credentials2, &config))
.await?;
if valid {
id.remember(credentials.user_id().to_string());
Ok(HttpResponse::Found().header("location", "/").finish())
} else {
Ok(HttpResponse::BadRequest().json(
crate::models::errors::ErrorModel::new(
20,
"Wrong password or account does not exist",
),
))
}
};
// println!("{}", credentials.user_id());
// println!("{:?}", credentials.password());
response
}

View File

@ -1,13 +1,10 @@
use actix_web_httpauth::extractors::basic::BasicAuth;
use crate::AppConfig;
// use actix_identity::Identity;
use crate::routes::validate_basic_auth;
use actix_threadpool::BlockingError;
use actix_web::{dev::ServiceRequest, web, Error};
// use Response;
pub async fn validator(
req: ServiceRequest,
@ -16,33 +13,16 @@ pub async fn validator(
println!("{}", credentials.user_id());
println!("{:?}", credentials.password());
// verify credentials from db
let credentials2 = credentials.clone();
// let pool = req.app_data();
let config = req.app_data::<AppConfig>().expect("Error getting db");
// .get_ref()
// .clone();
// let _config = req
// .app_data::<Config>()
// .map(|data| data.get_ref().clone())
// .unwrap_or_else(Default::default);
let config = req.app_data::<AppConfig>().expect("Error getting config");
let res = web::block(move || validate_basic_auth(credentials2, &config))
.await
.and_then(|valid| {
if valid {
debug!("Success");
Ok(req)
} else {
debug!("Failure");
Err(BlockingError::Error(
crate::errors::DomainError::new_password_error(
"Wrong password or account does not exist".to_string(),
),
))
// Err(AuthenticationError::from(config))
// Ok(req)
}
});
let res2: Result<ServiceRequest, Error> = res.map_err(|e| e.into());
res2
let valid =
web::block(move || validate_basic_auth(credentials, &config)).await?;
if valid {
debug!("Success");
Ok(req)
} else {
Err(crate::errors::DomainError::new_password_error(
"Wrong password or account does not exist".to_string(),
).into())
}
}