Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Quick Start

Note

This quick start is intended to demonstrate the overall authentication workflow. Some code has been omitted for brevity. Refer to the next chapters for complete implementations and production-ready examples.

This example shows:

  1. Create a user type
  2. Create a store
  3. Configure authentication
  4. Register a user
  5. Login
  6. Refresh tokens

User

#![allow(unused)]
fn main() {
#[derive(Clone, Debug)]
pub struct User {
    // Required fileds
    pub id: String,
    pub email: String,
    pub password_hash: String,
    pub is_email_verified: bool,

    // Your custom fileds
    pub username : String,
    pub location: String,
    ...
    
}
}
#![allow(unused)]
fn main() {
impl AuthUser for User {
    fn id(&self) -> String {
        self.id.clone()
    }

    fn email(&self) -> &str {
        &self.email
    }

    fn password_hash(&self) -> &str {
        &self.password_hash
    }

    fn is_email_verified(&self) -> bool {
        self.is_email_verified
    }

    fn set_email_verified(&mut self, verified: bool) {
        self.is_email_verified = verified;
    }

    fn set_password_hash(&mut self, hash: String) {
        self.password_hash = hash;
    }
}
}

Build the service:

#![allow(unused)]
fn main() {
pub type TestAuthService = AuthService<
    TestStore,
    DefaultHasher,
    DefaultJwtManager,
    RedisBlacklistStore,
    MockEmailSender,
    MockTemplates,
    RedisOttStore,
>;

pub fn build_test_auth() -> TestAuthService {
    let client = redis::Client::open("redis://127.0.0.1/").expect("failed to connect to redis");

    AuthService::builder()
        .store(TestStore::new())
        .hasher(DefaultHasher)
        .tokens(DefaultJwtManager::new("secret"))
        .blacklist(RedisBlacklistStore::new(client.clone()))
        .email_sender(MockEmailSender)
        .email_templates(MockTemplates)
        .ott_store(RedisOttStore::new(client))
        .build()
}
}

Register:

#![allow(unused)]
fn main() {
let user = auth.register(dto).await?;
}

Login:

#![allow(unused)]
fn main() {
let tokens = auth
    .login(email, password)
    .await?;
}

Refresh:

#![allow(unused)]
fn main() {
let refreshed = auth
    .refresh_token(
        &tokens.refresh_token
    )
    .await?;
}