#![cfg(feature = "rocket")]
#[macro_use]
extern crate rocket as rocket_framework;
use mwoauth::rocket::RocketOAuth;
use mwoauth::{Error, MwOAuthClient, MwOAuthConfig, UserGuard};
use rocket_framework as rocket;
#[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(),
}
}
#[get("/me")]
fn me(user: UserGuard) -> String {
format!(
"Authenticated as: {}\n\n{}",
user.profile().username(),
serde_json::to_string_pretty(user.profile()).unwrap()
)
}
#[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])
}