- horoscope-api: Swiss Ephemeris natal charts, timezone/place resolution, POST /v1/natal and POST /v1/synastry - backend: users with roles, email/password and Google login, saved charts, synastries and invites, analyses with credit ledger, public shares, admin - shared crates: astro-engine, db (migrations), horoscope-client, service-kit - docker-compose with postgres, legacy Java project for reference Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
127 lines
3.6 KiB
Rust
127 lines
3.6 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");
|
|
|
|
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,
|
|
User,
|
|
}
|
|
|
|
impl Role {
|
|
pub const ALL: [Role; 3] = [Role::Admin, Role::Creator, Role::User];
|
|
|
|
pub fn as_str(self) -> &'static str {
|
|
match self {
|
|
Role::Admin => "admin",
|
|
Role::Creator => "creator",
|
|
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())
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|