# 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`:
```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
```rust
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
```rust
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
```rust
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
```rust
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
```rust
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](https://git.prisma.moe/aichan/prisma_auth)
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
<p align="right">(<a href="#contributing">back to top</a>)</p>
## License
Distributed under the European Union Public License v1.2. See `LICENSE` for more information.
<p align="right">(<a href="#license">back to top</a>)</p>
## Contact
Aitor Astorga Saez de Vicuña - a.astorga.sdv@protonmail.com
Project Link: [https://git.prisma.moe/aichan/prisma_auth](https://git.prisma.moe/aichan/prisma_auth)
<p align="right">(<a href="#contact">back to top</a>)</p>
## Acknowledgments
Thanks to these amazing projects and technologies!
- [Rust Yew](https://yew.rs/) - A modern Rust framework for creating multi-threaded front-end web apps with WebAssembly
- [Rocket](https://rocket.rs/) - A web framework for Rust that makes it simple to write fast, secure web applications
- [WebAssembly](https://webassembly.org/) - A binary instruction format for a stack-based virtual machine
<p align="right">(<a href="#readme-top">back to top</a>)</p>