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:
- Create a user type
- Create a store
- Configure authentication
- Register a user
- Login
- 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?;
}