Warning
This library is in early development and the API may change significantly between versions.
A flexible authentication and authorization system for the Rocket web framework in Rust.
- Database Agnostic: Easily connect to any database by implementing a simple trait
- Role-Based Access Control: Define roles and their permissions with a simple macro
- Permission-Based Guards: Protect routes with role or permission requirements
- Flexible: Works with any token-based authentication system
Add this to your Cargo.toml
:
[dependencies]
rocket = "0.5.0"
rocket_roles = "0.1.0"
use rocket_roles::define_roles;
define_roles! {
"admin" => ["create_user", "delete_user", "view_admin_panel"],
"user" => ["view_profile", "edit_profile"],
"moderator" => ["delete_post", "edit_post", "pin_post"]
}
use rocket_roles::auth::{AuthProvider, AuthError, User};
use async_trait::async_trait;
use std::collections::HashSet;
struct MyAuthProvider {
// Your database connection or client here
}
#[async_trait]
impl AuthProvider for MyAuthProvider {
async fn authenticate_token(&self, token: &str) -> Result<User, AuthError> {
// Validate token and fetch user information from your database
// Return a User object with roles and permissions
// Example implementation:
if token == "invalid" {
return Err(AuthError::InvalidToken("Token is invalid".into()));
}
Ok(User::new("123", "john_doe")
.with_role("user")
.with_permission("custom_permission"))
}
}
use rocket_roles::auth::register_auth_provider;
#[launch]
fn rocket() -> _ {
// Create your auth provider
let auth_provider = MyAuthProvider::new();
// Register it
register_auth_provider(auth_provider);
// Initialize roles
initialize_roles();
rocket::build().mount("/", routes![/* your routes */])
}
use rocket_roles::{require_role, require_permission};
use rocket::get;
// Require a specific role
#[require_role("admin")]
#[get("/admin/dashboard")]
fn admin_dashboard() -> &'static str {
"Welcome to the admin dashboard!"
}
// Require a specific permission
#[require_permission("edit_profile")]
#[get("/profile/edit")]
fn edit_profile() -> &'static str {
"Edit your profile here"
}
Check out the examples directory for complete working examples:
MIT