feat(adapters): sqlite, postgres, JWT+bcrypt auth adapters

This commit is contained in:
2026-05-18 00:03:08 +02:00
parent 531b8f6eae
commit 4cab050ee8
16 changed files with 623 additions and 1789 deletions

View File

@@ -0,0 +1,15 @@
[package]
name = "adapters-auth"
version = "0.1.0"
edition = "2024"
[dependencies]
domain = { workspace = true }
async-trait = { workspace = true }
anyhow = { workspace = true }
jsonwebtoken = { workspace = true }
bcrypt = { workspace = true }
serde = { workspace = true }
uuid = { workspace = true }
chrono = { workspace = true }
tokio = { workspace = true }

View File

@@ -0,0 +1,74 @@
use async_trait::async_trait;
use chrono::Utc;
use domain::{errors::DomainError, ports::TokenIssuer, value_objects::{Role, UserId}};
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
use serde::{Deserialize, Serialize};
use std::str::FromStr;
#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
pub sub: String,
pub role: String,
pub exp: i64,
}
pub struct JwtTokenIssuer {
encoding_key: EncodingKey,
decoding_key: DecodingKey,
expiry_hours: i64,
}
impl JwtTokenIssuer {
pub fn new(secret: &str) -> Self {
Self {
encoding_key: EncodingKey::from_secret(secret.as_bytes()),
decoding_key: DecodingKey::from_secret(secret.as_bytes()),
expiry_hours: 24,
}
}
}
#[async_trait]
impl TokenIssuer for JwtTokenIssuer {
async fn issue(&self, user_id: &UserId, role: &Role) -> Result<String, DomainError> {
let claims = Claims {
sub: user_id.to_string(),
role: role.to_string(),
exp: (Utc::now() + chrono::Duration::hours(self.expiry_hours)).timestamp(),
};
encode(&Header::default(), &claims, &self.encoding_key)
.map_err(|e| DomainError::Internal(e.to_string()))
}
async fn verify(&self, token: &str) -> Result<(UserId, Role), DomainError> {
let data = decode::<Claims>(token, &self.decoding_key, &Validation::default())
.map_err(|_| DomainError::Unauthorized("Invalid or expired token".to_string()))?;
let uuid = uuid::Uuid::parse_str(&data.claims.sub)
.map_err(|_| DomainError::Unauthorized("Invalid token subject".to_string()))?;
let role = Role::from_str(&data.claims.role)
.map_err(|_| DomainError::Unauthorized("Invalid role in token".to_string()))?;
Ok((UserId::from_uuid(uuid), role))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn issue_and_verify_roundtrip() {
let issuer = JwtTokenIssuer::new("test-secret-key-long-enough-32chars!!");
let user_id = UserId::new();
let token = issuer.issue(&user_id, &Role::User).await.unwrap();
let (verified_id, verified_role) = issuer.verify(&token).await.unwrap();
assert_eq!(verified_id, user_id);
assert_eq!(verified_role, Role::User);
}
#[tokio::test]
async fn rejects_invalid_token() {
let issuer = JwtTokenIssuer::new("test-secret-key-long-enough-32chars!!");
let result = issuer.verify("not.a.valid.jwt").await;
assert!(matches!(result, Err(DomainError::Unauthorized(_))));
}
}

View File

@@ -0,0 +1,7 @@
pub mod jwt;
pub mod oidc;
pub mod password;
pub use jwt::JwtTokenIssuer;
pub use oidc::OidcAdapter;
pub use password::BcryptPasswordHasher;

View File

@@ -0,0 +1,10 @@
// Stub: extend this when auth_oidc = true.
pub struct OidcAdapter;
impl OidcAdapter {
pub fn new() -> Self { Self }
}
impl Default for OidcAdapter {
fn default() -> Self { Self::new() }
}

View File

@@ -0,0 +1,38 @@
use async_trait::async_trait;
use domain::{errors::DomainError, ports::PasswordHasher, value_objects::PasswordHash};
pub struct BcryptPasswordHasher;
#[async_trait]
impl PasswordHasher for BcryptPasswordHasher {
async fn hash(&self, password: &str) -> Result<PasswordHash, DomainError> {
let password = password.to_owned();
let hash = tokio::task::spawn_blocking(move || bcrypt::hash(&password, 12))
.await
.map_err(|e| DomainError::Internal(e.to_string()))?
.map_err(|e| DomainError::Internal(e.to_string()))?;
Ok(PasswordHash::from_hash(hash))
}
async fn verify(&self, password: &str, hash: &PasswordHash) -> Result<bool, DomainError> {
let password = password.to_owned();
let hash = hash.as_str().to_owned();
tokio::task::spawn_blocking(move || bcrypt::verify(&password, &hash))
.await
.map_err(|e| DomainError::Internal(e.to_string()))?
.map_err(|e| DomainError::Internal(e.to_string()))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn hash_and_verify_roundtrip() {
let h = BcryptPasswordHasher;
let hash = h.hash("mysecretpassword").await.unwrap();
assert!(h.verify("mysecretpassword", &hash).await.unwrap());
assert!(!h.verify("wrongpassword", &hash).await.unwrap());
}
}

View File

@@ -0,0 +1,12 @@
[package]
name = "adapters-postgres"
version = "0.1.0"
edition = "2024"
[dependencies]
domain = { workspace = true }
sqlx = { workspace = true, features = ["postgres"] }
uuid = { workspace = true }
chrono = { workspace = true }
anyhow = { workspace = true }
async-trait = { workspace = true }

View File

@@ -0,0 +1,7 @@
CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY NOT NULL,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

View File

@@ -0,0 +1,14 @@
pub type PgPool = sqlx::PgPool;
pub async fn connect(url: &str) -> anyhow::Result<PgPool> {
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(10)
.connect(url)
.await?;
Ok(pool)
}
pub async fn run_migrations(pool: &PgPool) -> anyhow::Result<()> {
sqlx::migrate!("./migrations").run(pool).await?;
Ok(())
}

View File

@@ -0,0 +1,5 @@
pub mod db;
pub mod user_repository;
pub use db::{connect, run_migrations, PgPool};
pub use user_repository::PostgresUserRepository;

View File

@@ -0,0 +1,86 @@
use async_trait::async_trait;
use domain::{
entities::User,
errors::DomainError,
ports::UserRepository,
value_objects::{Email, PasswordHash, Role, UserId},
};
use std::str::FromStr;
use crate::db::PgPool;
pub struct PostgresUserRepository {
pool: PgPool,
}
impl PostgresUserRepository {
pub fn new(pool: PgPool) -> Self { Self { pool } }
}
#[async_trait]
impl UserRepository for PostgresUserRepository {
async fn find_by_id(&self, id: &UserId) -> Result<Option<User>, DomainError> {
let row = sqlx::query!(
"SELECT id, email, password_hash, role, created_at FROM users WHERE id = $1",
*id.as_uuid()
)
.fetch_optional(&self.pool)
.await
.map_err(|e| DomainError::Internal(e.to_string()))?;
row.map(|r| Ok(User {
id: UserId::from_uuid(r.id),
email: Email::new(r.email)?,
password_hash: PasswordHash::from_hash(r.password_hash),
role: Role::from_str(&r.role).map_err(DomainError::Internal)?,
created_at: r.created_at,
}))
.transpose()
}
async fn find_by_email(&self, email: &Email) -> Result<Option<User>, DomainError> {
let row = sqlx::query!(
"SELECT id, email, password_hash, role, created_at FROM users WHERE email = $1",
email.as_str()
)
.fetch_optional(&self.pool)
.await
.map_err(|e| DomainError::Internal(e.to_string()))?;
row.map(|r| Ok(User {
id: UserId::from_uuid(r.id),
email: Email::new(r.email)?,
password_hash: PasswordHash::from_hash(r.password_hash),
role: Role::from_str(&r.role).map_err(DomainError::Internal)?,
created_at: r.created_at,
}))
.transpose()
}
async fn save(&self, user: &User) -> Result<(), DomainError> {
sqlx::query!(
"INSERT INTO users (id, email, password_hash, role, created_at)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (id) DO UPDATE SET
email = EXCLUDED.email,
password_hash = EXCLUDED.password_hash,
role = EXCLUDED.role",
*user.id.as_uuid(),
user.email.as_str(),
user.password_hash.as_str(),
user.role.to_string(),
user.created_at
)
.execute(&self.pool)
.await
.map_err(|e| DomainError::Internal(e.to_string()))?;
Ok(())
}
async fn delete(&self, id: &UserId) -> Result<(), DomainError> {
sqlx::query!("DELETE FROM users WHERE id = $1", *id.as_uuid())
.execute(&self.pool)
.await
.map_err(|e| DomainError::Internal(e.to_string()))?;
Ok(())
}
}

View File

@@ -0,0 +1,12 @@
[package]
name = "adapters-sqlite"
version = "0.1.0"
edition = "2024"
[dependencies]
domain = { workspace = true }
sqlx = { workspace = true, features = ["sqlite"] }
uuid = { workspace = true }
chrono = { workspace = true }
anyhow = { workspace = true }
async-trait = { workspace = true }

View File

@@ -0,0 +1,7 @@
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY NOT NULL,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
created_at TEXT NOT NULL
);

View File

@@ -0,0 +1,14 @@
pub type SqlitePool = sqlx::SqlitePool;
pub async fn connect(url: &str) -> anyhow::Result<SqlitePool> {
let pool = sqlx::sqlite::SqlitePoolOptions::new()
.max_connections(5)
.connect(url)
.await?;
Ok(pool)
}
pub async fn run_migrations(pool: &SqlitePool) -> anyhow::Result<()> {
sqlx::migrate!("./migrations").run(pool).await?;
Ok(())
}

View File

@@ -0,0 +1,5 @@
pub mod db;
pub mod user_repository;
pub use db::{connect, run_migrations, SqlitePool};
pub use user_repository::SqliteUserRepository;

View File

@@ -0,0 +1,95 @@
use async_trait::async_trait;
use domain::{
entities::User,
errors::DomainError,
ports::UserRepository,
value_objects::{Email, PasswordHash, Role, UserId},
};
use std::str::FromStr;
use crate::db::SqlitePool;
pub struct SqliteUserRepository {
pool: SqlitePool,
}
impl SqliteUserRepository {
pub fn new(pool: SqlitePool) -> Self { Self { pool } }
}
#[async_trait]
impl UserRepository for SqliteUserRepository {
async fn find_by_id(&self, id: &UserId) -> Result<Option<User>, DomainError> {
let id_str = id.to_string();
let row = sqlx::query!(
"SELECT id, email, password_hash, role, created_at FROM users WHERE id = ?",
id_str
)
.fetch_optional(&self.pool)
.await
.map_err(|e| DomainError::Internal(e.to_string()))?;
row.map(|r| row_to_user(r.id, r.email, r.password_hash, r.role, r.created_at))
.transpose()
}
async fn find_by_email(&self, email: &Email) -> Result<Option<User>, DomainError> {
let email_str = email.as_str().to_owned();
let row = sqlx::query!(
"SELECT id, email, password_hash, role, created_at FROM users WHERE email = ?",
email_str
)
.fetch_optional(&self.pool)
.await
.map_err(|e| DomainError::Internal(e.to_string()))?;
row.map(|r| row_to_user(r.id, r.email, r.password_hash, r.role, r.created_at))
.transpose()
}
async fn save(&self, user: &User) -> Result<(), DomainError> {
let id = user.id.to_string();
let email = user.email.as_str().to_owned();
let hash = user.password_hash.as_str().to_owned();
let role = user.role.to_string();
let created_at = user.created_at.to_rfc3339();
sqlx::query!(
"INSERT INTO users (id, email, password_hash, role, created_at)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
email = excluded.email,
password_hash = excluded.password_hash,
role = excluded.role",
id, email, hash, role, created_at
)
.execute(&self.pool)
.await
.map_err(|e| DomainError::Internal(e.to_string()))?;
Ok(())
}
async fn delete(&self, id: &UserId) -> Result<(), DomainError> {
let id_str = id.to_string();
sqlx::query!("DELETE FROM users WHERE id = ?", id_str)
.execute(&self.pool)
.await
.map_err(|e| DomainError::Internal(e.to_string()))?;
Ok(())
}
}
fn row_to_user(
id: String,
email: String,
password_hash: String,
role: String,
created_at: String,
) -> Result<User, DomainError> {
let uuid = uuid::Uuid::parse_str(&id).map_err(|e| DomainError::Internal(e.to_string()))?;
let email = Email::new(email)?;
let role = Role::from_str(&role).map_err(DomainError::Internal)?;
let created_at = chrono::DateTime::parse_from_rfc3339(&created_at)
.map_err(|e| DomainError::Internal(e.to_string()))?
.with_timezone(&chrono::Utc);
Ok(User { id: UserId::from_uuid(uuid), email, password_hash: PasswordHash::from_hash(password_hash), role, created_at })
}