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))
}

View File

@@ -0,0 +1,225 @@
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::unused_async)]
//! Public, read-only week-view calendar.
//!
//! Shows a 7-day grid (one column per day, one row per hour) for a single
//! court. Booked slots are coloured; free slots are blank. The same grid is
//! reused by the admin dashboard with `is_admin = true`.
use axum_extra::extract::cookie::CookieJar;
use chrono::{Datelike, Duration, NaiveDate, Utc};
use loco_rs::prelude::*;
use sea_orm::QueryOrder;
use serde::{Deserialize, Serialize};
use crate::models::_entities::{bookings, courts};
/// First bookable hour (06:00).
pub const FIRST_HOUR: i32 = 6;
/// Last bookable hour slot start (21:00 — i.e. the 21:00-22:00 slot).
pub const LAST_HOUR: i32 = 21;
const DAY_KEYS: [&str; 7] = [
"day-mon", "day-tue", "day-wed", "day-thu", "day-fri", "day-sat", "day-sun",
];
#[derive(Debug, Deserialize)]
pub struct CalQuery {
pub court: Option<i32>,
pub week: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct CourtOpt {
pub id: i32,
pub name: String,
pub selected: bool,
}
#[derive(Debug, Serialize)]
pub struct DayHead {
pub date: String,
pub key: String,
pub num: u32,
}
#[derive(Debug, Serialize)]
pub struct Cell {
pub date: String,
pub hour: i32,
pub booked: bool,
pub color: String,
pub booking_id: i32,
pub name: String,
}
#[derive(Debug, Serialize)]
pub struct Row {
pub hour_label: String,
pub cells: Vec<Cell>,
}
#[derive(Debug, Serialize)]
pub struct CalendarPage {
pub lang: String,
pub is_admin: bool,
pub base_path: String,
pub has_courts: bool,
pub courts: Vec<CourtOpt>,
pub court_id: i32,
pub court_name: String,
pub week: String,
pub week_label: String,
pub prev_week: String,
pub this_week: String,
pub next_week: String,
pub days: Vec<DayHead>,
pub rows: Vec<Row>,
}
/// Resolves the UI language from the `lang` cookie (`sk` or `en`, default `en`).
#[must_use]
pub fn current_lang(jar: &CookieJar) -> String {
match jar.get("lang").map(|c| c.value().to_string()) {
Some(ref l) if l == "sk" => "sk".to_string(),
_ => "en".to_string(),
}
}
fn monday_of(date: NaiveDate) -> NaiveDate {
date - Duration::days(i64::from(date.weekday().num_days_from_monday()))
}
fn week_monday(week: Option<&str>) -> NaiveDate {
let base = week
.and_then(|w| NaiveDate::parse_from_str(w, "%Y-%m-%d").ok())
.unwrap_or_else(|| Utc::now().date_naive());
monday_of(base)
}
/// Builds the calendar grid for the selected court and week.
pub async fn build_calendar(
ctx: &AppContext,
lang: &str,
is_admin: bool,
q_court: Option<i32>,
q_week: Option<String>,
) -> Result<CalendarPage> {
let court_list = courts::Entity::find()
.order_by_asc(courts::Column::Id)
.all(&ctx.db)
.await?;
let selected = q_court
.filter(|id| court_list.iter().any(|c| c.id == *id))
.or_else(|| court_list.first().map(|c| c.id))
.unwrap_or(0);
let courts_opts: Vec<CourtOpt> = court_list
.iter()
.map(|c| CourtOpt {
id: c.id,
name: c.name.clone().unwrap_or_else(|| format!("Court {}", c.id)),
selected: c.id == selected,
})
.collect();
let court_name = courts_opts
.iter()
.find(|c| c.selected)
.map(|c| c.name.clone())
.unwrap_or_default();
let monday = week_monday(q_week.as_deref());
let sunday = monday + Duration::days(6);
let days: Vec<DayHead> = (0..7i64)
.map(|i| {
let d = monday + Duration::days(i);
DayHead {
date: d.format("%Y-%m-%d").to_string(),
key: DAY_KEYS[i as usize].to_string(),
num: d.day(),
}
})
.collect();
let week_bookings = if selected == 0 {
Vec::new()
} else {
bookings::Entity::find()
.filter(bookings::Column::CourtId.eq(selected))
.filter(bookings::Column::Date.gte(monday))
.filter(bookings::Column::Date.lte(sunday))
.all(&ctx.db)
.await?
};
let rows: Vec<Row> = (FIRST_HOUR..=LAST_HOUR)
.map(|hour| {
let cells = (0..7i64)
.map(|i| {
let d = monday + Duration::days(i);
let iso = d.format("%Y-%m-%d").to_string();
match week_bookings.iter().find(|b| b.date == d && b.hour == hour) {
Some(b) => Cell {
date: iso,
hour,
booked: true,
color: b.color.clone(),
booking_id: b.id,
name: b.name.clone(),
},
None => Cell {
date: iso,
hour,
booked: false,
color: String::new(),
booking_id: 0,
name: String::new(),
},
}
})
.collect();
Row {
hour_label: format!("{hour:02}:00"),
cells,
}
})
.collect();
Ok(CalendarPage {
lang: lang.to_string(),
is_admin,
base_path: if is_admin { "/admin" } else { "/" }.to_string(),
has_courts: !courts_opts.is_empty(),
courts: courts_opts,
court_id: selected,
court_name,
week: monday.format("%Y-%m-%d").to_string(),
week_label: format!("{} {}", monday.format("%d %b"), sunday.format("%d %b %Y")),
prev_week: (monday - Duration::days(7)).format("%Y-%m-%d").to_string(),
this_week: monday_of(Utc::now().date_naive())
.format("%Y-%m-%d")
.to_string(),
next_week: (monday + Duration::days(7)).format("%Y-%m-%d").to_string(),
days,
rows,
})
}
#[debug_handler]
pub async fn index(
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
jar: CookieJar,
Query(q): Query<CalQuery>,
) -> Result<Response> {
let lang = current_lang(&jar);
let page = build_calendar(&ctx, &lang, false, q.court, q.week).await?;
format::render().view(&v, "calendar/week.html", &page)
}
pub fn routes() -> Routes {
Routes::new().add("/", get(index))
}

View File

@@ -1,117 +0,0 @@
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::unnecessary_struct_initialization)]
#![allow(clippy::unused_async)]
use loco_rs::prelude::*;
use serde::{Deserialize, Serialize};
use axum::response::Redirect;
use axum_extra::extract::Form;
use sea_orm::{sea_query::Order, QueryOrder};
use crate::{
models::_entities::courts::{ActiveModel, Column, Entity, Model},
views,
};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Params {
pub name: Option<String>,
pub surface: Option<String>,
pub indoor: Option<bool>,
}
impl Params {
fn update(&self, item: &mut ActiveModel) {
item.name = Set(self.name.clone());
item.surface = Set(self.surface.clone());
item.indoor = Set(self.indoor);
}
}
async fn load_item(ctx: &AppContext, id: i32) -> Result<Model> {
let item = Entity::find_by_id(id).one(&ctx.db).await?;
item.ok_or_else(|| Error::NotFound)
}
#[debug_handler]
pub async fn list(
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
) -> Result<Response> {
let item = Entity::find()
.order_by(Column::Id, Order::Desc)
.all(&ctx.db)
.await?;
views::court::list(&v, &item)
}
#[debug_handler]
pub async fn new(
ViewEngine(v): ViewEngine<TeraView>,
State(_ctx): State<AppContext>,
) -> Result<Response> {
views::court::create(&v)
}
#[debug_handler]
pub async fn update(
Path(id): Path<i32>,
State(ctx): State<AppContext>,
Form(params): Form<Params>,
) -> Result<Redirect> {
let item = load_item(&ctx, id).await?;
let mut item = item.into_active_model();
params.update(&mut item);
item.update(&ctx.db).await?;
Ok(Redirect::to("../courts"))
}
#[debug_handler]
pub async fn edit(
Path(id): Path<i32>,
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
) -> Result<Response> {
let item = load_item(&ctx, id).await?;
views::court::edit(&v, &item)
}
#[debug_handler]
pub async fn show(
Path(id): Path<i32>,
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
) -> Result<Response> {
let item = load_item(&ctx, id).await?;
views::court::show(&v, &item)
}
#[debug_handler]
pub async fn add(
State(ctx): State<AppContext>,
Form(params): Form<Params>,
) -> Result<Redirect> {
let mut item = ActiveModel {
..Default::default()
};
params.update(&mut item);
item.insert(&ctx.db).await?;
Ok(Redirect::to("courts"))
}
#[debug_handler]
pub async fn remove(Path(id): Path<i32>, State(ctx): State<AppContext>) -> Result<Response> {
load_item(&ctx, id).await?.delete(&ctx.db).await?;
format::empty()
}
pub fn routes() -> Routes {
Routes::new()
.prefix("courts/")
.add("/", get(list))
.add("/", post(add))
.add("new", get(new))
.add("{id}", get(show))
.add("{id}/edit", get(edit))
.add("{id}", delete(remove))
.add("{id}", post(update))
}

View File

@@ -1,16 +0,0 @@
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::unnecessary_struct_initialization)]
#![allow(clippy::unused_async)]
use loco_rs::prelude::*;
#[debug_handler]
pub async fn home(
ViewEngine(v): ViewEngine<TeraView>,
State(_ctx): State<AppContext>
) -> Result<Response> {
format::render().view(&v, "home/home.html", data!({}))
}
pub fn routes() -> Routes {
Routes::new().add("/", get(home))
}

View File

@@ -1,4 +1,3 @@
pub mod admin;
pub mod auth;
pub mod court;
pub mod home;
pub mod calendar;