| 1 |
1 |
|
//! OAuth client for "Log in with Makenot.work" and session user extraction.
|
|
2 |
+ |
//!
|
|
3 |
+ |
//! Perks (Fan+, creator tier, capabilities) come from MNW's `/oauth/userinfo`
|
|
4 |
+ |
//! `perks` object. We cache them in the session and refresh on three triggers:
|
|
5 |
+ |
//! (1) login, (2) session cycle, (3) on-demand via `POST /auth/refresh`. See
|
|
6 |
+ |
//! `MNW/server/docs/oauth_integration.md` for the contract.
|
| 2 |
7 |
|
|
| 3 |
8 |
|
use axum::{
|
| 4 |
9 |
|
extract::{FromRequestParts, Query, State},
|
| 5 |
10 |
|
http::{request::Parts, StatusCode},
|
| 6 |
11 |
|
response::{IntoResponse, Redirect},
|
|
12 |
+ |
Json,
|
| 7 |
13 |
|
};
|
| 8 |
14 |
|
use base64::Engine;
|
| 9 |
15 |
|
use rand::RngCore;
|
| 10 |
|
- |
use serde::Deserialize;
|
|
16 |
+ |
use serde::{Deserialize, Serialize};
|
| 11 |
17 |
|
use sha2::{Digest, Sha256};
|
| 12 |
18 |
|
use tokio::time::sleep;
|
| 13 |
19 |
|
use tower_sessions::Session;
|
| 37 |
43 |
|
|
| 38 |
44 |
|
// ── Session user ──
|
| 39 |
45 |
|
|
| 40 |
|
- |
/// Minimal user info stored in the session after OAuth login.
|
|
46 |
+ |
/// User info cached in the session after OAuth login.
|
|
47 |
+ |
///
|
|
48 |
+ |
/// `perks` reflects MNW state at the last refresh (login, session cycle, or
|
|
49 |
+ |
/// explicit `POST /auth/refresh`). Use [`UserPerks::effective_plus`] for the
|
|
50 |
+ |
/// canonical Fan+ gate.
|
| 41 |
51 |
|
#[derive(Clone, Debug)]
|
| 42 |
52 |
|
pub struct SessionUser {
|
| 43 |
53 |
|
pub user_id: uuid::Uuid,
|
| 44 |
54 |
|
pub username: String,
|
| 45 |
55 |
|
pub display_name: Option<String>,
|
|
56 |
+ |
pub perks: UserPerks,
|
|
57 |
+ |
}
|
|
58 |
+ |
|
|
59 |
+ |
/// Capability snapshot from MNW's `/oauth/userinfo` `perks` object.
|
|
60 |
+ |
///
|
|
61 |
+ |
/// Default = no perks; this is what unknown / not-yet-refreshed sessions see.
|
|
62 |
+ |
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
|
63 |
+ |
pub struct UserPerks {
|
|
64 |
+ |
#[serde(default)]
|
|
65 |
+ |
pub fan_plus: bool,
|
|
66 |
+ |
#[serde(default)]
|
|
67 |
+ |
pub is_creator: bool,
|
|
68 |
+ |
#[serde(default)]
|
|
69 |
+ |
pub creator_tier: Option<CreatorTierInfo>,
|
|
70 |
+ |
}
|
|
71 |
+ |
|
|
72 |
+ |
#[derive(Clone, Debug, Serialize, Deserialize)]
|
|
73 |
+ |
pub struct CreatorTierInfo {
|
|
74 |
+ |
pub tier: String,
|
|
75 |
+ |
pub features: Vec<String>,
|
|
76 |
+ |
}
|
|
77 |
+ |
|
|
78 |
+ |
impl UserPerks {
|
|
79 |
+ |
/// Canonical "should this user see + features" check. True for active Fan+
|
|
80 |
+ |
/// subscribers and for any creator (auto-grant: creators get + perks without
|
|
81 |
+ |
/// paying for Fan+ separately).
|
|
82 |
+ |
pub fn effective_plus(&self) -> bool {
|
|
83 |
+ |
self.fan_plus || self.is_creator
|
|
84 |
+ |
}
|
| 46 |
85 |
|
}
|
| 47 |
86 |
|
|
| 48 |
87 |
|
const SESSION_USER_ID: &str = "user_id";
|
| 49 |
88 |
|
const SESSION_USERNAME: &str = "username";
|
| 50 |
89 |
|
const SESSION_DISPLAY_NAME: &str = "display_name";
|
|
90 |
+ |
const SESSION_PERKS: &str = "perks";
|
|
91 |
+ |
const SESSION_ACCESS_TOKEN: &str = "mnw_access_token";
|
| 51 |
92 |
|
const SESSION_OAUTH_STATE: &str = "oauth_state";
|
| 52 |
93 |
|
const SESSION_PKCE_VERIFIER: &str = "pkce_verifier";
|
| 53 |
94 |
|
|
| 74 |
115 |
|
None
|
| 75 |
116 |
|
}
|
| 76 |
117 |
|
};
|
|
118 |
+ |
// Perks default to empty — sessions predating the perks change still load.
|
|
119 |
+ |
let perks: UserPerks = session
|
|
120 |
+ |
.get(SESSION_PERKS)
|
|
121 |
+ |
.await
|
|
122 |
+ |
.unwrap_or_default()
|
|
123 |
+ |
.unwrap_or_default();
|
| 77 |
124 |
|
Some(Self {
|
| 78 |
125 |
|
user_id,
|
| 79 |
126 |
|
username,
|
| 80 |
127 |
|
display_name,
|
|
128 |
+ |
perks,
|
| 81 |
129 |
|
})
|
| 82 |
130 |
|
}
|
| 83 |
131 |
|
|
| 91 |
139 |
|
if let Err(e) = session.insert(SESSION_DISPLAY_NAME, &self.display_name).await {
|
| 92 |
140 |
|
tracing::error!(error = %e, "failed to save display_name to session");
|
| 93 |
141 |
|
}
|
|
142 |
+ |
if let Err(e) = session.insert(SESSION_PERKS, &self.perks).await {
|
|
143 |
+ |
tracing::error!(error = %e, "failed to save perks to session");
|
|
144 |
+ |
}
|
| 94 |
145 |
|
}
|
| 95 |
146 |
|
}
|
| 96 |
147 |
|
|
| 157 |
208 |
|
username: String,
|
| 158 |
209 |
|
display_name: Option<String>,
|
| 159 |
210 |
|
avatar_url: Option<String>,
|
|
211 |
+ |
#[serde(default)]
|
|
212 |
+ |
perks: UserPerks,
|
|
213 |
+ |
}
|
|
214 |
+ |
|
|
215 |
+ |
#[derive(Debug)]
|
|
216 |
+ |
pub enum UserinfoError {
|
|
217 |
+ |
Unauthorized,
|
|
218 |
+ |
Transport,
|
|
219 |
+ |
BadResponse,
|
|
220 |
+ |
}
|
|
221 |
+ |
|
|
222 |
+ |
/// Single-attempt userinfo fetch against MNW. Callers decide retry policy.
|
|
223 |
+ |
///
|
|
224 |
+ |
/// `Unauthorized` means the bearer token is invalid or the user is gone.
|
|
225 |
+ |
/// `Transport` covers network and 5xx. `BadResponse` covers other 4xx and parse
|
|
226 |
+ |
/// errors. The login callback retries on `Transport`; `refresh_session` does
|
|
227 |
+ |
/// not — the client can retry.
|
|
228 |
+ |
async fn fetch_userinfo(
|
|
229 |
+ |
http: &reqwest::Client,
|
|
230 |
+ |
base_url: &str,
|
|
231 |
+ |
access_token: &str,
|
|
232 |
+ |
) -> Result<UserinfoResponse, UserinfoError> {
|
|
233 |
+ |
let url = format!("{}/oauth/userinfo", base_url);
|
|
234 |
+ |
let res = http
|
|
235 |
+ |
.get(&url)
|
|
236 |
+ |
.bearer_auth(access_token)
|
|
237 |
+ |
.send()
|
|
238 |
+ |
.await
|
|
239 |
+ |
.map_err(|e| {
|
|
240 |
+ |
tracing::warn!(error = %e, "userinfo transport error");
|
|
241 |
+ |
UserinfoError::Transport
|
|
242 |
+ |
})?;
|
|
243 |
+ |
|
|
244 |
+ |
let status = res.status();
|
|
245 |
+ |
if status == reqwest::StatusCode::UNAUTHORIZED {
|
|
246 |
+ |
return Err(UserinfoError::Unauthorized);
|
|
247 |
+ |
}
|
|
248 |
+ |
if status.is_server_error() {
|
|
249 |
+ |
return Err(UserinfoError::Transport);
|
|
250 |
+ |
}
|
|
251 |
+ |
if !status.is_success() {
|
|
252 |
+ |
let body = res.text().await.unwrap_or_default();
|
|
253 |
+ |
tracing::warn!(%status, %body, "userinfo non-success");
|
|
254 |
+ |
return Err(UserinfoError::BadResponse);
|
|
255 |
+ |
}
|
|
256 |
+ |
|
|
257 |
+ |
res.json::<UserinfoResponse>().await.map_err(|e| {
|
|
258 |
+ |
tracing::warn!(error = %e, "userinfo parse failed");
|
|
259 |
+ |
UserinfoError::BadResponse
|
|
260 |
+ |
})
|
|
261 |
+ |
}
|
|
262 |
+ |
|
|
263 |
+ |
/// Refresh the cached perks for the current session by re-hitting MNW.
|
|
264 |
+ |
///
|
|
265 |
+ |
/// Caller must have a logged-in session (access token stored at login). On
|
|
266 |
+ |
/// `Unauthorized` the session is flushed — the access token is gone for good
|
|
267 |
+ |
/// and the user needs to log in again. Other errors leave the session intact.
|
|
268 |
+ |
pub async fn refresh_session(
|
|
269 |
+ |
state: &AppState,
|
|
270 |
+ |
session: &Session,
|
|
271 |
+ |
) -> Result<UserPerks, UserinfoError> {
|
|
272 |
+ |
let token: String = session
|
|
273 |
+ |
.get(SESSION_ACCESS_TOKEN)
|
|
274 |
+ |
.await
|
|
275 |
+ |
.unwrap_or(None)
|
|
276 |
+ |
.ok_or(UserinfoError::Unauthorized)?;
|
|
277 |
+ |
|
|
278 |
+ |
match fetch_userinfo(&state.http, &state.config.mnw_base_url, &token).await {
|
|
279 |
+ |
Ok(info) => {
|
|
280 |
+ |
if let Err(e) = session.insert(SESSION_PERKS, &info.perks).await {
|
|
281 |
+ |
tracing::error!(error = %e, "failed to save refreshed perks");
|
|
282 |
+ |
}
|
|
283 |
+ |
// Username/display can drift on MNW too — sync them while we're here.
|
|
284 |
+ |
if let Err(e) = session.insert(SESSION_USERNAME, &info.username).await {
|
|
285 |
+ |
tracing::error!(error = %e, "failed to save refreshed username");
|
|
286 |
+ |
}
|
|
287 |
+ |
if let Err(e) = session.insert(SESSION_DISPLAY_NAME, &info.display_name).await {
|
|
288 |
+ |
tracing::error!(error = %e, "failed to save refreshed display_name");
|
|
289 |
+ |
}
|
|
290 |
+ |
// Mirror perks into users table so post rendering sees the change
|
|
291 |
+ |
// without consulting MNW per-post. Best-effort: rendering tolerates
|
|
292 |
+ |
// a stale row, so DB errors here are logged but non-fatal.
|
|
293 |
+ |
if let Err(e) = sqlx::query(
|
|
294 |
+ |
"UPDATE users SET is_fan_plus = $2, is_creator = $3 WHERE mnw_account_id = $1",
|
|
295 |
+ |
)
|
|
296 |
+ |
.bind(info.user_id)
|
|
297 |
+ |
.bind(info.perks.fan_plus)
|
|
298 |
+ |
.bind(info.perks.is_creator)
|
|
299 |
+ |
.execute(&state.db)
|
|
300 |
+ |
.await
|
|
301 |
+ |
{
|
|
302 |
+ |
tracing::warn!(error = %e, "failed to mirror refreshed perks to users table");
|
|
303 |
+ |
}
|
|
304 |
+ |
let _ = info.avatar_url; // not stored in session yet
|
|
305 |
+ |
Ok(info.perks)
|
|
306 |
+ |
}
|
|
307 |
+ |
Err(UserinfoError::Unauthorized) => {
|
|
308 |
+ |
// Token revoked, expired, or user deleted — drop the session.
|
|
309 |
+ |
if let Err(e) = session.flush().await {
|
|
310 |
+ |
tracing::warn!(error = %e, "failed to flush session after auth failure");
|
|
311 |
+ |
}
|
|
312 |
+ |
Err(UserinfoError::Unauthorized)
|
|
313 |
+ |
}
|
|
314 |
+ |
Err(e) => Err(e),
|
|
315 |
+ |
}
|
| 160 |
316 |
|
}
|
| 161 |
317 |
|
|
| 162 |
318 |
|
// ── Handlers ──
|
| 288 |
444 |
|
}
|
| 289 |
445 |
|
};
|
| 290 |
446 |
|
|
| 291 |
|
- |
// Fetch userinfo (retry up to 2 attempts on network/5xx errors)
|
| 292 |
|
- |
let userinfo_url = format!("{}/oauth/userinfo", state.config.mnw_base_url);
|
| 293 |
|
- |
tracing::info!(%userinfo_url, "fetching userinfo");
|
| 294 |
|
- |
let mut userinfo_res = None;
|
|
447 |
+ |
// Fetch userinfo (retry up to 2 attempts on transport / 5xx errors).
|
|
448 |
+ |
tracing::info!(base_url = %state.config.mnw_base_url, "fetching userinfo");
|
|
449 |
+ |
let mut info: Option<UserinfoResponse> = None;
|
| 295 |
450 |
|
for attempt in 0..=backoffs.len() {
|
| 296 |
|
- |
let res = state
|
| 297 |
|
- |
.http
|
| 298 |
|
- |
.get(&userinfo_url)
|
| 299 |
|
- |
.bearer_auth(&token.access_token)
|
| 300 |
|
- |
.send()
|
| 301 |
|
- |
.await;
|
| 302 |
|
- |
|
| 303 |
|
- |
match res {
|
| 304 |
|
- |
Ok(r) if r.status().is_server_error() => {
|
| 305 |
|
- |
let status = r.status();
|
| 306 |
|
- |
if attempt < backoffs.len() {
|
| 307 |
|
- |
tracing::warn!(%status, attempt, "userinfo got 5xx, retrying");
|
| 308 |
|
- |
sleep(backoffs[attempt]).await;
|
| 309 |
|
- |
continue;
|
| 310 |
|
- |
}
|
| 311 |
|
- |
let body = r.text().await.unwrap_or_default();
|
| 312 |
|
- |
tracing::error!(%status, %body, "userinfo fetch failed after retries");
|
| 313 |
|
- |
return Redirect::to("/?error=userinfo_fetch_failed");
|
| 314 |
|
- |
}
|
| 315 |
|
- |
Ok(r) if !r.status().is_success() => {
|
| 316 |
|
- |
let status = r.status();
|
| 317 |
|
- |
let body = r.text().await.unwrap_or_default();
|
| 318 |
|
- |
tracing::error!(%status, %body, "userinfo fetch failed");
|
| 319 |
|
- |
return Redirect::to("/?error=userinfo_fetch_failed");
|
| 320 |
|
- |
}
|
| 321 |
|
- |
Ok(r) => {
|
| 322 |
|
- |
userinfo_res = Some(r);
|
|
451 |
+ |
match fetch_userinfo(&state.http, &state.config.mnw_base_url, &token.access_token).await {
|
|
452 |
+ |
Ok(i) => {
|
|
453 |
+ |
info = Some(i);
|
| 323 |
454 |
|
break;
|
| 324 |
455 |
|
}
|
| 325 |
|
- |
Err(e) => {
|
| 326 |
|
- |
if attempt < backoffs.len() {
|
| 327 |
|
- |
tracing::warn!(error = %e, attempt, "userinfo request failed, retrying");
|
| 328 |
|
- |
sleep(backoffs[attempt]).await;
|
| 329 |
|
- |
continue;
|
| 330 |
|
- |
}
|
| 331 |
|
- |
tracing::error!(error = %e, "userinfo request failed after retries");
|
| 332 |
|
- |
return Redirect::to("/?error=userinfo_request_failed");
|
|
456 |
+ |
Err(UserinfoError::Transport) if attempt < backoffs.len() => {
|
|
457 |
+ |
tracing::warn!(attempt, "userinfo transport error, retrying");
|
|
458 |
+ |
sleep(backoffs[attempt]).await;
|
|
459 |
+ |
continue;
|
|
460 |
+ |
}
|
|
461 |
+ |
Err(UserinfoError::Transport) => {
|
|
462 |
+ |
tracing::error!("userinfo transport failed after retries");
|
|
463 |
+ |
return Redirect::to("/?error=userinfo_fetch_failed");
|
|
464 |
+ |
}
|
|
465 |
+ |
Err(UserinfoError::Unauthorized) => {
|
|
466 |
+ |
tracing::error!("userinfo unauthorized — token rejected");
|
|
467 |
+ |
return Redirect::to("/?error=userinfo_fetch_failed");
|
|
468 |
+ |
}
|
|
469 |
+ |
Err(UserinfoError::BadResponse) => {
|
|
470 |
+ |
tracing::error!("userinfo bad response");
|
|
471 |
+ |
return Redirect::to("/?error=userinfo_parse_failed");
|
| 333 |
472 |
|
}
|
| 334 |
473 |
|
}
|
| 335 |
474 |
|
}
|
| 336 |
|
- |
// Safety: loop always either sets userinfo_res or returns early
|
| 337 |
|
- |
let userinfo_res = userinfo_res.unwrap();
|
| 338 |
|
- |
|
| 339 |
|
- |
let info: UserinfoResponse = match userinfo_res.json().await {
|
| 340 |
|
- |
Ok(i) => i,
|
| 341 |
|
- |
Err(e) => {
|
| 342 |
|
- |
tracing::error!(error = %e, "userinfo parse failed");
|
| 343 |
|
- |
return Redirect::to("/?error=userinfo_parse_failed");
|
| 344 |
|
- |
}
|
| 345 |
|
- |
};
|
|
475 |
+ |
let info = info.expect("userinfo loop always sets value or returns");
|
| 346 |
476 |
|
|
| 347 |
477 |
|
tracing::info!(user_id = %info.user_id, username = %info.username, "OAuth login successful");
|
| 348 |
478 |
|
|
| 349 |
|
- |
// Upsert local user
|
|
479 |
+ |
// Upsert local user. `is_fan_plus`/`is_creator` are denormalised here so
|
|
480 |
+ |
// post rendering can look up the post author's perks via JOIN — see
|
|
481 |
+ |
// migration 026.
|
| 350 |
482 |
|
let upsert_result = sqlx::query(
|
| 351 |
483 |
|
r#"
|
| 352 |
|
- |
INSERT INTO users (mnw_account_id, username, display_name, avatar_url)
|
| 353 |
|
- |
VALUES ($1, $2, $3, $4)
|
|
484 |
+ |
INSERT INTO users (mnw_account_id, username, display_name, avatar_url, is_fan_plus, is_creator)
|
|
485 |
+ |
VALUES ($1, $2, $3, $4, $5, $6)
|
| 354 |
486 |
|
ON CONFLICT (mnw_account_id) DO UPDATE
|
| 355 |
|
- |
SET username = $2, display_name = $3, avatar_url = $4, updated_at = now()
|
|
487 |
+ |
SET username = $2, display_name = $3, avatar_url = $4,
|
|
488 |
+ |
is_fan_plus = $5, is_creator = $6, updated_at = now()
|
| 356 |
489 |
|
"#,
|
| 357 |
490 |
|
)
|
| 358 |
491 |
|
.bind(info.user_id)
|
| 359 |
492 |
|
.bind(&info.username)
|
| 360 |
493 |
|
.bind(&info.display_name)
|
| 361 |
494 |
|
.bind(&info.avatar_url)
|
|
495 |
+ |
.bind(info.perks.fan_plus)
|
|
496 |
+ |
.bind(info.perks.is_creator)
|
| 362 |
497 |
|
.execute(&state.db)
|
| 363 |
498 |
|
.await;
|
| 364 |
499 |
|
|
| 386 |
521 |
|
return Redirect::to("/?error=account_suspended");
|
| 387 |
522 |
|
}
|
| 388 |
523 |
|
|
| 389 |
|
- |
// Save session
|
|
524 |
+ |
// Save session — perks come from the same userinfo response, no second roundtrip.
|
| 390 |
525 |
|
let session_user = SessionUser {
|
| 391 |
526 |
|
user_id: info.user_id,
|
| 392 |
527 |
|
username: info.username,
|
| 393 |
528 |
|
display_name: info.display_name,
|
|
529 |
+ |
perks: info.perks,
|
| 394 |
530 |
|
};
|
| 395 |
531 |
|
session_user.save_to_session(&session).await;
|
|
532 |
+ |
// Stash the access token so `refresh_session` can re-hit userinfo without
|
|
533 |
+ |
// forcing the user through another OAuth round trip. Token lifetime is set
|
|
534 |
+ |
// by MNW (7d as of writing); after expiry, refresh returns Unauthorized and
|
|
535 |
+ |
// the session is flushed.
|
|
536 |
+ |
if let Err(e) = session.insert(SESSION_ACCESS_TOKEN, &token.access_token).await {
|
|
537 |
+ |
tracing::error!(error = %e, "failed to save access token to session");
|
|
538 |
+ |
}
|
| 396 |
539 |
|
if let Err(e) = session.cycle_id().await {
|
| 397 |
540 |
|
tracing::warn!(error = %e, "Failed to cycle session ID");
|
| 398 |
541 |
|
}
|
| 401 |
544 |
|
Redirect::to("/")
|
| 402 |
545 |
|
}
|
| 403 |
546 |
|
|
|
547 |
+ |
/// `POST /auth/refresh` — re-fetch MNW userinfo and overwrite cached perks.
|
|
548 |
+ |
///
|
|
549 |
+ |
/// Useful after the user takes an action that changed their MNW entitlements
|
|
550 |
+ |
/// (e.g., subscribing to Fan+, upgrading a creator tier) so they don't have to
|
|
551 |
+ |
/// log out and back in to see the new perks. Returns the refreshed perks as
|
|
552 |
+ |
/// JSON.
|
|
553 |
+ |
#[tracing::instrument(skip_all)]
|
|
554 |
+ |
pub async fn refresh(
|
|
555 |
+ |
State(state): State<AppState>,
|
|
556 |
+ |
session: Session,
|
|
557 |
+ |
) -> Result<Json<RefreshResponse>, StatusCode> {
|
|
558 |
+ |
match refresh_session(&state, &session).await {
|
|
559 |
+ |
Ok(perks) => Ok(Json(RefreshResponse { perks })),
|
|
560 |
+ |
Err(UserinfoError::Unauthorized) => Err(StatusCode::UNAUTHORIZED),
|
|
561 |
+ |
Err(UserinfoError::Transport) => Err(StatusCode::BAD_GATEWAY),
|
|
562 |
+ |
Err(UserinfoError::BadResponse) => Err(StatusCode::BAD_GATEWAY),
|
|
563 |
+ |
}
|
|
564 |
+ |
}
|
|
565 |
+ |
|
|
566 |
+ |
#[derive(Serialize)]
|
|
567 |
+ |
pub struct RefreshResponse {
|
|
568 |
+ |
pub perks: UserPerks,
|
|
569 |
+ |
}
|
|
570 |
+ |
|
| 404 |
571 |
|
/// `POST /auth/logout` — flush session, redirect home.
|
| 405 |
572 |
|
#[tracing::instrument(skip_all)]
|
| 406 |
573 |
|
pub async fn logout(session: Session) -> impl IntoResponse {
|