Skip to main content

capy_auth/
dto.rs

1use crate::Secret;
2use capy_core::{AppError, Result};
3use schemars::JsonSchema;
4use serde::{Deserialize, Serialize};
5use validator::ValidateEmail;
6
7/// Public identity; persistence/security fields never cross the API boundary.
8#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
9pub struct UserResponse {
10    /// Database identity.
11    pub id: i64,
12    /// Display name.
13    pub name: String,
14    /// Canonical account email.
15    pub email: String,
16}
17/// Registration input. Debug redacts the password.
18#[derive(Debug, Deserialize, JsonSchema)]
19pub struct RegisterRequest {
20    /// Display name, 2..=100 characters after trimming.
21    pub name: String,
22    /// Email, trimmed and lowercased without provider-specific rewriting.
23    pub email: String,
24    /// Password, 12..=128 Unicode characters, no composition rules.
25    #[schemars(with = "String")]
26    pub password: Secret,
27}
28/// Login input; failures do not distinguish unknown users from incorrect passwords.
29#[derive(Debug, Deserialize, JsonSchema)]
30pub struct LoginRequest {
31    /// Account email.
32    pub email: String,
33    /// Password.
34    #[schemars(with = "String")]
35    pub password: Secret,
36}
37/// Password reset request; the public response does not reveal account existence.
38#[derive(Debug, Deserialize, JsonSchema)]
39pub struct ForgotPasswordRequest {
40    /// Account email.
41    pub email: String,
42}
43/// Single-use reset credential and replacement password.
44#[derive(Debug, Deserialize, JsonSchema)]
45pub struct ResetPasswordRequest {
46    /// Reset secret from the application's delivery adapter.
47    #[schemars(with = "String")]
48    pub token: Secret,
49    /// Replacement password.
50    #[schemars(with = "String")]
51    pub password: Secret,
52}
53/// Constant public reset-request response.
54#[derive(Debug, Serialize, JsonSchema)]
55pub struct ResetRequestedResponse {
56    /// The same message for known and unknown accounts.
57    pub message: &'static str,
58}
59/// CSRF bootstrap response; do not log it or cache it.
60#[derive(Serialize, JsonSchema)]
61pub struct CsrfResponse {
62    /// Send in X-CSRF-Token on every state-changing request.
63    pub csrf_token: String,
64}
65impl std::fmt::Debug for CsrfResponse {
66    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67        f.write_str("CsrfResponse([REDACTED])")
68    }
69}
70/// Deterministic whole-address lowercase and whitespace trimming.
71/// This deliberately treats case variants as one account, with no alias/dot rewriting.
72pub fn normalize_email(email: &str) -> Result<String> {
73    let email = email.trim().to_lowercase();
74    if email.len() > 254 || !email.validate_email() {
75        return Err(invalid("email", "Enter a valid email address."));
76    }
77    Ok(email)
78}
79pub(crate) fn validate_password(password: &Secret, new: bool) -> Result<()> {
80    let length = password.expose().chars().count();
81    if !(if new { 12 } else { 1 }..=128).contains(&length) || password.expose().len() > 512 {
82        return Err(invalid(
83            "password",
84            if new {
85                "Use 12 to 128 characters."
86            } else {
87                "Invalid password length."
88            },
89        ));
90    }
91    Ok(())
92}
93pub(crate) fn invalid(field: &str, message: &str) -> AppError {
94    AppError::Validation([(field.into(), vec![message.into()])].into())
95}