services/frontend (Next.js 16, App Router) runs on port 3001 in compose. The browser only talks to the frontend: /api/v1/* is proxied to the backend, so the session cookie lives on the frontend's host, and /api/geo/* exposes the country list and place search of the horoscope-api. - /belepes: Google Identity Services button, client id from /v1/config - /profil: account facts, display name and language, own birth data with place search, DST ambiguity prompt and the chart's positions - /admin: user search, role toggles, credit grants (admins only, 404 otherwise) Services now tolerate migrations newer than their binary, so they can be rebuilt one at a time. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
148 lines
4.5 KiB
Rust
148 lines
4.5 KiB
Rust
//! Database schema and the data access shared by several services
|
|
//! (sessions are validated by the backend and later by the chat engine).
|
|
|
|
use std::time::Duration;
|
|
|
|
use base64::Engine;
|
|
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
|
use rand::RngCore;
|
|
use serde::{Deserialize, Serialize};
|
|
use sha2::{Digest, Sha256};
|
|
use sqlx::postgres::{PgPool, PgPoolOptions};
|
|
use time::OffsetDateTime;
|
|
use uuid::Uuid;
|
|
|
|
pub use sqlx;
|
|
|
|
/// All schema migrations, embedded at compile time.
|
|
pub static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!("./migrations");
|
|
|
|
/// Applies the pending migrations. Migrations newer than this binary (applied
|
|
/// by an already updated service) are tolerated, so services can be rebuilt
|
|
/// one at a time.
|
|
pub async fn migrate(pool: &PgPool) -> Result<(), sqlx::migrate::MigrateError> {
|
|
let mut migrator = sqlx::migrate!("./migrations");
|
|
migrator.set_ignore_missing(true);
|
|
migrator.run(pool).await
|
|
}
|
|
|
|
pub async fn connect(url: &str) -> Result<PgPool, sqlx::Error> {
|
|
PgPoolOptions::new().max_connections(20).acquire_timeout(Duration::from_secs(5)).connect(url).await
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum Role {
|
|
Admin,
|
|
/// May write articles (phase 2).
|
|
Creator,
|
|
/// Paid tier: may use the models marked `@premium`.
|
|
Premium,
|
|
/// Top tier: may use the `@vip` and `@premium` models.
|
|
Vip,
|
|
User,
|
|
}
|
|
|
|
impl Role {
|
|
pub const ALL: [Role; 5] = [Role::Admin, Role::Creator, Role::Premium, Role::Vip, Role::User];
|
|
|
|
pub fn as_str(self) -> &'static str {
|
|
match self {
|
|
Role::Admin => "admin",
|
|
Role::Creator => "creator",
|
|
Role::Premium => "premium",
|
|
Role::Vip => "vip",
|
|
Role::User => "user",
|
|
}
|
|
}
|
|
|
|
pub fn parse(s: &str) -> Option<Role> {
|
|
Role::ALL.into_iter().find(|r| r.as_str() == s)
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, sqlx::FromRow)]
|
|
pub struct User {
|
|
pub id: Uuid,
|
|
pub email: String,
|
|
pub email_verified_at: Option<OffsetDateTime>,
|
|
pub display_name: Option<String>,
|
|
pub locale: String,
|
|
pub roles: Vec<String>,
|
|
pub created_at: OffsetDateTime,
|
|
pub last_login_at: Option<OffsetDateTime>,
|
|
}
|
|
|
|
impl User {
|
|
pub fn has_role(&self, role: Role) -> bool {
|
|
self.roles.iter().any(|r| r == role.as_str())
|
|
}
|
|
|
|
/// Whether the user may use something that needs `role`: admins may use
|
|
/// everything, and the VIP tier includes the premium one.
|
|
pub fn has_access(&self, role: Role) -> bool {
|
|
self.has_role(role) || self.has_role(Role::Admin) || (role == Role::Premium && self.has_role(Role::Vip))
|
|
}
|
|
|
|
pub fn role_list(&self) -> Vec<Role> {
|
|
self.roles.iter().filter_map(|r| Role::parse(r)).collect()
|
|
}
|
|
}
|
|
|
|
/// Columns selected into [`User`].
|
|
pub const USER_COLUMNS: &str = "id, email, email_verified_at, display_name, locale, roles, created_at, last_login_at";
|
|
|
|
/// A new random secret token (256 bits, URL-safe base64).
|
|
pub fn new_token() -> String {
|
|
random_token(32)
|
|
}
|
|
|
|
/// `bytes` random bytes as URL-safe base64.
|
|
pub fn random_token(bytes: usize) -> String {
|
|
let mut buf = vec![0u8; bytes];
|
|
rand::rng().fill_bytes(&mut buf);
|
|
URL_SAFE_NO_PAD.encode(buf)
|
|
}
|
|
|
|
/// Stored form of a secret token.
|
|
pub fn token_hash(token: &str) -> Vec<u8> {
|
|
Sha256::digest(token.as_bytes()).to_vec()
|
|
}
|
|
|
|
/// The session id and user of a valid (unexpired) session token.
|
|
pub async fn user_by_session(pool: &PgPool, token: &str) -> Result<Option<(Uuid, User)>, sqlx::Error> {
|
|
#[derive(sqlx::FromRow)]
|
|
struct Row {
|
|
session_id: Uuid,
|
|
#[sqlx(flatten)]
|
|
user: User,
|
|
}
|
|
let row: Option<Row> = sqlx::query_as(
|
|
"SELECT s.id AS session_id, u.id, u.email, u.email_verified_at, u.display_name, u.locale, u.roles, \
|
|
u.created_at, u.last_login_at \
|
|
FROM sessions s JOIN users u ON u.id = s.user_id \
|
|
WHERE s.token_hash = $1 AND s.expires_at > now()",
|
|
)
|
|
.bind(token_hash(token))
|
|
.fetch_optional(pool)
|
|
.await?;
|
|
Ok(row.map(|r| (r.session_id, r.user)))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn tokens_are_random_and_hashed() {
|
|
let a = new_token();
|
|
let b = new_token();
|
|
assert_ne!(a, b);
|
|
assert_eq!(a.len(), 43);
|
|
assert_eq!(token_hash(&a), token_hash(&a));
|
|
assert_ne!(token_hash(&a), token_hash(&b));
|
|
assert_eq!(Role::parse("creator"), Some(Role::Creator));
|
|
assert_eq!(Role::parse("root"), None);
|
|
}
|
|
}
|