Authentication

Session Helpers

Import

use runique::middleware::auth::{
    login, auth_login, logout,
    is_authenticated, get_user_id, get_username,
};

Login

auth_login β€” login by user_id (recommended)

Generic shortcut: automatically loads user data from the DB using only the user_id. Suitable for any authentication flow (registration, OAuth, magic link…).

auth_login(&session, &db, user.id).await?;

login β€” full login

For cases where you already have all the data and want to control DB persistence and exclusive login.

login(
    &session,
    &db,
    user.id,
    &user.username,
    user.is_staff,
    user.is_superuser,
    None,    // Option<&RuniqueSessionStore> β€” multi-device persistence
    false,   // exclusive β€” invalidate other sessions
).await?;

Exclusive login

To allow only one active session per user at a time, pass exclusive: true:

login(&session, &db, user.id, &user.username, false, false, Some(&store), true).await?;

Or enable globally via the builder:

RuniqueApp::builder(config)
    .middleware(|m| m.with_exclusive_login(true))

Logout

logout(&session, None).await?;

// With DB session deletion (multi-device)
logout(&session, Some(&store)).await?;

Checks

// Is the user authenticated?
if is_authenticated(&session).await {
    // ...
}

// Get user ID from session (returns Pk = i32 or i64)
if let Some(user_id) = get_user_id(&session).await {
    // ...
}

// Get username from session
if let Some(username) = get_username(&session).await {
    // ...
}