use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
#[cfg(feature = "utoipa")]
use utoipa::ToSchema;
#[cfg(feature = "validator")]
use validator::{Validate, ValidationErrors};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct EmailAddr(String);
#[cfg(feature = "utoipa")]
mod u {
use utoipa::{openapi::ObjectBuilder, PartialSchema, ToSchema};
use crate::v1::types::email::EmailAddr;
impl ToSchema for EmailAddr {}
impl PartialSchema for EmailAddr {
fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
ObjectBuilder::new()
.schema_type(utoipa::openapi::schema::Type::String)
.format(Some(utoipa::openapi::SchemaFormat::Custom(
"email".to_string(),
)))
.description(Some("an email address"))
.build()
.into()
}
}
}
#[cfg(feature = "validator")]
mod v {
use validator::{Validate, ValidationError, ValidationErrors};
use crate::v1::types::email::EmailAddr;
impl Validate for EmailAddr {
fn validate(&self) -> Result<(), validator::ValidationErrors> {
if self.0.contains("@") {
Ok(())
} else {
let mut v = ValidationErrors::new();
let mut err = ValidationError::new("email");
err.add_param("email".into(), &"must be an email address");
v.add("email", err);
Err(v)
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
#[cfg_attr(feature = "validator", derive(Validate))]
pub struct EmailInfo {
#[cfg_attr(feature = "validator", validate(nested))]
pub email: EmailAddr,
pub is_verified: bool,
pub is_primary: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
#[cfg_attr(feature = "validator", derive(Validate))]
pub struct EmailInfoPatch {
pub is_primary: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub enum EmailTrust {
Never,
Trusted,
Full,
}
impl EmailAddr {
pub fn into_inner(self) -> String {
self.0
}
}
impl TryFrom<String> for EmailAddr {
type Error = ValidationErrors;
fn try_from(s: String) -> Result<Self, Self::Error> {
let e = EmailAddr(s);
e.validate()?;
Ok(e)
}
}
impl AsRef<str> for EmailAddr {
fn as_ref(&self) -> &str {
&self.0
}
}