Skip to main content

Auth

Struct Auth 

Source
pub struct Auth { /* private fields */ }
Expand description

Explicit authentication and session service backed by slabs_sessions, slabs_magic_links, and slabs_access_tokens.

Supports Argon2id password hashing, single-use 6-character magic links, HttpOnly browser session cookies, SHA-256 hashed Authorization: Bearer tokens, and HMAC-SHA256 signing.

Implementations§

Source§

impl Auth

Source

pub fn new(db: Db, secret_key: impl Into<String>, cookie_secure: bool) -> Self

Create an Auth service backed by db, using secret_key for HMAC signing and cookie_secure for the cookie Secure flag.

Source

pub fn for_signing(secret_key: impl Into<String>, cookie_secure: bool) -> Self

Create a stateless Auth handle for HMAC signing, token verification, and signed cookies without a database connection.

Source

pub fn cookie_secure(&self) -> bool

Return whether cookies emitted by this Auth instance should set the Secure attribute.

Source

pub fn hash_password(&self, password: &str) -> SlabResult<String>

Hash a plaintext password with Argon2id and a random OS salt, returning a PHC string.

Source

pub fn verify_password(&self, password: &str, password_hash: &str) -> bool

Verify a plaintext password against a stored Argon2id PHC hash string.

Source

pub fn hash_token(&self, raw_token: &str) -> String

Compute the hex-encoded SHA-256 digest of a raw token or verification code.

Source

pub fn generate_token(&self) -> String

Generate a cryptographically random 32-byte hex-encoded token.

Source

pub fn generate_short_code(&self, len: usize) -> String

Generate a random alphanumeric code of length len, omitting ambiguous 0, O, 1, and I characters.

Source

pub fn sign(&self, payload: &str) -> String

Compute a hex-encoded HMAC-SHA256 signature for payload using the configured secret key.

Source

pub fn verify_signature(&self, payload: &str, signature_hex: &str) -> bool

Verify a hex-encoded HMAC-SHA256 signature for payload in constant time.

Source

pub fn sign_token<T: Serialize>( &self, purpose: &str, payload: &T, ttl: Duration, ) -> SlabResult<String>

Mint a purpose-bound, expiring HMAC-signed token carrying payload.

Encodes {"p": purpose, "exp": unix_ts, "d": payload} as URL-safe base64 without padding and appends .<hex_hmac_sig>.

Source

pub fn verify_token<T: DeserializeOwned>( &self, purpose: &str, token: &str, ) -> SlabResult<T>

Verify a signed token produced by Auth::sign_token, enforcing purpose and expiration.

Returns HTTP 401 Unauthorized when the format, HMAC signature, encoding, payload shape, purpose, or expiration check fails.

Source

pub async fn create_session_in_tx( &self, tx: &mut Transaction<'_, Sqlite>, user_id: &str, role: &str, ttl_days: i64, ) -> SlabResult<(Session, Cookie<'static>)>

Insert a new browser session inside an existing SQLite transaction and return its cookie.

Source

pub async fn create_session( &self, user_id: &str, role: &str, ttl_days: i64, ) -> SlabResult<(Session, Cookie<'static>)>

Create and persist a new browser session in its own transaction and return its cookie.

Source

pub async fn optional_session( &self, jar: &CookieJar, ) -> SlabResult<Option<Session>>

Look up the active, unexpired Session for the request’s cookie jar, if present.

Source

pub async fn require_session(&self, jar: &CookieJar) -> SlabResult<Session>

Require a valid browser session from jar, failing with HTTP 401 if unauthenticated.

Source

pub async fn require_admin(&self, jar: &CookieJar) -> SlabResult<Session>

Require a valid browser session with the "admin" role, failing with HTTP 401 or 403 otherwise.

Source

pub async fn destroy_session( &self, jar: &CookieJar, ) -> SlabResult<Cookie<'static>>

Delete the current session from the database (if present) and return a removal cookie.

Build an HttpOnly, SameSite=Lax session cookie carrying raw_token.

Build an expired removal cookie that clears the browser session cookie.

Issue an expiring 6-character magic link code and store its SHA-256 hash in slabs_magic_links.

Atomically consume a valid, unexpired magic link code via DELETE ... RETURNING so each code works once.

Delete all expired magic link rows and return the number of rows removed.

Source

pub async fn issue_access_token( &self, user_id: &str, role: &str, description: &str, permission: &str, ) -> SlabResult<AccessTokenIssued>

Issue a personal access token prefixed with slb_ and store its SHA-256 hash in slabs_access_tokens.

Source

pub async fn optional_auth( &self, jar: &CookieJar, headers: &HeaderMap, ) -> SlabResult<Option<Principal>>

Authenticate via Authorization: Bearer <token> or the slabs_session cookie.

When a Bearer header is present, this method validates only that token and returns Ok(None) if it is invalid.

Source

pub async fn require_auth( &self, jar: &CookieJar, headers: &HeaderMap, ) -> SlabResult<Principal>

Require authentication via either session cookie or Authorization: Bearer token.

Source

pub async fn require_write_auth( &self, jar: &CookieJar, headers: &HeaderMap, ) -> SlabResult<Principal>

Require an authenticated Principal with "write" permission.

Trait Implementations§

Source§

impl Clone for Auth

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Auth

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Auth

§

impl !UnwindSafe for Auth

§

impl Forget for Auth

§

impl Freeze for Auth
where *const ArcInner<PoolInner<Sqlite>> is !null: Freeze, PhantomData<ArcInner<PoolInner<Sqlite>>>: Freeze, *const u8 is !null: Freeze, PhantomData<u8>: Freeze,

§

impl Move for Auth

§

impl Send for Auth
where Arc<PoolInner<Sqlite>>: Send, RawVecInner: Send,

§

impl Sync for Auth
where Arc<PoolInner<Sqlite>>: Sync, RawVecInner: Sync,

§

impl Unpin for Auth
where Arc<PoolInner<Sqlite>>: Unpin, *const u8 is !null: Unpin,

§

impl UnsafeUnpin for Auth
where *const ArcInner<PoolInner<Sqlite>> is !null: UnsafeUnpin, PhantomData<ArcInner<PoolInner<Sqlite>>>: UnsafeUnpin, *const u8 is !null: UnsafeUnpin, PhantomData<u8>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more