Add axum http routes

This commit is contained in:
Aadi Desai 2023-09-24 01:56:33 +01:00
parent 092562e8c4
commit eceb64c877
Signed by: supleed2
SSH key fingerprint: SHA256:CkbNRs0yVzXEiUp2zd0PSxsfRUMFF9bLlKXtE1xEbKM

55
src/routes.rs Normal file
View file

@ -0,0 +1,55 @@
use crate::PendingMember;
use axum::{http::StatusCode, response::IntoResponse, Json};
pub(crate) async fn hello_world() -> impl IntoResponse {
(StatusCode::OK, "Hello world!")
}
#[derive(serde::Deserialize, serde::Serialize)]
pub(crate) struct Verify {
id: String,
shortcode: String,
fullname: String,
key: String,
}
pub(crate) async fn verify(
pool: sqlx::PgPool,
payload: Option<Json<Verify>>,
key: String,
) -> impl IntoResponse {
match payload {
None => (StatusCode::BAD_REQUEST, "Invalid request body").into_response(),
Some(Json(verify)) => {
if verify.key == key {
let id = match verify.id.parse::<i64>() {
Ok(i) => i,
Err(_) => {
return (StatusCode::BAD_REQUEST, "Invalid request body").into_response();
}
};
// Delete from pending if exists
let _ = crate::db::delete_pending_by_id(&pool, id).await;
match crate::db::insert_pending(
&pool,
PendingMember {
discord_id: id,
shortcode: verify.shortcode.clone(),
realname: verify.fullname.clone(),
},
)
.await
{
Ok(_) => {
println!("ID {} added: {}, {}", id, verify.shortcode, verify.fullname);
(StatusCode::OK, "Member added to `pending` database").into_response()
}
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")).into_response(),
}
} else {
(StatusCode::UNAUTHORIZED, "Auth required").into_response()
}
}
}
}