1use crate::Secret;
2use capy_core::{AppError, Result};
3use schemars::JsonSchema;
4use serde::{Deserialize, Serialize};
5use validator::ValidateEmail;
6
7#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
9pub struct UserResponse {
10 pub id: i64,
12 pub name: String,
14 pub email: String,
16}
17#[derive(Debug, Deserialize, JsonSchema)]
19pub struct RegisterRequest {
20 pub name: String,
22 pub email: String,
24 #[schemars(with = "String")]
26 pub password: Secret,
27}
28#[derive(Debug, Deserialize, JsonSchema)]
30pub struct LoginRequest {
31 pub email: String,
33 #[schemars(with = "String")]
35 pub password: Secret,
36}
37#[derive(Debug, Deserialize, JsonSchema)]
39pub struct ForgotPasswordRequest {
40 pub email: String,
42}
43#[derive(Debug, Deserialize, JsonSchema)]
45pub struct ResetPasswordRequest {
46 #[schemars(with = "String")]
48 pub token: Secret,
49 #[schemars(with = "String")]
51 pub password: Secret,
52}
53#[derive(Debug, Serialize, JsonSchema)]
55pub struct ResetRequestedResponse {
56 pub message: &'static str,
58}
59#[derive(Serialize, JsonSchema)]
61pub struct CsrfResponse {
62 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}
70pub 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}