1use crate::SafeUrl;
2use serde::Serialize;
3use std::fmt;
4
5#[derive(Clone, Eq, PartialEq)]
13#[non_exhaustive]
14pub enum AuthKind {
15 SignIn,
17 Register,
19 RequestReset,
21 ResetPassword {
23 token: String,
25 },
26 ConfirmPassword,
28 VerifyEmail,
30}
31
32impl fmt::Debug for AuthKind {
33 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
34 match self {
35 Self::SignIn => formatter.write_str("SignIn"),
36 Self::Register => formatter.write_str("Register"),
37 Self::RequestReset => formatter.write_str("RequestReset"),
38 Self::ResetPassword { .. } => formatter
39 .debug_struct("ResetPassword")
40 .field("token", &"<redacted>")
41 .finish(),
42 Self::ConfirmPassword => formatter.write_str("ConfirmPassword"),
43 Self::VerifyEmail => formatter.write_str("VerifyEmail"),
44 }
45 }
46}
47
48#[derive(Clone, Copy, Debug, Eq, PartialEq)]
55#[non_exhaustive]
56pub enum AuthFormError {
57 InvalidAction,
59 MissingToken,
61}
62
63impl fmt::Display for AuthFormError {
64 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
65 formatter.write_str(match self {
66 Self::InvalidAction => "the auth action must be a rooted same-origin path",
67 Self::MissingToken => "the application must supply a non-empty form token",
68 })
69 }
70}
71impl std::error::Error for AuthFormError {}
72
73#[derive(Clone, Serialize)]
85pub struct AuthForm {
86 title: &'static str,
87 classes: &'static str,
88 box_class: &'static str,
89 action: SafeUrl,
90 fields: Vec<Field>,
91 remember_checked: bool,
92}
93
94impl AuthForm {
95 pub fn new(kind: AuthKind, action: SafeUrl, csrf: &str) -> Result<Self, AuthFormError> {
103 if !action.as_str().starts_with('/') || action.as_str().contains('#') {
104 return Err(AuthFormError::InvalidAction);
105 }
106 if csrf.trim().is_empty() {
107 return Err(AuthFormError::MissingToken);
108 }
109 let mut fields = vec![Field::hidden("_token", csrf)];
110 let (title, classes, box_class) = match kind {
111 AuthKind::SignIn => {
112 fields.extend([Field::email(), Field::password(false), Field::remember()]);
113 ("Sign in", "login-page bg-body-secondary", "login-box")
114 }
115 AuthKind::Register => {
116 fields.extend([
117 Field::visible("name", "text", "Name", "name"),
118 Field::email(),
119 Field::password(true),
120 Field::confirmation(),
121 ]);
122 ("Register", "register-page bg-body-secondary", "register-box")
123 }
124 AuthKind::RequestReset => {
125 fields.push(Field::email());
126 (
127 "Send password reset link",
128 "login-page bg-body-secondary",
129 "login-box",
130 )
131 }
132 AuthKind::ResetPassword { token } => {
133 if token.trim().is_empty() {
134 return Err(AuthFormError::MissingToken);
135 }
136 fields.extend([
137 Field::hidden("token", &token),
138 Field::email(),
139 Field::password(true),
140 Field::confirmation(),
141 ]);
142 ("Reset password", "login-page bg-body-secondary", "login-box")
143 }
144 AuthKind::ConfirmPassword => {
145 fields.push(Field::password(false));
146 (
147 "Confirm password",
148 "lockscreen bg-body-secondary",
149 "lockscreen-wrapper",
150 )
151 }
152 AuthKind::VerifyEmail => (
153 "Resend verification email",
154 "login-page bg-body-secondary",
155 "login-box",
156 ),
157 };
158 Ok(Self {
159 title,
160 classes,
161 box_class,
162 action,
163 fields,
164 remember_checked: false,
165 })
166 }
167
168 #[must_use]
177 pub fn old(mut self, name: &str, email: &str, remember: bool) -> Self {
178 for field in &mut self.fields {
179 match field.name {
180 "name" => field.value = name.into(),
181 "email" => field.value = email.into(),
182 _ => {}
183 }
184 }
185 self.remember_checked = remember;
186 self
187 }
188
189 #[must_use]
198 pub fn with_error(mut self, name: &str, message: impl Into<String>) -> Self {
199 if let Some(field) = self
200 .fields
201 .iter_mut()
202 .find(|field| field.name == name && field.kind != "hidden")
203 {
204 field.error = Some(message.into());
205 }
206 self
207 }
208}
209
210#[derive(Clone, Serialize)]
211struct Field {
212 name: &'static str,
213 kind: &'static str,
214 label: &'static str,
215 autocomplete: &'static str,
216 value: String,
217 error: Option<String>,
218}
219
220impl Field {
221 fn visible(
222 name: &'static str,
223 kind: &'static str,
224 label: &'static str,
225 autocomplete: &'static str,
226 ) -> Self {
227 Self {
228 name,
229 kind,
230 label,
231 autocomplete,
232 value: String::new(),
233 error: None,
234 }
235 }
236
237 fn hidden(name: &'static str, value: &str) -> Self {
238 Self {
239 value: value.to_owned(),
240 ..Self::visible(name, "hidden", "", "")
241 }
242 }
243
244 fn email() -> Self {
245 Self::visible("email", "email", "Email", "email")
246 }
247
248 fn password(is_new: bool) -> Self {
249 Self::visible(
250 "password",
251 "password",
252 "Password",
253 if is_new {
254 "new-password"
255 } else {
256 "current-password"
257 },
258 )
259 }
260
261 fn confirmation() -> Self {
262 Self::visible(
263 "password_confirmation",
264 "password",
265 "Confirm password",
266 "new-password",
267 )
268 }
269
270 fn remember() -> Self {
271 Self::visible("remember", "checkbox", "Remember me", "")
272 }
273}