feat: argon2id passwords, session cookies, bot bearer tokens

Adds the full auth flow. Reads stay public; writes (currently only POST
/api/v1/mangas) require a CurrentUser. Both browsers and bot scripts hit
the same endpoints — they just present credentials differently.

Migration 0002_auth.sql introduces users.password_hash, a sessions
table, and an api_tokens table. Sessions and api_tokens store only
sha256(raw_token) — the raw value lives in the cookie or the
Authorization header.

New endpoints under /api/v1/auth/:
- POST /register — argon2id hash, creates a session, sets cookie.
- POST /login — verifies, rotates to a fresh session (old ones expire
  naturally so other devices stay signed in).
- POST /logout — deletes the server-side session row + clears the
  cookie via Max-Age=0.
- GET  /me — current user via the new CurrentUser extractor.
- POST /tokens — issue a bot bearer token; raw value returned exactly
  once at creation.
- DELETE /tokens/{id} — owner-only: 404 if unknown, 403 if it exists
  but belongs to another user, 204 on success.

The CurrentUser axum extractor resolves cookie first, then
Authorization: Bearer; failure → AppError::Unauthenticated (401). New
AppError variants Unauthenticated/Forbidden/Conflict carry the matching
envelope codes; the top-level match in `code()` stays exhaustive.

Backend integration coverage in tests/api_auth.rs: register sets a
HttpOnly SameSite=Lax cookie and never leaks password_hash; duplicate
username → 409; weak password → 400; login rotates the cookie; wrong
password / unknown user → 401; /me with vs without cookie; logout
invalidates the cookie; bot-token roundtrip via Bearer; user A cannot
delete user B's token (403); unknown delete → 404.

Frontend:
- lib/api/auth.ts — typed wrappers; me() returns null on 401.
- lib/session.svelte.ts — per-tab user state with a seq counter to
  guard against an in-flight /me clobbering a fresh setUser.
- lib/api/client.ts — request<T> returns undefined for 204.
- routes/login + routes/register — forms with action="javascript:void(0)"
  so the no-JS path is a no-op (avoids the hydration-race where a
  pre-attach click would submit via the browser default).
- routes/+layout.svelte — session-aware nav: spinner → user + Logout,
  or Login / Register.
- e2e/auth-flow.spec.ts — login flips the layout, logout flips back;
  bad credentials surface the API error message.

Config grows AuthConfig (cookie_secure, cookie_domain, session_ttl_days)
and CORS_ALLOWED_ORIGINS. CORS middleware is mounted in app::build and
stays a no-op (same-origin) until origins are listed.

Lockstep version bump to 0.3.0.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
MechaCat02
2026-05-16 22:04:25 +02:00
parent ce9a01793f
commit 383cfbed3b
36 changed files with 1901 additions and 13 deletions

207
backend/src/api/auth.rs Normal file
View File

@@ -0,0 +1,207 @@
//! Authentication endpoints — register, login, logout, current-user, and
//! bot API token management. Session cookies are HttpOnly + SameSite=Lax
//! and rotate on login (a fresh session row is created; old sessions
//! expire naturally rather than being explicitly invalidated, so other
//! devices keep their existing logins).
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::routing::{delete, get, post};
use axum::{Json, Router};
use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
use chrono::{Duration, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::app::AppState;
use crate::auth::extractor::{CurrentUser, SESSION_COOKIE_NAME};
use crate::auth::password::{hash_password, verify_password};
use crate::auth::token::{generate_token, hash_token};
use crate::config::AuthConfig;
use crate::domain::{ApiToken, User};
use crate::error::{AppError, AppResult};
use crate::repo;
pub fn routes() -> Router<AppState> {
Router::new()
.route("/auth/register", post(register))
.route("/auth/login", post(login))
.route("/auth/logout", post(logout))
.route("/auth/me", get(me))
.route("/auth/tokens", post(create_token))
.route("/auth/tokens/:id", delete(delete_token))
}
#[derive(Debug, Deserialize)]
pub struct Credentials {
pub username: String,
pub password: String,
}
#[derive(Debug, Serialize)]
pub struct AuthResponse {
pub user: User,
}
#[derive(Debug, Deserialize)]
pub struct CreateTokenInput {
pub name: String,
}
#[derive(Debug, Serialize)]
pub struct CreatedTokenResponse {
#[serde(flatten)]
pub token: ApiToken,
/// Raw bearer token — returned exactly once at creation.
pub bearer: String,
}
async fn register(
State(state): State<AppState>,
jar: CookieJar,
Json(input): Json<Credentials>,
) -> AppResult<impl IntoResponse> {
let username = input.username.trim();
validate_username(username)?;
validate_password(&input.password)?;
let pwhash = hash_password(&input.password)?;
let user = repo::user::create(&state.db, username, &pwhash).await?;
let jar = start_session(&state, &user, jar).await?;
Ok((StatusCode::CREATED, jar, Json(AuthResponse { user })))
}
async fn login(
State(state): State<AppState>,
jar: CookieJar,
Json(input): Json<Credentials>,
) -> AppResult<impl IntoResponse> {
let username = input.username.trim();
if username.is_empty() || input.password.is_empty() {
return Err(AppError::InvalidInput(
"username and password are required".into(),
));
}
let user = repo::user::find_by_username(&state.db, username)
.await?
.ok_or(AppError::Unauthenticated)?;
if !verify_password(&input.password, &user.password_hash) {
return Err(AppError::Unauthenticated);
}
let jar = start_session(&state, &user, jar).await?;
Ok((StatusCode::OK, jar, Json(AuthResponse { user })))
}
async fn logout(
State(state): State<AppState>,
jar: CookieJar,
) -> AppResult<impl IntoResponse> {
if let Some(cookie) = jar.get(SESSION_COOKIE_NAME) {
let hash = hash_token(cookie.value());
repo::session::delete_by_token_hash(&state.db, &hash).await?;
}
let jar = jar.add(build_expired_cookie(&state.auth));
Ok((StatusCode::NO_CONTENT, jar))
}
async fn me(CurrentUser(user): CurrentUser) -> AppResult<Json<AuthResponse>> {
Ok(Json(AuthResponse { user }))
}
async fn create_token(
State(state): State<AppState>,
CurrentUser(user): CurrentUser,
Json(input): Json<CreateTokenInput>,
) -> AppResult<impl IntoResponse> {
let name = input.name.trim();
if name.is_empty() {
return Err(AppError::InvalidInput("token name is required".into()));
}
let (raw, hash) = generate_token();
let token = repo::api_token::create(&state.db, user.id, name, &hash).await?;
Ok((
StatusCode::CREATED,
Json(CreatedTokenResponse { token, bearer: raw }),
))
}
async fn delete_token(
State(state): State<AppState>,
CurrentUser(user): CurrentUser,
Path(id): Path<Uuid>,
) -> AppResult<StatusCode> {
match repo::api_token::find_owner(&state.db, id).await? {
None => Err(AppError::NotFound),
Some(owner) if owner != user.id => Err(AppError::Forbidden),
Some(_) => {
repo::api_token::delete(&state.db, id).await?;
Ok(StatusCode::NO_CONTENT)
}
}
}
async fn start_session(
state: &AppState,
user: &User,
jar: CookieJar,
) -> AppResult<CookieJar> {
let (raw, hash) = generate_token();
let expires_at = Utc::now() + Duration::days(state.auth.session_ttl_days);
repo::session::create(&state.db, user.id, &hash, expires_at).await?;
Ok(jar.add(build_session_cookie(raw, &state.auth)))
}
fn build_session_cookie(raw: String, cfg: &AuthConfig) -> Cookie<'static> {
let mut builder = Cookie::build((SESSION_COOKIE_NAME, raw))
.http_only(true)
.secure(cfg.cookie_secure)
.same_site(SameSite::Lax)
.path("/")
.max_age(time::Duration::days(cfg.session_ttl_days));
if let Some(domain) = &cfg.cookie_domain {
builder = builder.domain(domain.clone());
}
builder.build()
}
fn build_expired_cookie(cfg: &AuthConfig) -> Cookie<'static> {
let mut builder = Cookie::build((SESSION_COOKIE_NAME, ""))
.http_only(true)
.secure(cfg.cookie_secure)
.same_site(SameSite::Lax)
.path("/")
.max_age(time::Duration::seconds(0));
if let Some(domain) = &cfg.cookie_domain {
builder = builder.domain(domain.clone());
}
builder.build()
}
fn validate_username(u: &str) -> AppResult<()> {
if u.is_empty() {
return Err(AppError::InvalidInput("username is required".into()));
}
if u.len() < 3 || u.len() > 32 {
return Err(AppError::InvalidInput(
"username must be 3-32 characters".into(),
));
}
if !u.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '-') {
return Err(AppError::InvalidInput(
"username may only contain letters, digits, _ and -".into(),
));
}
Ok(())
}
fn validate_password(p: &str) -> AppResult<()> {
if p.len() < 8 {
return Err(AppError::InvalidInput(
"password must be at least 8 characters".into(),
));
}
Ok(())
}

View File

@@ -6,6 +6,7 @@ use uuid::Uuid;
use crate::api::pagination::PagedResponse;
use crate::app::AppState;
use crate::auth::extractor::CurrentUser;
use crate::domain::manga::{Manga, NewManga};
use crate::error::{AppError, AppResult};
use crate::repo;
@@ -54,6 +55,7 @@ async fn get_one(
async fn create(
State(state): State<AppState>,
CurrentUser(_user): CurrentUser,
Json(input): Json<NewManga>,
) -> AppResult<Json<Manga>> {
if input.title.trim().is_empty() {

View File

@@ -1,3 +1,4 @@
pub mod auth;
pub mod files;
pub mod health;
pub mod mangas;
@@ -12,4 +13,5 @@ pub fn routes() -> Router<AppState> {
.merge(health::routes())
.merge(mangas::routes())
.merge(files::routes())
.merge(auth::routes())
}

View File

@@ -1,17 +1,20 @@
use std::sync::Arc;
use axum::http::{HeaderName, HeaderValue, Method};
use axum::Router;
use sqlx::postgres::PgPoolOptions;
use sqlx::PgPool;
use tower_http::cors::{AllowOrigin, CorsLayer};
use tower_http::trace::TraceLayer;
use crate::config::Config;
use crate::config::{AuthConfig, Config};
use crate::storage::{LocalStorage, Storage};
#[derive(Clone)]
pub struct AppState {
pub db: PgPool,
pub storage: Arc<dyn Storage>,
pub auth: AuthConfig,
}
pub async fn build(config: Config) -> anyhow::Result<Router> {
@@ -23,7 +26,8 @@ pub async fn build(config: Config) -> anyhow::Result<Router> {
let storage: Arc<dyn Storage> = Arc::new(LocalStorage::new(config.storage_dir.clone()));
Ok(router(AppState { db, storage }))
let state = AppState { db, storage, auth: config.auth.clone() };
Ok(router(state).layer(cors_layer(&config.cors_allowed_origins)))
}
/// Build a router from a pre-assembled state. Used by integration tests
@@ -34,3 +38,22 @@ pub fn router(state: AppState) -> Router {
.with_state(state)
.layer(TraceLayer::new_for_http())
}
fn cors_layer(allowed_origins: &[String]) -> CorsLayer {
if allowed_origins.is_empty() {
// Same-origin only — no CORS headers emitted.
return CorsLayer::new();
}
let origins: Vec<HeaderValue> = allowed_origins
.iter()
.filter_map(|o| HeaderValue::from_str(o).ok())
.collect();
CorsLayer::new()
.allow_origin(AllowOrigin::list(origins))
.allow_credentials(true)
.allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE])
.allow_headers([
HeaderName::from_static("content-type"),
HeaderName::from_static("authorization"),
])
}

View File

@@ -0,0 +1,63 @@
//! `CurrentUser` axum extractor.
//!
//! Resolves a request to a logged-in user by trying, in order:
//! 1. a `mangalord_session` cookie (session lookup by `sha256(value)`);
//! 2. an `Authorization: Bearer <token>` header (api_token lookup).
//!
//! Both paths look up by hash, never by raw value. Failure to resolve
//! either way returns 401 via `AppError::Unauthenticated`.
use axum::async_trait;
use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use axum_extra::extract::cookie::CookieJar;
use axum_extra::headers::authorization::Bearer;
use axum_extra::headers::Authorization;
use axum_extra::TypedHeader;
use crate::app::AppState;
use crate::auth::token::hash_token;
use crate::domain::User;
use crate::error::AppError;
use crate::repo;
pub const SESSION_COOKIE_NAME: &str = "mangalord_session";
pub struct CurrentUser(pub User);
#[async_trait]
impl FromRequestParts<AppState> for CurrentUser {
type Rejection = AppError;
async fn from_request_parts(
parts: &mut Parts,
state: &AppState,
) -> Result<Self, Self::Rejection> {
let jar = CookieJar::from_headers(&parts.headers);
if let Some(cookie) = jar.get(SESSION_COOKIE_NAME) {
let hash = hash_token(cookie.value());
if let Some(session) = repo::session::find_active(&state.db, &hash).await? {
if let Some(user) = repo::user::find_by_id(&state.db, session.user_id).await? {
return Ok(CurrentUser(user));
}
}
}
if let Ok(TypedHeader(Authorization(bearer))) =
TypedHeader::<Authorization<Bearer>>::from_request_parts(parts, state).await
{
let hash = hash_token(bearer.token());
if let Some(token) = repo::api_token::find_active(&state.db, &hash).await? {
if let Some(user) = repo::user::find_by_id(&state.db, token.user_id).await? {
// Fire-and-forget would be ideal but the test harness needs
// a deterministic write so the touched timestamp shows up
// when the test inspects state. Synchronous is fine.
let _ = repo::api_token::touch_last_used(&state.db, token.id).await;
return Ok(CurrentUser(user));
}
}
}
Err(AppError::Unauthenticated)
}
}

10
backend/src/auth/mod.rs Normal file
View File

@@ -0,0 +1,10 @@
//! Authentication primitives.
//!
//! Password hashing (argon2id), opaque-token generation for sessions and
//! bot API tokens, and the `CurrentUser` axum extractor that resolves a
//! request to a logged-in user via either a session cookie or a bearer
//! token.
pub mod extractor;
pub mod password;
pub mod token;

View File

@@ -0,0 +1,59 @@
//! Argon2id password hashing.
//!
//! `hash_password` returns a PHC-encoded string suitable for storage in
//! `users.password_hash`. `verify_password` checks a candidate against a
//! stored hash. Default Argon2 params are argon2id with the crate's
//! recommended cost (m=19456 KiB, t=2, p=1) — OWASP-aligned.
use argon2::password_hash::rand_core::OsRng;
use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
use argon2::Argon2;
use crate::error::{AppError, AppResult};
pub fn hash_password(plain: &str) -> AppResult<String> {
let salt = SaltString::generate(&mut OsRng);
Argon2::default()
.hash_password(plain.as_bytes(), &salt)
.map(|h| h.to_string())
.map_err(|e| AppError::Other(anyhow::anyhow!("password hash failed: {e}")))
}
pub fn verify_password(plain: &str, phc: &str) -> bool {
let Ok(hash) = PasswordHash::new(phc) else {
return false;
};
Argon2::default()
.verify_password(plain.as_bytes(), &hash)
.is_ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hash_then_verify_roundtrip() {
let phc = hash_password("correct horse battery staple").unwrap();
assert!(phc.starts_with("$argon2id$"));
assert!(verify_password("correct horse battery staple", &phc));
}
#[test]
fn verify_rejects_wrong_password() {
let phc = hash_password("hunter2").unwrap();
assert!(!verify_password("hunter3", &phc));
}
#[test]
fn verify_rejects_malformed_hash() {
assert!(!verify_password("anything", "not a real phc string"));
}
#[test]
fn hashes_are_salted() {
let a = hash_password("same").unwrap();
let b = hash_password("same").unwrap();
assert_ne!(a, b, "two hashes of the same password must differ (salt)");
}
}

68
backend/src/auth/token.rs Normal file
View File

@@ -0,0 +1,68 @@
//! High-entropy opaque tokens for sessions and bot API access.
//!
//! `generate_token` draws 32 bytes from the OS CSPRNG, encodes them as
//! URL-safe base64 (no padding), and returns the raw string alongside its
//! SHA-256 hash. Storage holds only the hash; the raw value lives in the
//! cookie or `Authorization` header. Comparison goes through
//! `constant_time_eq` to keep timing side channels off the table.
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use rand::rngs::OsRng;
use rand::RngCore;
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;
pub const TOKEN_BYTES: usize = 32;
pub const HASH_BYTES: usize = 32;
pub fn generate_token() -> (String, [u8; HASH_BYTES]) {
let mut raw = [0u8; TOKEN_BYTES];
OsRng.fill_bytes(&mut raw);
let encoded = URL_SAFE_NO_PAD.encode(raw);
let hash = hash_token(&encoded);
(encoded, hash)
}
pub fn hash_token(raw: &str) -> [u8; HASH_BYTES] {
let mut hasher = Sha256::new();
hasher.update(raw.as_bytes());
hasher.finalize().into()
}
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
a.ct_eq(b).into()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn generates_unique_tokens() {
let (a, _) = generate_token();
let (b, _) = generate_token();
assert_ne!(a, b);
// 32 bytes base64url-no-pad → 43 chars.
assert_eq!(a.len(), 43);
}
#[test]
fn hash_matches_generated_pair() {
let (raw, hash) = generate_token();
assert_eq!(hash_token(&raw), hash);
}
#[test]
fn hash_is_deterministic() {
assert_eq!(hash_token("abc"), hash_token("abc"));
assert_ne!(hash_token("abc"), hash_token("abd"));
}
#[test]
fn constant_time_eq_compares_correctly() {
assert!(constant_time_eq(b"abc", b"abc"));
assert!(!constant_time_eq(b"abc", b"abd"));
assert!(!constant_time_eq(b"abc", b"abcd"));
}
}

View File

@@ -1,10 +1,29 @@
use std::path::PathBuf;
#[derive(Clone, Debug)]
pub struct AuthConfig {
pub cookie_secure: bool,
pub cookie_domain: Option<String>,
pub session_ttl_days: i64,
}
impl Default for AuthConfig {
fn default() -> Self {
Self {
cookie_secure: true,
cookie_domain: None,
session_ttl_days: 30,
}
}
}
#[derive(Clone, Debug)]
pub struct Config {
pub database_url: String,
pub bind_address: String,
pub storage_dir: PathBuf,
pub auth: AuthConfig,
pub cors_allowed_origins: Vec<String>,
}
impl Config {
@@ -17,6 +36,37 @@ impl Config {
storage_dir: std::env::var("STORAGE_DIR")
.unwrap_or_else(|_| "./data/storage".to_string())
.into(),
auth: AuthConfig {
cookie_secure: env_bool("COOKIE_SECURE", true),
cookie_domain: std::env::var("COOKIE_DOMAIN")
.ok()
.filter(|s| !s.is_empty()),
session_ttl_days: env_i64("SESSION_TTL_DAYS", 30),
},
cors_allowed_origins: std::env::var("CORS_ALLOWED_ORIGINS")
.ok()
.map(|s| {
s.split(',')
.map(|o| o.trim().to_string())
.filter(|o| !o.is_empty())
.collect()
})
.unwrap_or_default(),
})
}
}
fn env_bool(name: &str, default: bool) -> bool {
match std::env::var(name).ok().as_deref() {
Some("1") | Some("true") | Some("TRUE") | Some("yes") => true,
Some("0") | Some("false") | Some("FALSE") | Some("no") => false,
_ => default,
}
}
fn env_i64(name: &str, default: i64) -> i64 {
std::env::var(name)
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(default)
}

View File

@@ -0,0 +1,15 @@
use chrono::{DateTime, Utc};
use serde::Serialize;
use sqlx::FromRow;
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, FromRow)]
pub struct ApiToken {
pub id: Uuid,
pub user_id: Uuid,
pub name: String,
#[serde(skip)]
pub token_hash: Vec<u8>,
pub created_at: DateTime<Utc>,
pub last_used_at: Option<DateTime<Utc>>,
}

View File

@@ -1,9 +1,13 @@
pub mod api_token;
pub mod bookmark;
pub mod chapter;
pub mod manga;
pub mod session;
pub mod user;
pub use api_token::ApiToken;
pub use bookmark::Bookmark;
pub use chapter::Chapter;
pub use manga::Manga;
pub use session::Session;
pub use user::User;

View File

@@ -0,0 +1,12 @@
use chrono::{DateTime, Utc};
use sqlx::FromRow;
use uuid::Uuid;
#[derive(Debug, Clone, FromRow)]
pub struct Session {
pub id: Uuid,
pub user_id: Uuid,
pub token_hash: Vec<u8>,
pub created_at: DateTime<Utc>,
pub expires_at: DateTime<Utc>,
}

View File

@@ -7,5 +7,7 @@ use uuid::Uuid;
pub struct User {
pub id: Uuid,
pub username: String,
#[serde(skip)]
pub password_hash: String,
pub created_at: DateTime<Utc>,
}

View File

@@ -11,6 +11,12 @@ pub enum AppError {
NotFound,
#[error("invalid input: {0}")]
InvalidInput(String),
#[error("unauthenticated")]
Unauthenticated,
#[error("forbidden")]
Forbidden,
#[error("conflict: {0}")]
Conflict(String),
#[error(transparent)]
Database(#[from] sqlx::Error),
#[error(transparent)]
@@ -29,6 +35,9 @@ impl AppError {
match self {
AppError::NotFound => "not_found",
AppError::InvalidInput(_) => "invalid_input",
AppError::Unauthenticated => "unauthenticated",
AppError::Forbidden => "forbidden",
AppError::Conflict(_) => "conflict",
AppError::Database(sqlx::Error::RowNotFound) => "not_found",
AppError::Database(_) => "internal_error",
AppError::Storage(StorageError::NotFound) => "not_found",
@@ -45,6 +54,9 @@ impl IntoResponse for AppError {
let (status, message) = match &self {
AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()),
AppError::InvalidInput(msg) => (StatusCode::BAD_REQUEST, msg.clone()),
AppError::Unauthenticated => (StatusCode::UNAUTHORIZED, "unauthenticated".to_string()),
AppError::Forbidden => (StatusCode::FORBIDDEN, "forbidden".to_string()),
AppError::Conflict(msg) => (StatusCode::CONFLICT, msg.clone()),
AppError::Database(sqlx::Error::RowNotFound) => {
(StatusCode::NOT_FOUND, "not found".to_string())
}
@@ -72,6 +84,9 @@ mod tests {
fn codes_are_stable() {
assert_eq!(AppError::NotFound.code(), "not_found");
assert_eq!(AppError::InvalidInput("x".into()).code(), "invalid_input");
assert_eq!(AppError::Unauthenticated.code(), "unauthenticated");
assert_eq!(AppError::Forbidden.code(), "forbidden");
assert_eq!(AppError::Conflict("x".into()).code(), "conflict");
assert_eq!(AppError::Storage(StorageError::BadKey).code(), "bad_file_key");
assert_eq!(AppError::Storage(StorageError::NotFound).code(), "not_found");
assert_eq!(AppError::Database(sqlx::Error::RowNotFound).code(), "not_found");

View File

@@ -1,5 +1,6 @@
pub mod api;
pub mod app;
pub mod auth;
pub mod config;
pub mod domain;
pub mod error;

View File

@@ -0,0 +1,69 @@
//! Bot API token persistence. `token_hash` is sha256 of the raw bearer
//! token; the raw value is shown to the user once at creation and never
//! stored.
use sqlx::PgPool;
use uuid::Uuid;
use crate::domain::ApiToken;
use crate::error::AppResult;
pub async fn create(
pool: &PgPool,
user_id: Uuid,
name: &str,
token_hash: &[u8],
) -> AppResult<ApiToken> {
let row = sqlx::query_as::<_, ApiToken>(
r#"
INSERT INTO api_tokens (user_id, name, token_hash)
VALUES ($1, $2, $3)
RETURNING id, user_id, name, token_hash, created_at, last_used_at
"#,
)
.bind(user_id)
.bind(name)
.bind(token_hash)
.fetch_one(pool)
.await?;
Ok(row)
}
pub async fn find_active(pool: &PgPool, token_hash: &[u8]) -> AppResult<Option<ApiToken>> {
let row = sqlx::query_as::<_, ApiToken>(
r#"
SELECT id, user_id, name, token_hash, created_at, last_used_at
FROM api_tokens
WHERE token_hash = $1
"#,
)
.bind(token_hash)
.fetch_optional(pool)
.await?;
Ok(row)
}
pub async fn touch_last_used(pool: &PgPool, id: Uuid) -> AppResult<()> {
sqlx::query("UPDATE api_tokens SET last_used_at = now() WHERE id = $1")
.bind(id)
.execute(pool)
.await?;
Ok(())
}
pub async fn find_owner(pool: &PgPool, id: Uuid) -> AppResult<Option<Uuid>> {
let row: Option<(Uuid,)> =
sqlx::query_as("SELECT user_id FROM api_tokens WHERE id = $1")
.bind(id)
.fetch_optional(pool)
.await?;
Ok(row.map(|(uid,)| uid))
}
pub async fn delete(pool: &PgPool, id: Uuid) -> AppResult<()> {
sqlx::query("DELETE FROM api_tokens WHERE id = $1")
.bind(id)
.execute(pool)
.await?;
Ok(())
}

View File

@@ -1 +1,4 @@
pub mod api_token;
pub mod manga;
pub mod session;
pub mod user;

View File

@@ -0,0 +1,53 @@
//! Session persistence. `token_hash` is sha256 of the raw cookie value;
//! the raw value never hits the DB.
use chrono::{DateTime, Utc};
use sqlx::PgPool;
use uuid::Uuid;
use crate::domain::Session;
use crate::error::AppResult;
pub async fn create(
pool: &PgPool,
user_id: Uuid,
token_hash: &[u8],
expires_at: DateTime<Utc>,
) -> AppResult<Session> {
let row = sqlx::query_as::<_, Session>(
r#"
INSERT INTO sessions (user_id, token_hash, expires_at)
VALUES ($1, $2, $3)
RETURNING id, user_id, token_hash, created_at, expires_at
"#,
)
.bind(user_id)
.bind(token_hash)
.bind(expires_at)
.fetch_one(pool)
.await?;
Ok(row)
}
/// Returns the session iff `token_hash` matches and it hasn't expired.
pub async fn find_active(pool: &PgPool, token_hash: &[u8]) -> AppResult<Option<Session>> {
let row = sqlx::query_as::<_, Session>(
r#"
SELECT id, user_id, token_hash, created_at, expires_at
FROM sessions
WHERE token_hash = $1 AND expires_at > now()
"#,
)
.bind(token_hash)
.fetch_optional(pool)
.await?;
Ok(row)
}
pub async fn delete_by_token_hash(pool: &PgPool, token_hash: &[u8]) -> AppResult<()> {
sqlx::query("DELETE FROM sessions WHERE token_hash = $1")
.bind(token_hash)
.execute(pool)
.await?;
Ok(())
}

57
backend/src/repo/user.rs Normal file
View File

@@ -0,0 +1,57 @@
//! User persistence.
use sqlx::PgPool;
use uuid::Uuid;
use crate::domain::User;
use crate::error::{AppError, AppResult};
pub async fn create(pool: &PgPool, username: &str, password_hash: &str) -> AppResult<User> {
let result = sqlx::query_as::<_, User>(
r#"
INSERT INTO users (username, password_hash)
VALUES ($1, $2)
RETURNING id, username, password_hash, created_at
"#,
)
.bind(username)
.bind(password_hash)
.fetch_one(pool)
.await;
match result {
Ok(user) => Ok(user),
Err(e) if is_unique_violation(&e) => {
Err(AppError::Conflict("username is already taken".into()))
}
Err(e) => Err(AppError::Database(e)),
}
}
pub async fn find_by_username(pool: &PgPool, username: &str) -> AppResult<Option<User>> {
let row = sqlx::query_as::<_, User>(
r#"SELECT id, username, password_hash, created_at FROM users WHERE username = $1"#,
)
.bind(username)
.fetch_optional(pool)
.await?;
Ok(row)
}
pub async fn find_by_id(pool: &PgPool, id: Uuid) -> AppResult<Option<User>> {
let row = sqlx::query_as::<_, User>(
r#"SELECT id, username, password_hash, created_at FROM users WHERE id = $1"#,
)
.bind(id)
.fetch_optional(pool)
.await?;
Ok(row)
}
fn is_unique_violation(err: &sqlx::Error) -> bool {
if let sqlx::Error::Database(db_err) = err {
db_err.code().as_deref() == Some("23505")
} else {
false
}
}