use crate::error::{ForgeError, Result};
use async_trait::async_trait;
use bytes::Bytes;
use std::collections::HashMap;
use std::fmt;
use std::time::{Duration, SystemTime};
pub const MAX_PASSWORD_BYTES: usize = 4096;
pub const MAX_PHC_BYTES: usize = 1024;
pub const MAX_ID_BYTES: usize = 255;
pub const MAX_LABEL_BYTES: usize = 255;
pub const MAX_PURPOSE_BYTES: usize = 255;
pub const MAX_TOKEN_PAYLOAD_BYTES: usize = 4096;
pub const MAX_API_KEY_SCOPES: usize = 32;
pub const MAX_API_KEY_METADATA_BYTES: usize = 4096;
#[derive(Clone, PartialEq, Eq)]
pub struct PhcString(String);
impl PhcString {
pub fn new(s: impl Into<String>) -> Self {
Self(s.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Debug for PhcString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("PhcString(<redacted>)")
}
}
#[derive(Clone)]
pub struct SessionToken(String);
impl SessionToken {
pub fn new(s: impl Into<String>) -> Self {
Self(s.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Debug for SessionToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("SessionToken(<redacted>)")
}
}
#[derive(Clone)]
pub struct OneTimeToken(String);
impl OneTimeToken {
pub fn new(s: impl Into<String>) -> Self {
Self(s.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Debug for OneTimeToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("OneTimeToken(<redacted>)")
}
}
#[derive(Clone)]
pub struct ApiKeySecret(String);
impl ApiKeySecret {
pub fn new(s: impl Into<String>) -> Self {
Self(s.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Debug for ApiKeySecret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("ApiKeySecret(<redacted>)")
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy)]
pub struct SessionOpts {
pub idle_timeout: Duration,
pub absolute_timeout: Duration,
}
impl Default for SessionOpts {
fn default() -> Self {
Self {
idle_timeout: Duration::from_secs(30 * 60),
absolute_timeout: Duration::from_secs(12 * 60 * 60),
}
}
}
impl SessionOpts {
pub fn new() -> Self {
Self::default()
}
pub fn with_idle_timeout(mut self, d: Duration) -> Self {
self.idle_timeout = d;
self
}
pub fn with_absolute_timeout(mut self, d: Duration) -> Self {
self.absolute_timeout = d;
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct Session {
pub user_id: String,
pub created_at: SystemTime,
pub expires_at: SystemTime,
}
impl Session {
pub fn new(user_id: String, created_at: SystemTime, expires_at: SystemTime) -> Self {
Self {
user_id,
created_at,
expires_at,
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct ApiKey {
pub id: String,
pub label: String,
pub secret: ApiKeySecret,
pub created_at: SystemTime,
pub expires_at: Option<SystemTime>,
pub scopes: Vec<String>,
pub metadata: HashMap<String, String>,
}
impl ApiKey {
pub fn new(
id: String,
label: String,
secret: ApiKeySecret,
created_at: SystemTime,
expires_at: Option<SystemTime>,
scopes: Vec<String>,
metadata: HashMap<String, String>,
) -> Self {
Self {
id,
label,
secret,
created_at,
expires_at,
scopes,
metadata,
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct ApiKeyInfo {
pub id: String,
pub owner_id: String,
pub label: String,
pub expires_at: Option<SystemTime>,
pub scopes: Vec<String>,
pub metadata: HashMap<String, String>,
}
impl ApiKeyInfo {
pub fn new(
id: String,
owner_id: String,
label: String,
expires_at: Option<SystemTime>,
scopes: Vec<String>,
metadata: HashMap<String, String>,
) -> Self {
Self {
id,
owner_id,
label,
expires_at,
scopes,
metadata,
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Default)]
pub struct ApiKeyOpts {
pub expires_in: Option<Duration>,
pub scopes: Vec<String>,
pub metadata: HashMap<String, String>,
}
impl ApiKeyOpts {
pub fn new() -> Self {
Self::default()
}
pub fn with_expires_in(mut self, expires_in: Duration) -> Self {
self.expires_in = Some(expires_in);
self
}
pub fn with_scopes(mut self, scopes: Vec<String>) -> Self {
self.scopes = scopes;
self
}
pub fn with_metadata(mut self, metadata: HashMap<String, String>) -> Self {
self.metadata = metadata;
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TokenConsumption {
pub user_id: String,
pub payload: Bytes,
}
#[async_trait]
pub trait Auth: Send + Sync {
async fn hash_password(&self, plain: &str) -> Result<PhcString>;
async fn verify_password(&self, plain: &str, hash: &PhcString) -> Result<bool>;
fn needs_rehash(&self, hash: &PhcString) -> bool;
async fn create_session(&self, user_id: &str, opts: SessionOpts) -> Result<SessionToken>;
async fn validate_session(&self, token: &str) -> Result<Option<Session>>;
async fn revoke_session(&self, token: &str) -> Result<()>;
async fn revoke_all_sessions(&self, user_id: &str) -> Result<u64>;
async fn create_api_key(&self, owner_id: &str, label: &str) -> Result<ApiKey>;
async fn create_api_key_with(
&self,
owner_id: &str,
label: &str,
opts: ApiKeyOpts,
) -> Result<ApiKey>;
async fn verify_api_key(&self, key: &str) -> Result<Option<ApiKeyInfo>>;
async fn revoke_api_key(&self, key_id: &str) -> Result<bool>;
async fn create_token(
&self,
_user_id: &str,
_purpose: &str,
_ttl: Duration,
) -> Result<OneTimeToken> {
Err(ForgeError::backend(
"one-time tokens are not supported by this auth backend",
))
}
async fn create_token_with_payload(
&self,
user_id: &str,
purpose: &str,
ttl: Duration,
payload: Bytes,
) -> Result<OneTimeToken>;
async fn consume_token(&self, _token: &str, _purpose: &str) -> Result<Option<String>> {
Err(ForgeError::backend(
"one-time tokens are not supported by this auth backend",
))
}
async fn consume_token_with_payload(
&self,
token: &str,
purpose: &str,
) -> Result<Option<TokenConsumption>>;
}
mod memory;
mod postgres;
pub(crate) use memory::MemAuth;
pub(crate) use postgres::PgAuth;