tenis booking site done by claude

This commit is contained in:
Priec
2026-05-16 00:02:39 +02:00
parent 8b7f883f14
commit 7d05209d48
40 changed files with 1180 additions and 632 deletions

View File

@@ -0,0 +1,392 @@
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::unused_async)]
//! Admin area: cookie-based JWT login and the booking editor.
//!
//! There is exactly one admin. Login is gated to the `ADMIN_EMAIL` env value
//! so any other user row in the DB cannot reach the admin pages.
use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use axum::response::Redirect;
use axum_extra::extract::cookie::{Cookie, CookieJar};
use loco_rs::auth::jwt;
use loco_rs::prelude::*;
use sea_orm::QueryOrder;
use serde::Deserialize;
use crate::controllers::calendar::{self, build_calendar, current_lang, FIRST_HOUR, LAST_HOUR};
use crate::models::_entities::{bookings, courts};
use crate::models::users;
const AUTH_COOKIE: &str = "auth_token";
fn admin_email() -> String {
std::env::var("ADMIN_EMAIL").unwrap_or_default()
}
fn jwt_settings(ctx: &AppContext) -> Option<(String, u64)> {
let jwt = ctx.config.auth.as_ref()?.jwt.as_ref()?;
Some((jwt.secret.clone(), jwt.expiration))
}
/// Request guard for admin-only routes. On any failure it redirects to the
/// login page instead of returning an error.
pub struct AdminAuth {
#[allow(dead_code)]
pub user: users::Model,
}
impl FromRequestParts<AppContext> for AdminAuth {
type Rejection = Redirect;
async fn from_request_parts(
parts: &mut Parts,
ctx: &AppContext,
) -> std::result::Result<Self, Self::Rejection> {
let deny = || Redirect::to("/admin/login");
let admin = admin_email();
if admin.is_empty() {
return Err(deny());
}
let jar = CookieJar::from_headers(&parts.headers);
let token = jar
.get(AUTH_COOKIE)
.map(|c| c.value().to_string())
.ok_or_else(deny)?;
let (secret, _) = jwt_settings(ctx).ok_or_else(deny)?;
let claims = jwt::JWT::new(&secret)
.validate(&token)
.map_err(|_| deny())?;
let user = users::Model::find_by_pid(&ctx.db, &claims.claims.pid)
.await
.map_err(|_| deny())?;
if user.email != admin {
return Err(deny());
}
Ok(Self { user })
}
}
// ---------------------------------------------------------------- login ----
fn render_login(v: &TeraView, lang: &str, error: bool) -> Result<Response> {
format::render().view(
v,
"admin/login.html",
data!({ "lang": lang, "is_admin": false, "error": error }),
)
}
#[debug_handler]
pub async fn login_form(ViewEngine(v): ViewEngine<TeraView>, jar: CookieJar) -> Result<Response> {
render_login(&v, &current_lang(&jar), false)
}
#[derive(Debug, Deserialize)]
pub struct LoginForm {
pub email: String,
pub password: String,
}
#[debug_handler]
pub async fn login_submit(
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
jar: CookieJar,
Form(form): Form<LoginForm>,
) -> Result<Response> {
let lang = current_lang(&jar);
let admin = admin_email();
if admin.is_empty() || form.email != admin {
return render_login(&v, &lang, true);
}
let Ok(user) = users::Model::find_by_email(&ctx.db, &form.email).await else {
return render_login(&v, &lang, true);
};
if !user.verify_password(&form.password) {
return render_login(&v, &lang, true);
}
let (secret, expiration) =
jwt_settings(&ctx).ok_or_else(|| Error::string("JWT is not configured"))?;
let token = user.generate_jwt(&secret, expiration)?;
let jar = jar.add(
Cookie::build((AUTH_COOKIE, token))
.path("/")
.http_only(true)
.build(),
);
Ok((jar, Redirect::to("/admin")).into_response())
}
#[debug_handler]
pub async fn logout(jar: CookieJar) -> Result<Response> {
let jar = jar.remove(Cookie::build((AUTH_COOKIE, "")).path("/").build());
Ok((jar, Redirect::to("/admin/login")).into_response())
}
// ------------------------------------------------------------ dashboard ----
#[debug_handler]
pub async fn dashboard(
_auth: AdminAuth,
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
jar: CookieJar,
Query(q): Query<calendar::CalQuery>,
) -> Result<Response> {
let lang = current_lang(&jar);
let page = build_calendar(&ctx, &lang, true, q.court, q.week).await?;
format::render().view(&v, "calendar/week.html", &page)
}
// ---------------------------------------------------------------- courts ---
#[debug_handler]
pub async fn courts_page(
_auth: AdminAuth,
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
jar: CookieJar,
) -> Result<Response> {
let lang = current_lang(&jar);
let list = courts::Entity::find()
.order_by_asc(courts::Column::Id)
.all(&ctx.db)
.await?;
let items: Vec<_> = list
.iter()
.map(|c| {
data!({
"id": c.id,
"name": c.name.clone().unwrap_or_else(|| format!("Court {}", c.id)),
"surface": c.surface.clone().unwrap_or_default(),
"indoor": c.indoor.unwrap_or(false),
})
})
.collect();
format::render().view(
&v,
"admin/courts.html",
data!({ "lang": lang, "is_admin": true, "courts": items }),
)
}
#[derive(Debug, Deserialize)]
pub struct CourtForm {
pub name: String,
pub surface: Option<String>,
pub indoor: Option<String>,
}
#[debug_handler]
pub async fn create_court(
_auth: AdminAuth,
State(ctx): State<AppContext>,
Form(form): Form<CourtForm>,
) -> Result<Response> {
courts::ActiveModel {
name: Set(Some(form.name)),
surface: Set(form.surface.filter(|s| !s.is_empty())),
indoor: Set(Some(form.indoor.is_some())),
..Default::default()
}
.insert(&ctx.db)
.await?;
Ok(Redirect::to("/admin/courts").into_response())
}
// --------------------------------------------------------------- bookings --
fn hour_options() -> Vec<serde_json::Value> {
(FIRST_HOUR..=LAST_HOUR)
.map(|h| data!({ "v": h, "label": format!("{h:02}:00") }))
.collect()
}
#[derive(Debug, Deserialize)]
pub struct NewBookingQuery {
pub court: Option<i32>,
pub date: Option<String>,
pub hour: Option<i32>,
}
#[debug_handler]
pub async fn booking_new(
_auth: AdminAuth,
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
jar: CookieJar,
Query(q): Query<NewBookingQuery>,
) -> Result<Response> {
let lang = current_lang(&jar);
let court_list = courts::Entity::find()
.order_by_asc(courts::Column::Id)
.all(&ctx.db)
.await?;
let court_id = q
.court
.or_else(|| court_list.first().map(|c| c.id))
.unwrap_or(0);
let court_name = court_list
.iter()
.find(|c| c.id == court_id)
.and_then(|c| c.name.clone())
.unwrap_or_else(|| format!("Court {court_id}"));
format::render().view(
&v,
"admin/booking_form.html",
data!({
"lang": lang,
"is_admin": true,
"mode": "new",
"action": "/admin/booking",
"court_id": court_id,
"court_name": court_name,
"date": q.date.unwrap_or_default(),
"hour": q.hour.unwrap_or(FIRST_HOUR),
"color": "#3b82f6",
"name": "",
"contact": "",
"note": "",
"hours": hour_options(),
"booking_id": 0,
}),
)
}
#[derive(Debug, Deserialize)]
pub struct BookingForm {
pub court_id: i32,
pub date: String,
pub hour: i32,
pub color: String,
pub name: String,
pub contact: Option<String>,
pub note: Option<String>,
}
fn parse_date(s: &str) -> Result<chrono::NaiveDate> {
chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d")
.map_err(|_| Error::string("invalid date"))
}
#[debug_handler]
pub async fn booking_create(
_auth: AdminAuth,
State(ctx): State<AppContext>,
Form(form): Form<BookingForm>,
) -> Result<Response> {
let date = parse_date(&form.date)?;
bookings::ActiveModel {
court_id: Set(form.court_id),
date: Set(date),
hour: Set(form.hour),
color: Set(form.color),
name: Set(form.name),
contact: Set(form.contact.filter(|s| !s.is_empty())),
note: Set(form.note.filter(|s| !s.is_empty())),
..Default::default()
}
.insert(&ctx.db)
.await?;
Ok(Redirect::to(&format!("/admin?court={}&week={}", form.court_id, form.date)).into_response())
}
#[debug_handler]
pub async fn booking_edit(
_auth: AdminAuth,
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
jar: CookieJar,
Path(id): Path<i32>,
) -> Result<Response> {
let lang = current_lang(&jar);
let booking = bookings::Entity::find_by_id(id)
.one(&ctx.db)
.await?
.ok_or(Error::NotFound)?;
let court_name = courts::Entity::find_by_id(booking.court_id)
.one(&ctx.db)
.await?
.and_then(|c| c.name)
.unwrap_or_else(|| format!("Court {}", booking.court_id));
format::render().view(
&v,
"admin/booking_form.html",
data!({
"lang": lang,
"is_admin": true,
"mode": "edit",
"action": format!("/admin/booking/{id}"),
"court_id": booking.court_id,
"court_name": court_name,
"date": booking.date.format("%Y-%m-%d").to_string(),
"hour": booking.hour,
"color": booking.color,
"name": booking.name,
"contact": booking.contact.unwrap_or_default(),
"note": booking.note.unwrap_or_default(),
"hours": hour_options(),
"booking_id": id,
}),
)
}
#[debug_handler]
pub async fn booking_update(
_auth: AdminAuth,
State(ctx): State<AppContext>,
Path(id): Path<i32>,
Form(form): Form<BookingForm>,
) -> Result<Response> {
let date = parse_date(&form.date)?;
let booking = bookings::Entity::find_by_id(id)
.one(&ctx.db)
.await?
.ok_or(Error::NotFound)?;
let mut active = booking.into_active_model();
active.court_id = Set(form.court_id);
active.date = Set(date);
active.hour = Set(form.hour);
active.color = Set(form.color);
active.name = Set(form.name);
active.contact = Set(form.contact.filter(|s| !s.is_empty()));
active.note = Set(form.note.filter(|s| !s.is_empty()));
active.update(&ctx.db).await?;
Ok(Redirect::to(&format!("/admin?court={}&week={}", form.court_id, form.date)).into_response())
}
#[debug_handler]
pub async fn booking_delete(
_auth: AdminAuth,
State(ctx): State<AppContext>,
Path(id): Path<i32>,
) -> Result<Response> {
let court = bookings::Entity::find_by_id(id)
.one(&ctx.db)
.await?
.map_or(0, |b| b.court_id);
bookings::Entity::delete_by_id(id).exec(&ctx.db).await?;
Ok(Redirect::to(&format!("/admin?court={court}")).into_response())
}
pub fn routes() -> Routes {
Routes::new()
.prefix("admin")
.add("/login", get(login_form))
.add("/login", post(login_submit))
.add("/logout", post(logout))
.add("/", get(dashboard))
.add("/courts", get(courts_page))
.add("/courts", post(create_court))
.add("/booking", get(booking_new))
.add("/booking", post(booking_create))
.add("/booking/{id}", get(booking_edit))
.add("/booking/{id}", post(booking_update))
.add("/booking/{id}/delete", post(booking_delete))
}