1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
use std::io::{Error as IOError, ErrorKind as IOErrorKind};

use actix_web::{
    dev::HttpResponseBuilder,
    error::ResponseError,
    http::{header, StatusCode},
    HttpResponse,
};

use argon2_creds::errors::CredsError;

use derive_more::{Display, Error};
use log::debug;
use serde::Serialize;
// use validator::ValidationErrors;

use std::convert::From;

#[derive(Debug, Display, Clone, PartialEq, Error)]
#[cfg(not(tarpaulin_include))]
pub enum ServiceError {
    #[display(fmt = "internal server error")]
    InternalServerError,
    #[display(fmt = "The value you entered for email is not an email")] //405j
    NotAnEmail,
    #[display(fmt = "File not found")]
    FileNotFound,
    #[display(fmt = "File exists")]
    FileExists,
    #[display(fmt = "Permission denied")]
    PermissionDenied,
    #[display(fmt = "Invalid credentials")]
    InvalidCredentials,
    #[display(fmt = "Authorization required")]
    AuthorizationRequired,

    /// when the value passed contains profainity
    #[display(fmt = "Can't allow profanity in usernames")]
    ProfainityError,
    /// when the value passed contains blacklisted words
    /// see [blacklist](https://github.com/shuttlecraft/The-Big-Username-Blacklist)
    #[display(fmt = "Username contains blacklisted words")]
    BlacklistError,

    /// when the value passed contains characters not present
    /// in [UsernameCaseMapped](https://tools.ietf.org/html/rfc8265#page-7)
    /// profile
    #[display(fmt = "username_case_mapped violation")]
    UsernameCaseMappedError,

    /// when the value passed contains profainity
    #[display(fmt = "Username not available")]
    UsernameTaken,
    /// when a question is already answered
    #[display(fmt = "Already answered")]
    AlreadyAnswered,
}

#[derive(Serialize)]
#[cfg(not(tarpaulin_include))]
struct ErrorToResponse {
    error: String,
}

impl ResponseError for ServiceError {
    fn error_response(&self) -> HttpResponse {
        HttpResponseBuilder::new(self.status_code())
            .set_header(header::CONTENT_TYPE, "application/json; charset=UTF-8")
            .json(ErrorToResponse {
                error: self.to_string(),
            })
    }

    fn status_code(&self) -> StatusCode {
        match *self {
            ServiceError::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR,
            ServiceError::NotAnEmail => StatusCode::BAD_REQUEST,
            ServiceError::FileNotFound => StatusCode::NOT_FOUND,
            ServiceError::FileExists => StatusCode::METHOD_NOT_ALLOWED,
            ServiceError::PermissionDenied => StatusCode::UNAUTHORIZED,
            ServiceError::InvalidCredentials => StatusCode::UNAUTHORIZED,
            ServiceError::AuthorizationRequired => StatusCode::UNAUTHORIZED,
            ServiceError::ProfainityError => StatusCode::BAD_REQUEST,
            ServiceError::BlacklistError => StatusCode::BAD_REQUEST,
            ServiceError::UsernameCaseMappedError => StatusCode::BAD_REQUEST,
            ServiceError::UsernameTaken => StatusCode::BAD_REQUEST,
            ServiceError::AlreadyAnswered => StatusCode::BAD_REQUEST,
        }
    }
}

impl From<IOError> for ServiceError {
    fn from(e: IOError) -> ServiceError {
        debug!("{:?}", &e);
        match e.kind() {
            IOErrorKind::NotFound => ServiceError::FileNotFound,
            IOErrorKind::PermissionDenied => ServiceError::PermissionDenied,
            IOErrorKind::AlreadyExists => ServiceError::FileExists,
            _ => ServiceError::InternalServerError,
        }
    }
}

impl From<CredsError> for ServiceError {
    fn from(e: CredsError) -> ServiceError {
        debug!("{:?}", &e);
        match e {
            CredsError::UsernameCaseMappedError => ServiceError::UsernameCaseMappedError,
            CredsError::ProfainityError => ServiceError::ProfainityError,
            CredsError::BlacklistError => ServiceError::BlacklistError,
            CredsError::NotAnEmail => ServiceError::NotAnEmail,
            CredsError::Argon2Error(_) => ServiceError::InternalServerError,
            _ => ServiceError::InternalServerError,
        }
    }
}

// impl From<ValidationErrors> for ServiceError {
//     fn from(_: ValidationErrors) -> ServiceError {
//         ServiceError::NotAnEmail
//     }
// }
//
impl From<sqlx::Error> for ServiceError {
    fn from(e: sqlx::Error) -> Self {
        use sqlx::error::Error;
        use std::borrow::Cow;
        debug!("{:?}", &e);
        if let Error::Database(err) = e {
            if err.code() == Some(Cow::from("23505")) {
                return ServiceError::UsernameTaken;
            }
        }

        ServiceError::InternalServerError
    }
}

pub type ServiceResult<V> = std::result::Result<V, ServiceError>;