1use axum::extract::FromRequestParts;
22use axum::http::request::Parts;
23use axum::response::{IntoResponse, Response};
24use axum::Json;
25use rustango::extractors::Tenant;
26use rustango::tenancy::auth::User;
27use rustango::tenancy::member_auth;
28use serde::Deserialize;
29use std::convert::Infallible;
30use std::sync::Arc;
31
32pub const LOGIN_PATH: &str = "/api/v2/auth/login";
34
35#[derive(Deserialize)]
38pub struct LoginForm {
39 pub identifier: String,
41 pub password: String,
42}
43
44pub async fn login(
50 tenant: Tenant,
51 axum::Extension(ctx): axum::Extension<Arc<rustango::extractors::TenantContext>>,
52 headers: axum::http::HeaderMap,
53 body: axum::body::Bytes,
54) -> Response {
55 let is_json = headers
56 .get(axum::http::header::CONTENT_TYPE)
57 .and_then(|v| v.to_str().ok())
58 .is_some_and(|v| v.starts_with("application/json"));
59
60 let parsed: Result<LoginForm, String> = if is_json {
61 serde_json::from_slice(&body).map_err(|e| e.to_string())
62 } else {
63 serde_urlencoded::from_bytes(&body).map_err(|e| e.to_string())
64 };
65 let Ok(form) = parsed else {
66 return crate::api::error::ApiError::bad_request(
67 "expected `identifier` and `password`, as JSON or form encoding",
68 )
69 .into_response();
70 };
71
72 login_inner(&tenant, &ctx, &form).await
73}
74
75async fn login_inner(
76 tenant: &Tenant,
77 ctx: &rustango::extractors::TenantContext,
78 form: &LoginForm,
79) -> Response {
80 let Some(user) = crate::admin::members::authenticate_member(
81 tenant.pool(),
82 &form.identifier,
83 &form.password,
84 )
85 .await
86 else {
87 return crate::api::error::ApiError::new(
91 crate::api::error::ErrorCode::Unauthenticated,
92 "invalid credentials",
93 )
94 .into_response();
95 };
96
97 let uid = user.id.get().copied().unwrap_or_default();
98 let ttl = crate::admin::members::MEMBER_SESSION_TTL;
99 let token = member_auth::encode(
100 &ctx.session_secret,
101 &member_auth::MemberSessionPayload::new(
102 uid,
103 &tenant.org.slug,
104 ttl,
105 rustango::session::PasswordFingerprint::of(&ctx.session_secret, &user.password_hash),
106 ),
107 );
108
109 Json(serde_json::json!({
110 "token": token,
111 "token_type": "Bearer",
112 "expires_in": ttl,
113 "member": {
114 "id": uid,
115 "username": user.username,
116 "email": user.email,
117 },
118 }))
119 .into_response()
120}
121
122#[derive(Debug, Clone)]
129pub struct BearerMember(pub Option<User>);
130
131impl<S: Send + Sync> FromRequestParts<S> for BearerMember {
132 type Rejection = Infallible;
133
134 async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
135 let Some(token) = bearer_token(parts) else {
136 return Ok(Self(None));
137 };
138 let Some(ctx) = parts
139 .extensions
140 .get::<Arc<rustango::extractors::TenantContext>>()
141 .cloned()
142 else {
143 return Ok(Self(None));
144 };
145 use rustango::tenancy::OrgResolver as _;
146 let org = match ctx.resolver.resolve(parts, &ctx.pools.registry_pool()).await {
147 Ok(Some(o)) => o,
148 _ => return Ok(Self(None)),
149 };
150 let Ok(payload) = member_auth::decode(&ctx.session_secret, &org.slug, &token) else {
153 return Ok(Self(None));
154 };
155 let Ok(pool) = ctx.pools.scoped_pool_dyn(&org).await else {
156 return Ok(Self(None));
157 };
158
159 use rustango::core::Column as _;
160 use rustango::sql::FetcherPool as _;
161 let user = User::objects()
162 .where_(User::id.eq(payload.uid))
163 .fetch(&pool)
164 .await
165 .unwrap_or_default()
166 .into_iter()
167 .next()
168 .filter(|u| u.active)
169 .filter(|u| match u.password_changed_at {
173 Some(changed) => payload.iat >= changed.timestamp(),
174 None => true,
175 });
176 Ok(Self(user))
177 }
178}
179
180fn bearer_token(parts: &Parts) -> Option<String> {
182 let raw = parts
183 .headers
184 .get(axum::http::header::AUTHORIZATION)?
185 .to_str()
186 .ok()?;
187 let (scheme, value) = raw.split_once(' ')?;
188 scheme
189 .eq_ignore_ascii_case("bearer")
190 .then(|| value.trim().to_owned())
191 .filter(|v| !v.is_empty())
192}
193
194#[cfg(test)]
195mod tests {
196 use super::*;
197
198 fn parts_with(header: Option<&str>) -> Parts {
199 let mut b = axum::http::Request::builder().uri("/");
200 if let Some(h) = header {
201 b = b.header(axum::http::header::AUTHORIZATION, h);
202 }
203 b.body(()).unwrap().into_parts().0
204 }
205
206 #[test]
207 fn extracts_a_bearer_token() {
208 assert_eq!(
209 bearer_token(&parts_with(Some("Bearer abc.def"))),
210 Some("abc.def".to_owned()),
211 );
212 }
213
214 #[test]
215 fn the_scheme_is_case_insensitive() {
216 for h in ["bearer abc", "BEARER abc", "BeArEr abc"] {
218 assert_eq!(bearer_token(&parts_with(Some(h))), Some("abc".to_owned()));
219 }
220 }
221
222 #[test]
223 fn another_scheme_is_not_a_bearer_token() {
224 assert_eq!(bearer_token(&parts_with(Some("Basic abc"))), None);
225 }
226
227 #[test]
228 fn a_missing_or_empty_header_yields_nothing() {
229 assert_eq!(bearer_token(&parts_with(None)), None);
230 assert_eq!(bearer_token(&parts_with(Some("Bearer"))), None);
231 assert_eq!(bearer_token(&parts_with(Some("Bearer "))), None);
232 }
233}