1use topcoat::{
5 context::Cx,
6 router::{
7 Body, RouteFuture,
8 request::{client_ip, uri},
9 response::IntoResponse,
10 },
11 view::{BoxView, ViewExt},
12};
13
14use super::{
15 PanelUser,
16 external::leave_for,
17 hook::{AuthEvent, AuthEventKind},
18 infrastructure_failure, panel_root, resolved,
19 session::{
20 delete_session, fresh_session, record, select_tenant, stop, sweep::sweep_expired_sessions,
21 },
22 signed, unauthenticated_error,
23};
24use crate::{
25 TenantId,
26 auth::realm::{Realm, current_realm, hosted, panel_prefix},
27};
28
29pub(super) const MAX_LOGIN_BYTES: usize = 64 * 1024;
32
33pub const LOGIN_FIELD: &str = "email";
36pub const PASSWORD_FIELD: &str = "password";
38pub const NEXT_FIELD: &str = "next";
40
41pub(super) const GENERIC_ERROR: &str = "tablo-login-failed";
44
45pub const TENANT_FIELD: &str = "tenant";
47
48pub(crate) fn login_url(cx: &Cx) -> String {
50 format!("{}/login", panel_prefix(cx))
51}
52
53pub(crate) fn logout_url(cx: &Cx) -> String {
55 format!("{}/logout", panel_prefix(cx))
56}
57
58pub(super) fn login_url_with_next(cx: &Cx) -> String {
60 let mut url = login_url(cx);
61 let request = uri(cx);
62 let requested = match request.query() {
63 Some(query) => format!("{}?{query}", request.path()),
64 None => request.path().to_string(),
65 };
66 if let Some(next) = safe_next(&requested) {
67 let mut serializer = form_urlencoded::Serializer::new(String::new());
68 serializer.append_pair(NEXT_FIELD, next);
69 url.push('?');
70 url.push_str(&serializer.finish());
71 }
72 url
73}
74
75pub fn safe_next(next: &str) -> Option<&str> {
80 crate::outcome::same_origin_path(next)
81}
82
83pub(super) fn next_from_query(cx: &Cx) -> Option<String> {
85 let query = uri(cx).query()?;
86 form_urlencoded::parse(query.as_bytes())
87 .find(|(key, _)| key == NEXT_FIELD)
88 .map(|(_, value)| value.into_owned())
89 .filter(|value| safe_next(value).is_some())
90}
91
92#[derive(Debug, Clone, Copy)]
95enum LoginError {
96 Credentials,
99 Unavailable,
101}
102
103impl LoginError {
104 fn message(self) -> &'static str {
106 match self {
107 Self::Credentials => GENERIC_ERROR,
108 Self::Unavailable => "tablo-login-unavailable",
109 }
110 }
111
112 fn status(self) -> http::StatusCode {
113 match self {
114 Self::Credentials => http::StatusCode::FORBIDDEN,
115 Self::Unavailable => http::StatusCode::SERVICE_UNAVAILABLE,
116 }
117 }
118}
119
120async fn login_response(
121 cx: &Cx,
122 error: Option<LoginError>,
123 next: String,
124) -> topcoat::Result<topcoat::router::response::Response> {
125 let page = render_login_page(cx, error, next).await?;
126 page.single().await?.into_response(cx)
127}
128
129pub(super) fn login_page(cx: &Cx, _body: Body) -> RouteFuture<'_> {
131 let next = next_from_query(cx).unwrap_or_default();
132 Box::pin(login_response(cx, None, next))
133}
134
135pub(super) fn login_post(cx: &Cx, body: Body) -> RouteFuture<'_> {
137 Box::pin(async move {
138 let parts = crate::auth::input::read_form(cx, body).await?;
139 crate::csrf::verify(cx, parts.last(crate::csrf::FIELD_NAME))?;
140 let next = parts
141 .last(NEXT_FIELD)
142 .and_then(safe_next)
143 .map(str::to_string)
144 .or_else(|| next_from_query(cx))
145 .unwrap_or_default();
146 let login = parts.last(LOGIN_FIELD).map(str::trim);
147 let password = parts.last(PASSWORD_FIELD);
148 let panel = current_realm(cx).ok_or_else(topcoat::router::error::not_found)?;
149 let client = client_ip(cx);
150 let verified = match (panel.auth.authenticator(), login, password) {
151 (Some(authenticator), Some(login), Some(password))
152 if !login.is_empty() && !password.is_empty() =>
153 {
154 super::throttle::warn_unforwarded(cx);
157 if !panel
158 .auth
159 .login_throttle()
160 .attempt(cx, "sign-in", login, client)
161 .await?
162 || !panel
163 .auth
164 .account_throttle_of()
165 .attempt(cx, "account", login, None)
166 .await?
167 {
168 tracing::warn!(
169 panel = %panel.prefix,
170 client = ?client,
171 "sign-in attempt throttled"
172 );
173 return login_response(cx, Some(LoginError::Credentials), next).await;
174 }
175 match authenticator.verify(cx, login, password).await {
176 Ok(user) => user,
177 Err(error) => return failed(cx, error, next).await,
178 }
179 }
180 _ => None,
181 };
182 let admitted = verified
185 .as_deref()
186 .filter(|user| user.can_access_panel(&panel.id));
187 let Some(user) = admitted else {
188 if let Some(login) = login.filter(|login| !login.is_empty()) {
189 let kind = AuthEventKind::SignInFailed { login };
190 let event = match verified.as_deref() {
191 Some(user) => AuthEvent::own(kind, &panel.id, None, user),
192 None => AuthEvent::unsigned(kind, &panel.id, None),
193 };
194 super::hook::note(cx, panel, &event).await;
195 }
196 return login_response(cx, Some(LoginError::Credentials), next).await;
197 };
198 if let Some(login) = login {
199 panel
200 .auth
201 .login_throttle()
202 .clear(cx, "sign-in", login, client)
203 .await?;
204 panel
205 .auth
206 .account_throttle_of()
207 .clear(cx, "account", login, None)
208 .await?;
209 }
210 admit(cx, panel, user, next).await
211 })
212}
213
214pub(super) async fn admit(
218 cx: &Cx,
219 panel: &Realm,
220 user: &dyn PanelUser,
221 next: String,
222) -> topcoat::Result<topcoat::router::response::Response> {
223 if let Err(error) = sweep_expired_sessions(cx).await {
224 tracing::error!(error = %error, "expired-session sweep failed");
225 }
226 if let Err(error) = super::token::sweep_expired(cx).await {
227 tracing::error!(error = %error, "expired-token sweep failed");
228 }
229 #[cfg(feature = "two-factor")]
231 if panel.auth.two_factor_config().is_some() {
232 match super::two_factor::enrolled(cx, user).await {
233 Ok(Some(kind)) => {
234 return super::two_factor::begin_challenge(cx, user, kind, &next).await;
235 }
236 Ok(None) => {}
237 Err(error) => return failed(cx, error, next).await,
238 }
239 }
240 let recorded = match fresh_session(cx).await {
241 Ok(session) => record(cx, &session, user, panel).await,
242 Err(error) => Err(error),
243 };
244 if let Err(error) = recorded {
245 return failed(cx, error, next).await;
246 }
247 let target = if next.is_empty() {
248 panel_root(cx)
249 } else {
250 next
251 };
252 topcoat::router::error::see_other(target).into_response(cx)
253}
254
255async fn failed(
258 cx: &Cx,
259 error: topcoat::Error,
260 next: String,
261) -> topcoat::Result<topcoat::router::response::Response> {
262 let error = infrastructure_failure(error);
263 if crate::error::TabloError::is_infrastructure(&error) {
264 return login_response(cx, Some(LoginError::Unavailable), next).await;
265 }
266 Err(error)
267}
268
269pub(super) fn logout_post(cx: &Cx, body: Body) -> RouteFuture<'_> {
271 Box::pin(async move {
272 let signed = resolved(cx);
276 let external = current_realm(cx).and_then(|panel| panel.auth.external());
277 if signed.is_none() && external.is_none() {
278 return Err(unauthenticated_error(cx));
279 }
280 let parts = crate::auth::input::read_form(cx, body).await?;
281 crate::csrf::verify(cx, parts.last(crate::csrf::FIELD_NAME))?;
282 if let Some(signed) = signed {
283 crate::auth::impersonation::stop_on_sign_out(cx, signed).await?;
284 let user = signed.impersonator.as_deref().unwrap_or(&*signed.user);
286 let tenant = signed
287 .impersonator
288 .is_none()
289 .then(|| signed.acting_tenant(cx))
290 .flatten();
291 let event = AuthEvent::own(AuthEventKind::SignOut, &signed.realm.id, tenant, user);
292 super::hook::note(cx, &signed.realm, &event).await;
293 }
294 if let Some(hash) = stop(cx).await? {
295 delete_session(cx, &hash).await?;
296 }
297 if let Some(signed) = signed {
299 crate::bus::bus(cx).wake(&signed.realm.prefix, &signed.user.user_id());
300 }
301 match external {
302 Some(external) => leave_for(cx, external.logout_url(cx)).await,
303 None => topcoat::router::error::see_other(login_url(cx)).into_response(cx),
304 }
305 })
306}
307
308pub(super) fn tenant_post(cx: &Cx, body: Body) -> RouteFuture<'_> {
311 Box::pin(async move {
312 let Some(signed) = signed(cx) else {
313 return Err(unauthenticated_error(cx));
314 };
315 let parts = crate::auth::input::read_form(cx, body).await?;
316 crate::csrf::verify(cx, parts.last(crate::csrf::FIELD_NAME))?;
317 let tenant = parts
318 .last(TENANT_FIELD)
319 .and_then(|value| value.parse::<TenantId>().ok())
320 .filter(|tenant| {
321 signed
322 .user
323 .tenants()
324 .iter()
325 .any(|membership| membership.tenant == *tenant)
326 })
327 .ok_or_else(topcoat::router::error::forbidden)?;
328 select_tenant(cx, tenant).await?;
329 crate::bus::bus(cx).wake(&signed.realm.prefix, &signed.user.user_id());
332 topcoat::router::error::see_other(panel_root(cx)).into_response(cx)
333 })
334}
335
336pub(crate) fn tenant_url(cx: &Cx) -> String {
338 format!("{}/tenant", panel_prefix(cx))
339}
340
341async fn render_login_page<'a>(
344 cx: &'a Cx,
345 error: Option<LoginError>,
346 next: String,
347) -> topcoat::Result<BoxView<'a>> {
348 let csrf = crate::csrf::ensure_token(cx);
349 let action = login_url(cx);
350 let providers = super::oidc::buttons(cx, &next);
351 let hint =
352 current_realm(cx).and_then(|panel| panel.login_hint.as_ref().map(|hint| hint.localize(cx)));
353 let forgot = super::password_reset::offered(cx).then(|| super::password_reset::forgot_url(cx));
354 let sign_up = super::registration::offered(cx)
355 .then(|| super::registration::with_next(super::registration::register_url(cx), &next));
356 let notice = (error.is_none() && *topcoat::router::request::method(cx) == http::Method::GET)
359 .then(|| crate::flash::take_notification(cx))
360 .flatten();
361 let password = crate::schema::fields::password_reveal(
362 cx,
363 "password".to_string(),
364 topcoat::view::view! {
365 tablo_ui::input(
366 attrs: topcoat::view::attributes! {
367 id="password"
368 name=(PASSWORD_FIELD)
369 type="password"
370 required=""
371 autocomplete="current-password"
372 }
373 )
374 }
375 .boxed(),
376 );
377 let form = topcoat::view::view! {
378 <form method="post" action=(action) class="flex flex-col gap-5">
379 (crate::csrf::field(cx, &csrf))
380 <input type="hidden" name=(NEXT_FIELD) value=(next)>
381 if let Some(error) = error {
382 tablo_ui::alert(
383 variant: tablo_ui::AlertVariant::Destructive,
384 attrs: topcoat::view::attributes! { role="alert" },
385 tablo_ui::alert_title((crate::t!(cx, error.message())))
386 )
387 }
388 if let Some(notice) = notice {
389 tablo_ui::alert(
390 variant: match notice.status {
391 crate::NotificationStatus::Error => tablo_ui::AlertVariant::Destructive,
392 _ => tablo_ui::AlertVariant::Neutral,
393 },
394 attrs: topcoat::view::attributes! { role="status" },
395 tablo_ui::alert_title((notice.title))
396 if let Some(description) = notice.description {
397 tablo_ui::alert_description((description))
398 }
399 )
400 }
401 tablo_ui::field(
402 tablo_ui::field_label(
403 attrs: topcoat::view::attributes! { for="email" },
404 (crate::t!(cx, "tablo-login-identifier"))
405 )
406 tablo_ui::input(
407 attrs: topcoat::view::attributes! {
408 id="email"
409 name=(LOGIN_FIELD)
410 type="text"
411 required=""
412 autocomplete="username"
413 autofocus=""
414 }
415 )
416 )
417 tablo_ui::field(
418 tablo_ui::field_label(
419 attrs: topcoat::view::attributes! { for="password" },
420 (crate::t!(cx, "tablo-auth-password"))
421 )
422 (password)
423 )
424 if let Some(forgot) = forgot {
425 <a
426 (crate::navigation::runtime_link(cx, &forgot))
427 class="-mt-2 self-end text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"
428 >
429 (crate::t!(cx, "tablo-login-forgot"))
430 </a>
431 }
432 tablo_ui::button(
433 variant: tablo_ui::ButtonVariant::Primary,
434 attrs: topcoat::view::attributes! { type="submit" class="w-full" },
435 (crate::t!(cx, "tablo-login-submit"))
436 )
437 </form>
438 if let Some(providers) = providers {
439 <div class="mt-5">(providers)</div>
440 }
441 }
442 .boxed();
443 super::page::render(
444 cx,
445 super::page::AuthPage {
446 title: crate::t!(cx, "tablo-login-title"),
447 description: crate::t!(
448 cx,
449 "tablo-login-description",
450 brand = hosted(cx)?.brand_name(cx)
451 ),
452 status: error.map(|error| error.status()),
453 form,
454 switch: sign_up.map(|href| {
455 super::page::switch_link(cx, "tablo-login-no-account", &href, "tablo-login-sign-up")
456 }),
457 note: hint,
458 },
459 )
460 .await
461}