💾 Archived View for alchemi.dev › en › projects › kochab › files › examples › user_management.rs captured on 2022-07-16 at 16:42:58.
-=-=-=-=-=-=-
use anyhow::*; use log::LevelFilter; use kochab::{ Document, Request, Response, Server, user_management::{ user::RegisteredUser, UserManagementRoutes, }, }; #[tokio::main] /// An ultra-simple demonstration of authentication. /// /// The user should be able to set a secret string that only they can see. They should be /// able to change this at any time to any thing. Both the string and the user account /// will persist across restarts. /// /// This method sets up and starts the server async fn main() -> Result<()> { // Turn on logging env_logger::builder() .filter_module("kochab", LevelFilter::Debug) .init(); Server::new() // Add our main routes .add_authenticated_route("/", handle_main) .add_authenticated_input_route("/update", "Enter your new string:", handle_update) // Add routes for handling user authentication .add_um_routes::<String>() // Start the server .serve_unix("kochab.sock") .await } /// The landing page /// /// Displays the user's current secret string, or prompts the user to sign in if they /// haven't. Includes links to update your string (`/update`) or your account /// (`/account`). Even though we haven't added an explicit handler for `/account`, this /// route is managed by kochab. /// /// Because this route is registered as an authenticated route, any connections without a /// certificate will be prompted to add a certificate and register. async fn handle_main(_req: Request, user: RegisteredUser<String>) -> Result<Response> { // If the user is signed in, render and return their page let response = Document::new() .add_text("Your personal secret string:") .add_text(user.as_ref()) .add_blank_line() .add_link("/update", "Change your string") .add_link("/account", "Update your account") .into(); Ok(response) } /// The update endpoint /// /// Users can update their secret string here. async fn handle_update(_request: Request, mut user: RegisteredUser<String>, input: String) -> Result<Response> { // The user has already been prompted to log in if they weren't and asked to give an // input string, so all we need to do is... // Update the users data *user.as_mut() = input; // Render a response let response = Document::new() .add_text("String updated!") .add_blank_line() .add_link("/", "Back") .into(); Ok(response) }