74 lines
2.1 KiB
Rust
74 lines
2.1 KiB
Rust
use axum::{
|
|
Extension,
|
|
extract,
|
|
http::StatusCode,
|
|
response::{Html, IntoResponse},
|
|
};
|
|
use crate::{
|
|
http_server::ServerState,
|
|
oauth,
|
|
};
|
|
|
|
pub async fn get_token_donate() -> impl IntoResponse {
|
|
Html(&include_bytes!("../../templates/token_donate.html")[..])
|
|
}
|
|
|
|
#[derive(serde::Deserialize, Debug)]
|
|
pub struct TokenDonateForm {
|
|
instance: String,
|
|
}
|
|
|
|
pub enum PostTokenDonateResult {
|
|
OauthRedirect(String),
|
|
Error(String),
|
|
}
|
|
|
|
impl IntoResponse for PostTokenDonateResult {
|
|
fn into_response(self) -> axum::response::Response {
|
|
match self {
|
|
PostTokenDonateResult::OauthRedirect(url) => (
|
|
StatusCode::SEE_OTHER,
|
|
[("location", url)]
|
|
).into_response(),
|
|
|
|
PostTokenDonateResult::Error(e) => (
|
|
StatusCode::INTERNAL_SERVER_ERROR,
|
|
[("content-type", "text/plain")],
|
|
e
|
|
).into_response(),
|
|
}
|
|
}
|
|
}
|
|
|
|
pub async fn post_token_donate(
|
|
Extension(ServerState { db, http_client, .. }): Extension<ServerState>,
|
|
extract::Form(form): extract::Form<TokenDonateForm>,
|
|
) -> PostTokenDonateResult {
|
|
let apps = db.get_apps(&form.instance).await
|
|
.expect("db.get_apps");
|
|
|
|
let app;
|
|
if let Some((client_id, client_secret)) = apps.into_iter().next() {
|
|
// existing app
|
|
app = oauth::Application {
|
|
client_id,
|
|
client_secret,
|
|
};
|
|
} else {
|
|
// register a new app with this instance
|
|
app = match oauth::Application::register(&http_client, &form.instance).await {
|
|
Ok(app) => app,
|
|
Err(e) => {
|
|
tracing::error!("Canont register OAuth app: {}", e);
|
|
return PostTokenDonateResult::Error(format!("{e}"));
|
|
}
|
|
};
|
|
db.add_app(&form.instance, &app.client_id, &app.client_secret).await
|
|
.expect("db.add_app");
|
|
tracing::info!("Added app for {}: {}", form.instance, app.client_id);
|
|
};
|
|
|
|
let url = app.generate_auth_url(&form.instance);
|
|
PostTokenDonateResult::OauthRedirect(url)
|
|
}
|