use crate::Secret;
use capy_core::{AppError, Result};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use validator::ValidateEmail;
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct UserResponse {
pub id: i64,
pub name: String,
pub email: String,
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct RegisterRequest {
pub name: String,
pub email: String,
#[schemars(with = "String")]
pub password: Secret,
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct LoginRequest {
pub email: String,
#[schemars(with = "String")]
pub password: Secret,
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ForgotPasswordRequest {
pub email: String,
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ResetPasswordRequest {
#[schemars(with = "String")]
pub token: Secret,
#[schemars(with = "String")]
pub password: Secret,
}
#[derive(Debug, Serialize, JsonSchema)]
pub struct ResetRequestedResponse {
pub message: &'static str,
}
#[derive(Serialize, JsonSchema)]
pub struct CsrfResponse {
pub csrf_token: String,
}
impl std::fmt::Debug for CsrfResponse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("CsrfResponse([REDACTED])")
}
}
pub fn normalize_email(email: &str) -> Result<String> {
let email = email.trim().to_lowercase();
if email.len() > 254 || !email.validate_email() {
return Err(invalid("email", "Enter a valid email address."));
}
Ok(email)
}
pub(crate) fn validate_password(password: &Secret, new: bool) -> Result<()> {
let length = password.expose().chars().count();
if !(if new { 12 } else { 1 }..=128).contains(&length) || password.expose().len() > 512 {
return Err(invalid(
"password",
if new {
"Use 12 to 128 characters."
} else {
"Invalid password length."
},
));
}
Ok(())
}
pub(crate) fn invalid(field: &str, message: &str) -> AppError {
AppError::Validation([(field.into(), vec![message.into()])].into())
}