mwoauth 0.1.0-rc.1

MediaWiki OAuth 2.0 client with optional Rocket, Axum, and Actix Web adapters
Documentation
// SPDX-License-Identifier: GPL-3.0-or-later
#![cfg(feature = "rocket")]
//! A minimal Rocket application that authenticates users via MediaWiki OAuth2.
//!
//! `mwoauth` uses Rocket private cookies. For local debug runs Rocket may
//! generate a temporary key, which invalidates sessions after restart. In
//! production, configure a stable key with `ROCKET_SECRET_KEY` (or Rocket's
//! equivalent Figment configuration) and keep it outside source control.

#[macro_use]
extern crate rocket as rocket_framework;

use mwoauth::rocket::RocketOAuth;
use mwoauth::{Error, MwOAuthClient, MwOAuthConfig, UserGuard};
use rocket_framework as rocket;

/// Landing page – shows the current login state and relevant links.
#[get("/")]
fn index(user: Option<UserGuard>) -> String {
    match user {
        Some(u) => format!(
            "Hello, {} (id #{})!\n\n\
             • Visit /me to see your user info.\n\
             • Visit /oauth/logout to log out.\n",
            u.profile().username(),
            u.profile().central_id()
        ),
        None => "You are not logged in.\n\n\
                 • Visit /oauth/login to log in via MediaWiki OAuth.\n"
            .to_string(),
    }
}

/// A route that requires an authenticated user.  If the session cookie is
/// missing or invalid the request guard returns 401 Unauthorized.
#[get("/me")]
fn me(user: UserGuard) -> String {
    format!(
        "Authenticated as: {}\n\n{}",
        user.profile().username(),
        serde_json::to_string_pretty(user.profile()).unwrap()
    )
}

/// You can pattern-match on [`mwoauth::Error`] if you want custom
/// error handling in your own routes.
#[get("/demo_error_handling")]
fn demo_error_handling(result: Result<UserGuard, Error>) -> String {
    match result {
        Ok(user) => format!("Logged in as {}", user.profile().username()),
        Err(Error::NotLoggedIn) => "You need to log in first.".to_string(),
        Err(other) => format!("Something went wrong: {other}"),
    }
}

#[launch]
fn rocket() -> _ {
    let config = MwOAuthConfig::confidential(
        "https://meta.wikimedia.org/w/api.php".parse().unwrap(),
        "CLIENT_ID",
        "CLIENT_SECRET",
        "http://127.0.0.1:8000/oauth/callback".parse().unwrap(),
        "https://gitlab.com/mwoauth/mwoauth demo code",
    )
    .unwrap();
    let client = MwOAuthClient::new(config).unwrap();

    rocket::build()
        .attach(RocketOAuth::new(client))
        .mount("/", routes![index, me, demo_error_handling])
}