prisma_auth 0.1.0

A simple authentication crate supporting both Rocket backend API and Yew frontend authentication components
Documentation

Prisma Auth

A simple, reusable authentication crate supporting both Rocket backend API and Yew frontend authentication components.

Features

  • Backend Support: Rocket-based authentication with JWT tokens
  • Frontend Support: Yew components for login and authentication guards
  • Token Management: Automatic token storage, validation, and expiration
  • Modular Design: Use backend, frontend, or both features as needed

Usage

Add to your Cargo.toml:

[dependencies]
# For backend (Rocket API)
prisma_auth = { path = "../prisma_auth", features = ["rocket_backend"] }

# For frontend (Yew WASM)
prisma_auth = { path = "../prisma_auth", features = ["yew_frontend"] }

# For both
prisma_auth = { path = "../prisma_auth", features = ["rocket_backend", "yew_frontend"] }

Backend Usage (Rocket)

Basic Setup

use rocket::State;
use prisma_auth::backend::{TokenStore, login_handler, AuthGuard};
use prisma_auth::{LoginRequest, TokenResponse};

#[rocket::post("/login", format = "json", data = "<body>")]
pub fn login(body: Json<LoginRequest>, store: &State<TokenStore>) -> Result<Json<TokenResponse>, Status> {
    login_handler(body, store)
}

#[rocket::get("/protected")]
pub fn protected_route(_auth: AuthGuard) -> &'static str {
    "You are authenticated!"
}

#[launch]
fn rocket() -> _ {
    rocket::build()
        .manage(TokenStore::new())
        .mount("/api", routes![login, protected_route])
}

Environment Variables

  • ADMIN_PASSWORD: Required. The admin password for authentication
  • TOKEN_TTL_SECONDS: Optional. Token expiration time in seconds (default: 600)

Frontend Usage (Yew)

Login Component

use yew::prelude::*;
use prisma_auth::frontend::LoginComponent;

#[function_component(Login)]
pub fn login() -> Html {
    let on_success = Callback::from(|_token: String| {
        // Handle successful login
        web_sys::console::log_1(&"Login successful!".into());
    });

    html! {
        <LoginComponent
            api_base_url={"http://localhost:8000/api".to_string()}
            on_success={on_success}
            title={"My App".to_string()}
            subtitle={"Please login".to_string()}
        />
    }
}

Authentication Guard

use yew::prelude::*;
use prisma_auth::frontend::AuthGuardComponent;

#[function_component(ProtectedPage)]
pub fn protected_page() -> Html {
    let fallback = html! {
        <div>{"Please login to access this page"}</div>
    };

    html! {
        <AuthGuardComponent fallback={Some(fallback)}>
            <div>{"This content is only visible to authenticated users"}</div>
        </AuthGuardComponent>
    }
}

Manual Token Management

use prisma_auth::frontend::{get_stored_token, store_token, logout, is_authenticated};

if is_authenticated() {
    // User has a valid token stored
}

// Get the current token
if let Some(token) = get_stored_token() {
    // Use token for API requests
}

store_token("your-jwt-token").unwrap();

// Logout (remove stored token)
logout().unwrap();

Making Authenticated API Requests

use prisma_auth::frontend::{make_authenticated_request, make_request_with_token};

// Using stored token automatically
let response = make_authenticated_request(
    "GET",
    "/protected-endpoint", 
    None,
    "http://localhost:8000/api"
).await?;

// Using a specific token
let response = make_request_with_token(
    "POST",
    "/endpoint",
    Some(serde_json::json!({"data": "value"})),
    Some("your-token"),
    "http://localhost:8000/api"
).await?;

Contributing

Contributions are welcome! Please fork the repository, make your changes, and open a pull request.

  1. Fork the Project on Forgejo
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

License

Distributed under the European Union Public License v1.2. See LICENSE for more information.

Contact

Aitor Astorga Saez de Vicuña - a.astorga.sdv@protonmail.com

Project Link: https://git.prisma.moe/aichan/prisma_auth

Acknowledgments

Thanks to these amazing projects and technologies!

  • Rust Yew - A modern Rust framework for creating multi-threaded front-end web apps with WebAssembly
  • Rocket - A web framework for Rust that makes it simple to write fast, secure web applications
  • WebAssembly - A binary instruction format for a stack-based virtual machine