13 Commits

Author SHA1 Message Date
Ultradesu 91ca486e64 Added user/visits 'deleted' status, hide it in UI
Build and Publish / Build and Publish Docker Image (push) Successful in 1m22s
2026-06-04 13:41:18 +03:00
Ultradesu 2389bca42b Fixed image transcoding. Paying attention to EXIF orientation data
Build and Publish / Build and Publish Docker Image (push) Successful in 1m24s
2026-06-04 13:08:34 +03:00
Ultradesu 520960d009 Added image compression
Build and Publish / Build and Publish Docker Image (push) Successful in 1m59s
2026-06-02 19:30:05 +03:00
Ultradesu 0cda791d44 Fixed OIDC small bug 2026-05-20 14:43:24 +03:00
ab a65488c304 Added OIDC auth
Build and Publish / Build and Publish Docker Image (push) Successful in 1m49s
2026-05-19 00:57:05 +03:00
ab 4d9d0a894c Added OIDC auth
Build and Publish / Build and Publish Docker Image (push) Successful in 2m53s
2026-05-19 00:32:36 +03:00
ab fd1e78ba8c Added OIDC auth
Build and Publish / Build and Publish Docker Image (push) Successful in 1m49s
2026-05-19 00:16:22 +03:00
ab 99e2cbc1f0 Added OIDC auth
Build and Publish / Build and Publish Docker Image (push) Successful in 1m51s
2026-05-18 23:50:34 +03:00
ab 71f444b9aa Added claudflare Turnstile captcha support 2026-05-18 23:09:07 +03:00
ab a8de7cfa33 Added claudflare Turnstile captcha support
Build and Publish / Build and Publish Docker Image (push) Successful in 3m29s
2026-05-18 22:30:36 +03:00
ab f7dcefeea6 Added claudflare Turnstile captcha support
Build and Publish / Build and Publish Docker Image (push) Successful in 7m6s
2026-05-18 22:12:54 +03:00
ab 757ebea2ba Added claudflare Turnstile captcha support
Build and Publish / Build and Publish Docker Image (push) Successful in 1m56s
2026-05-18 21:48:30 +03:00
ab 4d41513994 Added claudflare Turnstile captcha support 2026-05-18 21:48:02 +03:00
14 changed files with 1095 additions and 70 deletions
Generated
+133 -1
View File
@@ -332,12 +332,24 @@ version = "3.20.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb"
[[package]]
name = "bytemuck"
version = "1.25.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec"
[[package]]
name = "byteorder"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "byteorder-lite"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]]
name = "bytes"
version = "1.11.1"
@@ -630,6 +642,15 @@ version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853"
[[package]]
name = "crc32fast"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
dependencies = [
"cfg-if",
]
[[package]]
name = "crossbeam-queue"
version = "0.3.12"
@@ -893,12 +914,31 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "fdeflate"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
dependencies = [
"simd-adler32",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
[[package]]
name = "flate2"
version = "1.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
dependencies = [
"crc32fast",
"miniz_oxide",
]
[[package]]
name = "flume"
version = "0.11.1"
@@ -1434,6 +1474,32 @@ dependencies = [
"icu_properties",
]
[[package]]
name = "image"
version = "0.25.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
dependencies = [
"bytemuck",
"byteorder-lite",
"image-webp",
"moxcms",
"num-traits",
"png",
"zune-core",
"zune-jpeg",
]
[[package]]
name = "image-webp"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"
dependencies = [
"byteorder-lite",
"quick-error",
]
[[package]]
name = "indexmap"
version = "2.14.0"
@@ -1637,6 +1703,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
@@ -1650,6 +1717,16 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "moxcms"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"
dependencies = [
"num-traits",
"pxfm",
]
[[package]]
name = "multer"
version = "3.1.0"
@@ -1915,6 +1992,19 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
[[package]]
name = "png"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
dependencies = [
"bitflags",
"crc32fast",
"fdeflate",
"flate2",
"miniz_oxide",
]
[[package]]
name = "potential_utf"
version = "0.1.5"
@@ -1967,6 +2057,18 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "pxfm"
version = "0.1.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0c5ccf5294c6ccd63a74f1565028353830a9c2f5eb0c682c355c471726a6e3f"
[[package]]
name = "quick-error"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
[[package]]
name = "quinn"
version = "0.11.9"
@@ -2455,6 +2557,12 @@ dependencies = [
"rand_core 0.6.4",
]
[[package]]
name = "simd-adler32"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"
[[package]]
name = "siphasher"
version = "1.0.2"
@@ -3182,6 +3290,12 @@ dependencies = [
"serde_derive",
]
[[package]]
name = "urlencoding"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"
[[package]]
name = "utf8_iter"
version = "1.0.4"
@@ -3353,12 +3467,14 @@ dependencies = [
[[package]]
name = "web-petting"
version = "0.1.9"
version = "0.1.14"
dependencies = [
"base64",
"chrono",
"chrono-tz",
"cot",
"futures",
"image",
"multer",
"password-auth",
"reqwest",
@@ -3368,6 +3484,7 @@ dependencies = [
"tokio",
"tracing",
"tracing-subscriber",
"urlencoding",
"uuid",
]
@@ -3908,3 +4025,18 @@ name = "zmij"
version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
[[package]]
name = "zune-core"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb8a0807f7c01457d0379ba880ba6322660448ddebc890ce29bb64da71fb40f9"
[[package]]
name = "zune-jpeg"
version = "0.5.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
dependencies = [
"zune-core",
]
+4 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "web-petting"
version = "0.1.10"
version = "0.1.15"
edition = "2024"
[dependencies]
@@ -14,7 +14,10 @@ reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"
serde_json = "1"
multer = "3"
futures = "0.3"
image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp"] }
tokio = { version = "1", features = ["fs"] }
uuid = { version = "1", features = ["v4"] }
base64 = "0.22"
urlencoding = "2"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
+632 -29
View File
@@ -6,7 +6,13 @@ use cot::request::extractors::Path;
use cot::response::{IntoResponse, Redirect, Response};
use cot::router::{Route, Router};
use cot::session::Session;
use image::ImageDecoder;
use image::ImageFormat;
use image::ImageReader;
use image::codecs::jpeg::JpegEncoder;
use image::imageops::FilterType;
use serde::Deserialize;
use std::io::Cursor;
use crate::i18n::{Lang, Translations};
use crate::models::{Client, Lead, Media, Setting, Testimonial, User, Visit};
@@ -14,6 +20,9 @@ use crate::telegram;
const SESSION_USER_ID: &str = "user_id";
const SESSION_USER_NAME: &str = "user_name";
const SESSION_OIDC_STATE: &str = "oidc_state";
const MAX_UPLOADED_IMAGE_DIMENSION: u32 = 1920;
const UPLOADED_IMAGE_JPEG_QUALITY: u8 = 82;
// ---------------------------------------------------------------------------
// Helpers
@@ -88,6 +97,74 @@ fn has_query_flag(request: &Request, flag: &str) -> bool {
.unwrap_or(false)
}
fn get_query_param(request: &Request, key: &str) -> Option<String> {
let prefix = format!("{}=", key);
request.uri().query().and_then(|q| {
q.split('&')
.find_map(|p| p.strip_prefix(&prefix).map(|v| v.to_string()))
})
}
fn image_format_from_ext(ext: &str) -> Option<ImageFormat> {
match ext {
"jpg" | "jpeg" => Some(ImageFormat::Jpeg),
"png" => Some(ImageFormat::Png),
"webp" => Some(ImageFormat::WebP),
_ => None,
}
}
fn transcode_uploaded_image(data: &[u8], ext: &str) -> cot::Result<Option<Vec<u8>>> {
let Some(format) = image_format_from_ext(ext) else {
return Ok(None);
};
let mut decoder = ImageReader::with_format(Cursor::new(data), format)
.into_decoder()
.map_err(|e| cot::Error::internal(e.to_string()))?;
let orientation = decoder
.orientation()
.map_err(|e| cot::Error::internal(e.to_string()))?;
let mut image = image::DynamicImage::from_decoder(decoder)
.map_err(|e| cot::Error::internal(e.to_string()))?;
image.apply_orientation(orientation);
let resized = image.resize(
MAX_UPLOADED_IMAGE_DIMENSION,
MAX_UPLOADED_IMAGE_DIMENSION,
FilterType::Lanczos3,
);
let rgb = resized.to_rgb8();
let mut encoded = Vec::new();
let mut encoder = JpegEncoder::new_with_quality(&mut encoded, UPLOADED_IMAGE_JPEG_QUALITY);
encoder
.encode_image(&rgb)
.map_err(|e| cot::Error::internal(e.to_string()))?;
Ok(Some(encoded))
}
async fn save_uploaded_image(
upload_dir: &str,
file_id: uuid::Uuid,
ext: &str,
data: &[u8],
) -> cot::Result<String> {
if let Some(encoded) = transcode_uploaded_image(data, ext)? {
let path = format!("{}/{}.jpg", upload_dir, file_id);
tokio::fs::write(&path, &encoded)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
Ok(path)
} else {
let path = format!("{}/{}.{}", upload_dir, file_id, ext);
tokio::fs::write(&path, data)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
Ok(path)
}
}
/// Soft pastel palette for client calendar colors.
const CLIENT_COLORS: &[&str] = &[
"#7c6ed4", "#5b9bd5", "#4caf93", "#e0915e", "#d46c8e", "#8e6bbf", "#5cb8a5", "#c77c4f",
@@ -193,6 +270,9 @@ struct LoginTemplate<'a> {
t: &'a Translations,
lang: Lang,
error: Option<String>,
turnstile_site_key: String,
auth_password_enabled: bool,
auth_sso_enabled: bool,
}
#[derive(Debug, Template)]
@@ -254,6 +334,8 @@ struct SettingsTemplate<'a> {
admin_name: &'a str,
settings: Vec<Setting>,
saved: bool,
auth_password_checked: bool,
auth_sso_checked: bool,
}
#[derive(Debug, Template)]
@@ -284,7 +366,7 @@ struct ScheduleEditTemplate<'a> {
lang: Lang,
admin_name: &'a str,
visit: Visit,
clients: Vec<Client>,
client: Client,
users: Vec<User>,
media: Vec<Media>,
}
@@ -346,10 +428,55 @@ async fn login_page(request: Request, session: Session, db: Database) -> cot::Re
return Redirect::new(format!("/admin/setup?lang={}", lang.code())).into_response();
}
let turnstile_site_key = crate::turnstile::get_site_key(&db).await?;
let settings = Setting::objects().all(&db).await?;
let get_val = |key: &str| -> String {
settings
.iter()
.find(|s| s.key == key)
.map(|s| s.value.clone())
.unwrap_or_default()
};
let password_setting = get_val("auth_password_enabled");
let sso_setting = get_val("auth_sso_enabled");
let oidc_configured = !get_val("oidc_issuer_url").trim().is_empty();
// Default: password enabled if setting was never saved
let auth_password_enabled = if password_setting.is_empty() {
true
} else {
password_setting == "true"
};
let auth_sso_enabled = sso_setting == "true" && oidc_configured;
// Fallback: if neither is enabled, show password form
let (auth_password_enabled, auth_sso_enabled) = if !auth_password_enabled && !auth_sso_enabled {
(true, false)
} else {
(auth_password_enabled, auth_sso_enabled)
};
let error = get_query_param(&request, "error").map(|code| {
let t = lang.t();
match code.as_str() {
"sso_group" => t.login_sso_error_group,
"sso_provider" => t.login_sso_error_provider,
"sso_disabled" => t.login_sso_error_user_disabled,
"sso" => t.login_sso_error,
_ => t.login_sso_error,
}
.to_string()
});
let body = LoginTemplate {
t: lang.t(),
lang,
error: None,
error,
turnstile_site_key,
auth_password_enabled,
auth_sso_enabled,
}
.render()?;
html_response(body, lang)
@@ -425,11 +552,27 @@ async fn setup_submit(request: Request, session: Session, db: Database) -> cot::
struct LoginForm {
login: String,
password: String,
#[serde(default, rename = "cf-turnstile-response")]
cf_turnstile_response: Option<String>,
}
async fn login_submit(request: Request, session: Session, db: Database) -> cot::Result<Response> {
let (lang, form): (_, LoginForm) = parse_form_from_request(request).await?;
if !crate::turnstile::verify(&db, form.cf_turnstile_response.as_deref()).await? {
let turnstile_site_key = crate::turnstile::get_site_key(&db).await?;
let body = LoginTemplate {
t: lang.t(),
lang,
error: Some(lang.t().login_error.to_string()),
turnstile_site_key,
auth_password_enabled: true,
auth_sso_enabled: false,
}
.render()?;
return html_response(body, lang);
}
let login = form.login.clone();
let user = query!(User, $login == login && $status == "active")
.get(&db)
@@ -448,10 +591,14 @@ async fn login_submit(request: Request, session: Session, db: Database) -> cot::
}
}
let turnstile_site_key = crate::turnstile::get_site_key(&db).await?;
let body = LoginTemplate {
t: lang.t(),
lang,
error: Some(lang.t().login_error.to_string()),
turnstile_site_key,
auth_password_enabled: true,
auth_sso_enabled: false,
}
.render()?;
html_response(body, lang)
@@ -463,6 +610,325 @@ async fn logout(request: Request, session: Session) -> cot::Result<Response> {
Redirect::new(format!("/admin/login?lang={}", lang.code())).into_response()
}
// ---------------------------------------------------------------------------
// OIDC Handlers
// ---------------------------------------------------------------------------
/// Read an OIDC-related setting from the DB, returning empty string if absent.
async fn oidc_setting(db: &Database, name: &str) -> cot::Result<String> {
let k = name.to_string();
Ok(query!(Setting, $key == k)
.get(db)
.await?
.map(|s| s.value)
.unwrap_or_default())
}
/// Fetch the OpenID Connect discovery document and extract a field.
async fn oidc_discover(issuer_url: &str, field: &str) -> Option<String> {
let url = format!(
"{}/.well-known/openid-configuration",
issuer_url.trim_end_matches('/')
);
let resp = reqwest::Client::new().get(&url).send().await.ok()?;
let json: serde_json::Value = resp.json().await.ok()?;
json.get(field)?.as_str().map(|s| s.to_string())
}
/// Decode the payload of a JWT (base64url, no signature verification).
fn decode_jwt_payload(token: &str) -> Option<serde_json::Value> {
use base64::Engine;
let parts: Vec<&str> = token.split('.').collect();
if parts.len() != 3 {
return None;
}
let payload = parts[1];
let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(payload)
.ok()?;
serde_json::from_slice(&bytes).ok()
}
fn oidc_state_cookie(value: &str, max_age_seconds: u32) -> String {
format!(
"oidc_state={}; Path=/admin/oidc; HttpOnly; SameSite=Lax; Max-Age={}",
value, max_age_seconds,
)
}
fn get_cookie(request: &Request, name: &str) -> Option<String> {
let prefix = format!("{name}=");
request
.headers()
.get("cookie")
.and_then(|v| v.to_str().ok())
.and_then(|cookies| {
cookies.split(';').find_map(|part| {
let part = part.trim();
part.strip_prefix(&prefix).map(|v| v.to_string())
})
})
}
async fn oidc_start(request: Request, session: Session, db: Database) -> cot::Result<Response> {
let lang = detect_lang(&request);
let issuer_url = oidc_setting(&db, "oidc_issuer_url").await?;
let client_id = oidc_setting(&db, "oidc_client_id").await?;
let site_domain = oidc_setting(&db, "site_domain").await?;
if issuer_url.trim().is_empty() || client_id.trim().is_empty() {
return Redirect::new(format!(
"/admin/login?lang={}&error=sso_provider",
lang.code()
))
.into_response();
}
let authorization_endpoint = match oidc_discover(&issuer_url, "authorization_endpoint").await {
Some(ep) => ep,
None => {
return Redirect::new(format!(
"/admin/login?lang={}&error=sso_provider",
lang.code()
))
.into_response();
}
};
let state = rand_token();
session.insert(SESSION_OIDC_STATE, state.clone()).await?;
let redirect_uri = format!("{}/admin/oidc/callback", site_domain.trim_end_matches('/'));
let redirect_url = format!(
"{}?response_type=code&client_id={}&redirect_uri={}&scope=openid+profile&state={}",
authorization_endpoint,
urlencoding::encode(&client_id),
urlencoding::encode(&redirect_uri),
urlencoding::encode(&state),
);
let state_cookie = oidc_state_cookie(&state, 600);
Redirect::new(redirect_url)
.into_response()?
.with_header("set-cookie", state_cookie)
.into_response()
}
async fn oidc_callback(request: Request, session: Session, db: Database) -> cot::Result<Response> {
let lang = detect_lang(&request);
let fail = |code: &str| format!("/admin/login?lang={}&error={}", lang.code(), code);
// Prefer the server-side session; keep the cookie as a compatibility
// fallback for flows started before this code was deployed.
let saved_state_from_session = session
.get::<String>(SESSION_OIDC_STATE)
.await
.ok()
.flatten();
let saved_state_from_cookie = get_cookie(&request, "oidc_state");
let saved_state = saved_state_from_session
.as_deref()
.or(saved_state_from_cookie.as_deref())
.unwrap_or("");
// Extract code and state from query string
let query_str = request.uri().query().unwrap_or("");
let mut code = String::new();
let mut state = String::new();
for pair in query_str.split('&') {
if let Some(v) = pair.strip_prefix("code=") {
code = v.to_string();
} else if let Some(v) = pair.strip_prefix("state=") {
state = v.to_string();
}
}
if code.is_empty() || state.is_empty() || state != saved_state {
tracing::warn!(
target: "oidc",
has_session_state = saved_state_from_session.is_some(),
has_cookie_state = saved_state_from_cookie.is_some(),
code_empty = code.is_empty(),
state_empty = state.is_empty(),
"OIDC state mismatch",
);
let clear_cookie = oidc_state_cookie("", 0);
return Redirect::new(fail("sso"))
.into_response()?
.with_header("set-cookie", clear_cookie)
.into_response();
}
let _ = session.remove::<String>(SESSION_OIDC_STATE).await;
let issuer_url = oidc_setting(&db, "oidc_issuer_url").await?;
let client_id = oidc_setting(&db, "oidc_client_id").await?;
let client_secret = oidc_setting(&db, "oidc_client_secret").await?;
let site_domain = oidc_setting(&db, "site_domain").await?;
// Get token endpoint from discovery
let token_endpoint = match oidc_discover(&issuer_url, "token_endpoint").await {
Some(ep) => ep,
None => {
tracing::warn!("OIDC discovery failed for issuer_url={issuer_url:?}");
return Redirect::new(fail("sso_provider")).into_response();
}
};
let redirect_uri = format!("{}/admin/oidc/callback", site_domain.trim_end_matches('/'));
// Exchange code for tokens
let token_resp = reqwest::Client::new()
.post(&token_endpoint)
.form(&[
("grant_type", "authorization_code"),
("code", &code),
("redirect_uri", &redirect_uri),
("client_id", &client_id),
("client_secret", &client_secret),
])
.send()
.await;
let token_json: serde_json::Value = match token_resp {
Ok(resp) => match resp.json().await {
Ok(v) => v,
Err(e) => {
tracing::warn!("OIDC token response parse error: {e}");
return Redirect::new(fail("sso_provider")).into_response();
}
},
Err(e) => {
tracing::warn!("OIDC token request failed: {e}");
return Redirect::new(fail("sso_provider")).into_response();
}
};
let id_token = match token_json.get("id_token").and_then(|v| v.as_str()) {
Some(t) => t,
None => {
tracing::warn!("OIDC no id_token in response: {token_json}");
return Redirect::new(fail("sso_provider")).into_response();
}
};
// Decode JWT payload (no signature verification — token obtained directly from provider over TLS)
let claims = match decode_jwt_payload(id_token) {
Some(c) => c,
None => {
tracing::warn!("OIDC JWT decode failed");
return Redirect::new(fail("sso_provider")).into_response();
}
};
let preferred_username = match claims.get("preferred_username").and_then(|v| v.as_str()) {
Some(u) => u.to_string(),
None => {
tracing::warn!("OIDC no preferred_username in claims: {claims}");
return Redirect::new(fail("sso")).into_response();
}
};
let display_name = claims
.get("name")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
// Check group membership
let allowed_groups = oidc_setting(&db, "oidc_allowed_groups").await?;
if !allowed_groups.trim().is_empty() {
let required: Vec<&str> = allowed_groups
.split(',')
.map(|s| s.trim())
.filter(|s| !s.is_empty())
.collect();
let user_groups: Vec<String> = claims
.get("groups")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|g| g.as_str())
.map(|g| g.trim_start_matches('/').to_string())
.collect()
})
.unwrap_or_default();
let has_group = required
.iter()
.any(|r| user_groups.iter().any(|ug| ug.eq_ignore_ascii_case(r)));
if !has_group {
tracing::warn!(
"OIDC group check failed: user={preferred_username}, user_groups={user_groups:?}, required={required:?}"
);
return Redirect::new(fail("sso_group")).into_response();
}
}
// Find or create user
let login = preferred_username.clone();
let existing = query!(User, $login == login).get(&db).await?;
let user = match existing {
Some(u) => {
tracing::info!(target: "oidc", username = %u.login, "SSO login: existing user");
u
}
None => {
tracing::info!(target: "oidc", username = %preferred_username, "SSO login: creating new user");
let mut new_user = User {
id: Auto::auto(),
login: preferred_username.clone(),
password_hash: String::new(),
display_name: display_name.clone(),
telegram_chat_id: None,
telegram_notifications: Some(false),
status: "active".to_string(),
created_at: now_utc(),
updated_at: now_utc(),
};
new_user.save(&db).await?;
// Re-query to get the DB-assigned id (Auto::auto() may not be
// populated in the struct after save)
let login2 = preferred_username.clone();
match query!(User, $login == login2).get(&db).await? {
Some(u) => {
tracing::info!(target: "oidc", username = %u.login, id = ?u.id, "SSO login: new user created and fetched");
u
}
None => {
tracing::error!(target: "oidc", username = %preferred_username, "SSO login: user not found after creation");
return Redirect::new(fail("sso")).into_response();
}
}
}
};
if user.status != "active" {
tracing::warn!(target: "oidc", username = %user.login, status = %user.status, "SSO login: user disabled");
return Redirect::new(fail("sso_disabled")).into_response();
}
let session_name = user
.display_name
.as_deref()
.filter(|s| !s.is_empty())
.unwrap_or(&user.login)
.to_string();
tracing::info!(target: "oidc", username = %user.login, display_name = %session_name, "SSO login: session established");
session.insert(SESSION_USER_ID, user.id.unwrap()).await?;
session.insert(SESSION_USER_NAME, session_name).await?;
// Clear the oidc_state cookie
let clear_cookie = oidc_state_cookie("", 0);
Redirect::new(format!("/admin/?lang={}", lang.code()))
.into_response()?
.with_header("set-cookie", clear_cookie)
.into_response()
}
// ---------------------------------------------------------------------------
// GET Handlers (protected)
// ---------------------------------------------------------------------------
@@ -477,8 +943,10 @@ async fn admin_index(request: Request, session: Session, db: Database) -> cot::R
let tz = crate::tz::load_tz(&db).await;
let today = crate::tz::today_in_tz(tz);
let all_visits = Visit::objects().all(&db).await?;
let clients = Client::objects().all(&db).await?;
let mut all_visits = Visit::objects().all(&db).await?;
all_visits.retain(|v| v.status != "deleted");
let mut clients = Client::objects().all(&db).await?;
clients.retain(|c| c.status != "deleted");
let mut today_visits: Vec<TodayVisit> = all_visits
.iter()
@@ -501,9 +969,7 @@ async fn admin_index(request: Request, session: Session, db: Database) -> cot::R
let mut all_feedbacks: Vec<RecentFeedback> = all_visits
.iter()
.filter(|v| {
v.user_id.primary_key().unwrap() == user_id && v.client_feedback.is_some()
})
.filter(|v| v.user_id.primary_key().unwrap() == user_id && v.client_feedback.is_some())
.map(|v| {
let cid: i64 = v.client_id.primary_key().unwrap();
let client_name = clients
@@ -582,11 +1048,12 @@ async fn clients_page(request: Request, session: Session, db: Database) -> cot::
Err(resp) => return Ok(resp),
};
let show_all = has_query_flag(&request, "all");
let clients = if show_all {
let mut clients = if show_all {
Client::objects().all(&db).await?
} else {
query!(Client, $status == "active").all(&db).await?
};
clients.retain(|c| c.status != "deleted");
let body = ClientsTemplate {
t: lang.t(),
lang,
@@ -719,12 +1186,24 @@ async fn settings_page(request: Request, session: Session, db: Database) -> cot:
Err(resp) => return Ok(resp),
};
let settings = Setting::objects().all(&db).await?;
let auth_password_checked = settings
.iter()
.find(|s| s.key == "auth_password_enabled")
.map(|s| s.value == "true")
.unwrap_or(true);
let auth_sso_checked = settings
.iter()
.find(|s| s.key == "auth_sso_enabled")
.map(|s| s.value == "true")
.unwrap_or(false);
let body = SettingsTemplate {
t: lang.t(),
lang,
admin_name: &admin_name,
settings,
saved: false,
auth_password_checked,
auth_sso_checked,
}
.render()?;
html_response(body, lang)
@@ -798,6 +1277,16 @@ struct SettingsForm {
timezone: String,
site_domain: String,
seo_keywords: String,
turnstile_site_key: String,
turnstile_secret_key: String,
oidc_issuer_url: String,
oidc_client_id: String,
oidc_client_secret: String,
oidc_allowed_groups: String,
#[serde(default)]
auth_password_enabled: Option<String>,
#[serde(default)]
auth_sso_enabled: Option<String>,
}
async fn save_settings(request: Request, session: Session, db: Database) -> cot::Result<Response> {
@@ -814,6 +1303,28 @@ async fn save_settings(request: Request, session: Session, db: Database) -> cot:
("timezone", form.timezone),
("site_domain", form.site_domain),
("seo_keywords", form.seo_keywords),
("turnstile_site_key", form.turnstile_site_key),
("turnstile_secret_key", form.turnstile_secret_key),
("oidc_issuer_url", form.oidc_issuer_url),
("oidc_client_id", form.oidc_client_id),
("oidc_client_secret", form.oidc_client_secret),
("oidc_allowed_groups", form.oidc_allowed_groups),
(
"auth_password_enabled",
if form.auth_password_enabled.is_some() {
"true".to_string()
} else {
"false".to_string()
},
),
(
"auth_sso_enabled",
if form.auth_sso_enabled.is_some() {
"true".to_string()
} else {
"false".to_string()
},
),
] {
let k = key.to_string();
let existing = query!(Setting, $key == k).get(&db).await?;
@@ -836,12 +1347,24 @@ async fn save_settings(request: Request, session: Session, db: Database) -> cot:
}
let settings = Setting::objects().all(&db).await?;
let auth_password_checked = settings
.iter()
.find(|s| s.key == "auth_password_enabled")
.map(|s| s.value == "true")
.unwrap_or(true);
let auth_sso_checked = settings
.iter()
.find(|s| s.key == "auth_sso_enabled")
.map(|s| s.value == "true")
.unwrap_or(false);
let rendered = SettingsTemplate {
t: lang.t(),
lang,
admin_name: &admin_name,
settings,
saved: true,
auth_password_checked,
auth_sso_checked,
}
.render()?;
html_response(rendered, lang)
@@ -944,6 +1467,24 @@ async fn client_activate(
Redirect::new(format!("/admin/clients?lang={}", lang.code())).into_response()
}
async fn client_delete(
request: Request,
session: Session,
db: Database,
Path(client_id): Path<i64>,
) -> cot::Result<Response> {
let lang = detect_lang(&request);
if let Err(resp) = require_auth(&session, lang).await {
return Ok(resp);
}
if let Some(mut client) = query!(Client, $id == client_id).get(&db).await? {
client.status = "deleted".to_string();
client.updated_at = now_utc();
client.save(&db).await?;
}
Redirect::new(format!("/admin/clients?lang={}", lang.code())).into_response()
}
async fn user_archive(
request: Request,
session: Session,
@@ -1161,12 +1702,18 @@ async fn schedule_events(
let mut events = Vec::new();
for v in &visits {
if v.status == "deleted" {
continue;
}
if v.visit_date < start_date || v.visit_date > end_date {
continue;
}
let client_id_val: i64 = v.client_id.primary_key().unwrap();
let user_id_val: i64 = v.user_id.primary_key().unwrap();
let client = clients.iter().find(|c| c.id.unwrap() == client_id_val);
if client.map(|c| c.status.as_str()) == Some("deleted") {
continue;
}
let user = users.iter().find(|u| u.id.unwrap() == user_id_val);
let client_name = client.map(|c| c.name.as_str()).unwrap_or("?");
let client_phone = client.and_then(|c| c.phone.as_deref()).unwrap_or("");
@@ -1290,7 +1837,16 @@ async fn schedule_edit_page(
return Redirect::new(format!("/admin/schedule?lang={}", lang.code())).into_response();
}
};
let clients = query!(Client, $status == "active").all(&db).await?;
if visit.status == "deleted" {
return Redirect::new(format!("/admin/schedule?lang={}", lang.code())).into_response();
}
let client_id: i64 = visit.client_id.primary_key().unwrap();
let client = match query!(Client, $id == client_id).get(&db).await? {
Some(c) => c,
None => {
return Redirect::new(format!("/admin/schedule?lang={}", lang.code())).into_response();
}
};
let users = query!(User, $status == "active").all(&db).await?;
let mut visit_media = Media::objects().all(&db).await?;
visit_media.retain(|m| {
@@ -1306,7 +1862,7 @@ async fn schedule_edit_page(
lang,
admin_name: &admin_name,
visit,
clients,
client,
users,
media: visit_media,
}
@@ -1316,7 +1872,6 @@ async fn schedule_edit_page(
#[derive(Deserialize)]
struct EditVisitForm {
client_id: i64,
user_id: i64,
visit_date: String,
time_start: String,
@@ -1337,7 +1892,9 @@ async fn schedule_edit_submit(
return Ok(resp);
}
if let Some(mut visit) = query!(Visit, $id == visit_id).get(&db).await? {
visit.client_id = ForeignKey::PrimaryKey(Auto::fixed(form.client_id));
if visit.status == "deleted" {
return Redirect::new(format!("/admin/schedule?lang={}", lang.code())).into_response();
}
visit.user_id = ForeignKey::PrimaryKey(Auto::fixed(form.user_id));
if let Ok(d) = chrono::NaiveDate::parse_from_str(&form.visit_date, "%Y-%m-%d") {
visit.visit_date = d;
@@ -1363,7 +1920,11 @@ async fn visit_delete(
if let Err(resp) = require_auth(&session, lang).await {
return Ok(resp);
}
query!(Visit, $id == visit_id).delete(&db).await?;
if let Some(mut visit) = query!(Visit, $id == visit_id).get(&db).await? {
visit.status = "deleted".to_string();
visit.updated_at = now_utc();
visit.save(&db).await?;
}
Redirect::new(format!("/admin/schedule?lang={}", lang.code())).into_response()
}
@@ -1378,6 +1939,9 @@ async fn visit_set_done(
return Ok(resp);
}
if let Some(mut visit) = query!(Visit, $id == visit_id).get(&db).await? {
if visit.status == "deleted" {
return Redirect::new(format!("/admin/schedule?lang={}", lang.code())).into_response();
}
visit.status = "completed".to_string();
visit.updated_at = now_utc();
visit.save(&db).await?;
@@ -1396,6 +1960,9 @@ async fn visit_set_cancel(
return Ok(resp);
}
if let Some(mut visit) = query!(Visit, $id == visit_id).get(&db).await? {
if visit.status == "deleted" {
return Redirect::new(format!("/admin/schedule?lang={}", lang.code())).into_response();
}
visit.status = "cancelled".to_string();
visit.updated_at = now_utc();
visit.save(&db).await?;
@@ -1425,16 +1992,40 @@ async fn media_page(request: Request, session: Session, db: Database) -> cot::Re
})
.unwrap_or(0);
let clients_all = Client::objects().all(&db).await?;
let visits_all = Visit::objects().all(&db).await?;
let mut media_list = Media::objects().all(&db).await?;
media_list.retain(|m| m.status == "active");
media_list.retain(|m| {
if m.status != "active" {
return false;
}
let cid: i64 = m.client_id.primary_key().unwrap();
if clients_all
.iter()
.find(|c| c.id.unwrap() == cid)
.map(|c| c.status.as_str())
== Some("deleted")
{
return false;
}
if let Some(fk) = &m.visit_id {
let vid: i64 = fk.primary_key().unwrap();
if visits_all
.iter()
.find(|v| v.id.unwrap() == vid)
.map(|v| v.status.as_str())
== Some("deleted")
{
return false;
}
}
true
});
if filter_client_id > 0 {
media_list.retain(|m| m.client_id.primary_key().unwrap() == filter_client_id);
}
media_list.sort_by(|a, b| b.created_at.cmp(&a.created_at));
let clients_all = Client::objects().all(&db).await?;
let visits_all = Visit::objects().all(&db).await?;
let items: Vec<MediaItem> = media_list
.into_iter()
.map(|m| {
@@ -1488,6 +2079,9 @@ async fn media_upload_page(
Some(v) => v,
None => return Redirect::new(format!("/admin/?lang={}", lang.code())).into_response(),
};
if visit.status == "deleted" {
return Redirect::new(format!("/admin/schedule?lang={}", lang.code())).into_response();
}
let cid: i64 = visit.client_id.primary_key().unwrap();
let client = query!(Client, $id == cid).get(&db).await?;
let client_name = client.map(|c| c.name).unwrap_or_default();
@@ -1536,6 +2130,9 @@ async fn media_upload_submit(
Some(v) => v,
None => return Redirect::new(format!("/admin/?lang={}", lang.code())).into_response(),
};
if visit.status == "deleted" {
return Redirect::new(format!("/admin/schedule?lang={}", lang.code())).into_response();
}
let client_id: i64 = visit.client_id.primary_key().unwrap();
let bytes = request.into_body().into_bytes().await?;
@@ -1585,7 +2182,6 @@ async fn media_upload_submit(
};
let file_id = uuid::Uuid::new_v4();
let file_path = format!("{}/{}.{}", upload_dir, file_id, ext);
let data = field
.bytes()
@@ -1594,9 +2190,15 @@ async fn media_upload_submit(
if data.is_empty() {
continue;
}
tokio::fs::write(&file_path, &data)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
let file_path = if file_type == "photo" {
save_uploaded_image(&upload_dir, file_id, &ext, &data).await?
} else {
let path = format!("{}/{}.{}", upload_dir, file_id, ext);
tokio::fs::write(&path, &data)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
path
};
saved_files.push((file_path, file_type.to_string()));
}
@@ -1806,10 +2408,7 @@ async fn testimonial_add(
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
let file_id = uuid::Uuid::new_v4();
let path = format!("{}/{}.{}", upload_dir, file_id, ext);
tokio::fs::write(&path, &data)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
let path = save_uploaded_image(upload_dir, file_id, &ext, &data).await?;
image_path = Some(path);
}
_ => {}
@@ -1957,10 +2556,7 @@ async fn testimonial_edit(
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
let file_id = uuid::Uuid::new_v4();
let path = format!("{}/{}.{}", upload_dir, file_id, ext);
tokio::fs::write(&path, &data)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
let path = save_uploaded_image(upload_dir, file_id, &ext, &data).await?;
new_image_path = Some(path);
}
_ => {}
@@ -2032,6 +2628,8 @@ pub fn admin_router() -> Router {
Route::with_handler_and_name("/logout", logout, "admin-logout"),
Route::with_handler_and_name("/setup", setup_page, "admin-setup"),
Route::with_handler_and_name("/setup/submit", setup_submit, "admin-setup-submit"),
Route::with_handler_and_name("/oidc/start", oidc_start, "admin-oidc-start"),
Route::with_handler_and_name("/oidc/callback", oidc_callback, "admin-oidc-callback"),
// Protected
Route::with_handler_and_name("", admin_index, "admin-index-bare"),
Route::with_handler_and_name("/", admin_index, "admin-index"),
@@ -2070,6 +2668,11 @@ pub fn admin_router() -> Router {
client_activate,
"admin-client-activate",
),
Route::with_handler_and_name(
"/clients/{client_id}/delete",
client_delete,
"admin-client-delete",
),
Route::with_handler_and_name("/schedule", schedule_page, "admin-schedule"),
Route::with_handler_and_name("/schedule/new", schedule_new_page, "admin-schedule-new"),
Route::with_handler_and_name("/schedule/events", schedule_events, "admin-schedule-events"),
+68
View File
@@ -103,8 +103,11 @@ pub struct Translations {
pub clients_media_link: &'static str,
pub clients_add_title: &'static str,
pub clients_add_button: &'static str,
pub clients_delete: &'static str,
pub clients_delete_confirm: &'static str,
pub client_status_active: &'static str,
pub client_status_archived: &'static str,
pub client_status_deleted: &'static str,
// Users
pub users_title: &'static str,
@@ -135,6 +138,19 @@ pub struct Translations {
pub settings_timezone: &'static str,
pub settings_site_domain: &'static str,
pub settings_seo_keywords: &'static str,
pub settings_turnstile_site_key: &'static str,
pub settings_turnstile_secret_key: &'static str,
pub settings_oidc_issuer_url: &'static str,
pub settings_oidc_client_id: &'static str,
pub settings_oidc_client_secret: &'static str,
pub settings_oidc_allowed_groups: &'static str,
pub settings_auth_password_enabled: &'static str,
pub settings_auth_sso_enabled: &'static str,
pub settings_section_advanced: &'static str,
pub settings_section_notifications: &'static str,
pub settings_section_captcha: &'static str,
pub settings_section_oidc: &'static str,
pub settings_section_general: &'static str,
pub landing_contact_label: &'static str,
pub landing_pricing_title: &'static str,
@@ -149,6 +165,11 @@ pub struct Translations {
pub login_title: &'static str,
pub login_button: &'static str,
pub login_error: &'static str,
pub login_sso_button: &'static str,
pub login_sso_error: &'static str,
pub login_sso_error_group: &'static str,
pub login_sso_error_provider: &'static str,
pub login_sso_error_user_disabled: &'static str,
pub logout: &'static str,
pub setup_title: &'static str,
pub setup_description: &'static str,
@@ -238,6 +259,7 @@ pub struct Translations {
pub visit_status_scheduled: &'static str,
pub visit_status_completed: &'static str,
pub visit_status_cancelled: &'static str,
pub visit_status_deleted: &'static str,
pub schedule_mark_done: &'static str,
pub schedule_cancel: &'static str,
pub schedule_edit_title: &'static str,
@@ -318,8 +340,11 @@ static RU: Translations = Translations {
clients_media_link: "Медиа",
clients_add_title: "Добавить клиента",
clients_add_button: "Добавить",
clients_delete: "Удалить клиента",
clients_delete_confirm: "Точно удалить этого клиента?",
client_status_active: "Активный",
client_status_archived: "Архив",
client_status_deleted: "Удалён",
users_title: "Администраторы",
users_login: "Логин",
@@ -348,6 +373,19 @@ static RU: Translations = Translations {
settings_timezone: "Часовой пояс (например Asia/Vladivostok)",
settings_site_domain: "Домен сайта (например https://example.com)",
settings_seo_keywords: "SEO-ключевые слова (через запятую, отображаются на сайте и в мета-теге keywords)",
settings_turnstile_site_key: "Cloudflare Turnstile — Site Key (ключ виджета)",
settings_turnstile_secret_key: "Cloudflare Turnstile — Secret Key (секретный ключ)",
settings_oidc_issuer_url: "OIDC — URL провайдера (Issuer URL)",
settings_oidc_client_id: "OIDC — Client ID",
settings_oidc_client_secret: "OIDC — Client Secret",
settings_oidc_allowed_groups: "OIDC — Разрешённые группы (через запятую, пусто = все)",
settings_auth_password_enabled: "Вход по логину и паролю",
settings_auth_sso_enabled: "Вход через SSO (OIDC)",
settings_section_advanced: "Расширенные настройки",
settings_section_notifications: "Уведомления",
settings_section_captcha: "Защита от ботов",
settings_section_oidc: "Единый вход (SSO / OIDC)",
settings_section_general: "Сайт",
landing_contact_label: "Или свяжитесь с нами напрямую",
landing_pricing_title: "Стоимость",
@@ -382,6 +420,11 @@ static RU: Translations = Translations {
login_title: "Вход в систему",
login_button: "Войти",
login_error: "Неверный логин или пароль.",
login_sso_button: "Войти через SSO",
login_sso_error: "Ошибка SSO-авторизации.",
login_sso_error_group: "У вас нет доступа: вы не состоите в разрешённой группе.",
login_sso_error_provider: "Не удалось связаться с провайдером авторизации.",
login_sso_error_user_disabled: "Ваша учётная запись отключена.",
logout: "Выйти",
setup_title: "Создание администратора",
setup_description: "В системе нет ни одного администратора. Создайте первого для начала работы.",
@@ -417,6 +460,7 @@ static RU: Translations = Translations {
visit_status_scheduled: "Запланирован",
visit_status_completed: "Выполнен",
visit_status_cancelled: "Отменён",
visit_status_deleted: "Удалён",
schedule_mark_done: "Выполнен",
schedule_cancel: "Отменить",
schedule_edit_title: "Редактировать визит",
@@ -521,8 +565,11 @@ static EN: Translations = Translations {
clients_media_link: "Media",
clients_add_title: "Add Client",
clients_add_button: "Add",
clients_delete: "Delete client",
clients_delete_confirm: "Are you sure you want to delete this client?",
client_status_active: "Active",
client_status_archived: "Archived",
client_status_deleted: "Deleted",
users_title: "Administrators",
users_login: "Login",
@@ -551,6 +598,19 @@ static EN: Translations = Translations {
settings_timezone: "Timezone (e.g. Asia/Vladivostok)",
settings_site_domain: "Site domain (e.g. https://example.com)",
settings_seo_keywords: "SEO keywords (comma-separated, shown on site and in keywords meta tag)",
settings_turnstile_site_key: "Cloudflare Turnstile — Site Key",
settings_turnstile_secret_key: "Cloudflare Turnstile — Secret Key",
settings_oidc_issuer_url: "OIDC — Issuer URL",
settings_oidc_client_id: "OIDC — Client ID",
settings_oidc_client_secret: "OIDC — Client Secret",
settings_oidc_allowed_groups: "OIDC — Allowed groups (comma-separated, empty = all)",
settings_auth_password_enabled: "Password login",
settings_auth_sso_enabled: "SSO login (OIDC)",
settings_section_advanced: "Advanced settings",
settings_section_notifications: "Notifications",
settings_section_captcha: "Bot protection",
settings_section_oidc: "Single Sign-On (SSO / OIDC)",
settings_section_general: "Site",
landing_contact_label: "Or contact us directly",
landing_pricing_title: "Pricing",
@@ -585,6 +645,11 @@ static EN: Translations = Translations {
login_title: "Sign In",
login_button: "Sign In",
login_error: "Invalid login or password.",
login_sso_button: "Sign in with SSO",
login_sso_error: "SSO authentication failed.",
login_sso_error_group: "Access denied: you are not a member of an allowed group.",
login_sso_error_provider: "Could not reach the authentication provider.",
login_sso_error_user_disabled: "Your account is disabled.",
logout: "Sign Out",
setup_title: "Create Administrator",
setup_description: "There are no administrators yet. Create the first one to get started.",
@@ -620,6 +685,7 @@ static EN: Translations = Translations {
visit_status_scheduled: "Scheduled",
visit_status_completed: "Completed",
visit_status_cancelled: "Cancelled",
visit_status_deleted: "Deleted",
schedule_mark_done: "Done",
schedule_cancel: "Cancel",
schedule_edit_title: "Edit Visit",
@@ -706,6 +772,7 @@ impl Translations {
"scheduled" => self.visit_status_scheduled,
"completed" => self.visit_status_completed,
"cancelled" => self.visit_status_cancelled,
"deleted" => self.visit_status_deleted,
_ => "?",
}
}
@@ -714,6 +781,7 @@ impl Translations {
match status {
"active" => self.client_status_active,
"archived" => self.client_status_archived,
"deleted" => self.client_status_deleted,
_ => "?",
}
}
+24 -4
View File
@@ -4,14 +4,15 @@ mod migrations;
pub mod models;
mod public;
mod telegram;
mod turnstile;
mod tz;
use tracing_subscriber;
use cot::cli::CliMetadata;
use cot::config::{
DatabaseConfig, MiddlewareConfig, ProjectConfig, SessionMiddlewareConfig, SessionStoreConfig,
SessionStoreTypeConfig,
DatabaseConfig, MiddlewareConfig, ProjectConfig, SameSite, SessionMiddlewareConfig,
SessionStoreConfig, SessionStoreTypeConfig,
};
use cot::db::migrations::SyncDynMigration;
use cot::middleware::SessionMiddleware;
@@ -50,14 +51,32 @@ impl App for PublicApp {
struct PettingProject;
fn parse_bool_env(name: &str) -> Option<bool> {
let value = std::env::var(name).ok()?;
match value.trim().to_ascii_lowercase().as_str() {
"1" | "true" | "yes" | "on" => Some(true),
"0" | "false" | "no" | "off" => Some(false),
_ => None,
}
}
fn debug_enabled(config_name: &str) -> bool {
parse_bool_env("WEB_PETTING_DEBUG").unwrap_or_else(|| {
matches!(
config_name,
"dev" | "development" | "debug" | "local" | "test"
)
})
}
impl Project for PettingProject {
fn cli_metadata(&self) -> CliMetadata {
cot::cli::metadata!()
}
fn config(&self, _config_name: &str) -> cot::Result<ProjectConfig> {
fn config(&self, config_name: &str) -> cot::Result<ProjectConfig> {
Ok(ProjectConfig::builder()
.debug(true)
.debug(debug_enabled(config_name))
.database(
DatabaseConfig::builder()
.url("sqlite://db.sqlite3?mode=rwc")
@@ -68,6 +87,7 @@ impl Project for PettingProject {
.session(
SessionMiddlewareConfig::builder()
.secure(false)
.same_site(SameSite::Lax)
.store(
SessionStoreConfig::builder()
.store_type(SessionStoreTypeConfig::Database)
+3 -1
View File
@@ -43,6 +43,7 @@ pub enum VisitStatus {
Scheduled,
Completed,
Cancelled,
Deleted,
}
impl VisitStatus {
@@ -51,6 +52,7 @@ impl VisitStatus {
Self::Scheduled => "scheduled",
Self::Completed => "completed",
Self::Cancelled => "cancelled",
Self::Deleted => "deleted",
}
}
}
@@ -146,7 +148,7 @@ pub struct Visit {
pub public_notes: Option<String>,
/// Feedback text from client via portal.
pub client_feedback: Option<String>,
/// scheduled | completed | cancelled
/// scheduled | completed | cancelled | deleted
pub status: String,
pub created_at: chrono::NaiveDateTime,
pub updated_at: chrono::NaiveDateTime,
+49 -4
View File
@@ -76,6 +76,7 @@ struct LandingTemplate<'a> {
testimonials: Vec<Testimonial>,
site_domain: String,
review_count: usize,
turnstile_site_key: String,
}
#[derive(Debug, Template)]
@@ -138,6 +139,7 @@ async fn landing_page(request: Request, db: Database) -> cot::Result<Response> {
.await?
.map(|s| s.value)
.unwrap_or_default();
let turnstile_site_key = crate::turnstile::get_site_key(&db).await?;
let mut testimonials = Testimonial::objects().all(&db).await?;
testimonials.retain(|t| t.status == "active");
testimonials.sort_by(|a, b| a.sort_order.cmp(&b.sort_order));
@@ -151,6 +153,7 @@ async fn landing_page(request: Request, db: Database) -> cot::Result<Response> {
testimonials,
site_domain,
review_count,
turnstile_site_key,
}
.render()?;
html_response(body, lang)
@@ -161,6 +164,8 @@ struct LeadForm {
name: String,
phone: Option<String>,
comment: Option<String>,
#[serde(default, rename = "cf-turnstile-response")]
cf_turnstile_response: Option<String>,
}
async fn submit_lead(request: Request, db: Database) -> cot::Result<Response> {
@@ -170,6 +175,10 @@ async fn submit_lead(request: Request, db: Database) -> cot::Result<Response> {
let form: LeadForm =
serde_html_form::from_bytes(&bytes).map_err(|e| cot::Error::internal(e.to_string()))?;
if !crate::turnstile::verify(&db, form.cf_turnstile_response.as_deref()).await? {
return Redirect::new(format!("/?lang={}", lang.code())).into_response();
}
let mut lead = Lead {
id: Auto::auto(),
name: form.name,
@@ -215,6 +224,7 @@ struct ClientPortalTemplate<'a> {
upcoming: Vec<PortalVisit>,
past: Vec<PortalVisit>,
feedback_sent: bool,
turnstile_site_key: String,
}
async fn client_portal(
@@ -230,7 +240,8 @@ async fn client_portal(
.unwrap_or(false);
let client = match query!(Client, $media_token == token).get(&db).await? {
Some(c) => c,
Some(c) if c.status != "deleted" => c,
Some(_) => return Html::new("404").into_response(),
None => return Html::new("404").into_response(),
};
@@ -239,7 +250,11 @@ async fn client_portal(
let today = crate::tz::today_in_tz(tz);
let mut visits = Visit::objects().all(&db).await?;
visits.retain(|v| v.client_id.primary_key().unwrap() == client_id && v.status != "cancelled");
visits.retain(|v| {
v.client_id.primary_key().unwrap() == client_id
&& v.status != "cancelled"
&& v.status != "deleted"
});
visits.sort_by(|a, b| {
a.visit_date
.cmp(&b.visit_date)
@@ -286,6 +301,7 @@ async fn client_portal(
}
past.reverse(); // newest first
let turnstile_site_key = crate::turnstile::get_site_key(&db).await?;
let body = ClientPortalTemplate {
t: lang.t(),
lang,
@@ -293,6 +309,7 @@ async fn client_portal(
upcoming,
past,
feedback_sent,
turnstile_site_key,
}
.render()?;
html_response(body, lang)
@@ -301,6 +318,8 @@ async fn client_portal(
#[derive(Deserialize)]
struct FeedbackForm {
feedback: String,
#[serde(default, rename = "cf-turnstile-response")]
cf_turnstile_response: Option<String>,
}
async fn submit_feedback(
@@ -313,7 +332,8 @@ async fn submit_feedback(
// Verify token matches visit's client
let token_clone = token.clone();
let client = match query!(Client, $media_token == token).get(&db).await? {
Some(c) => c,
Some(c) if c.status != "deleted" => c,
Some(_) => return Html::new("404").into_response(),
None => return Html::new("404").into_response(),
};
let client_id = client.id.unwrap();
@@ -322,7 +342,24 @@ async fn submit_feedback(
let form: FeedbackForm =
serde_html_form::from_bytes(&bytes).map_err(|e| cot::Error::internal(e.to_string()))?;
if !crate::turnstile::verify(&db, form.cf_turnstile_response.as_deref()).await? {
return Redirect::new(format!(
"/client/{}?lang={}",
token_clone,
lang.code()
))
.into_response();
}
if let Some(mut visit) = query!(Visit, $id == visit_id).get(&db).await? {
if visit.status == "deleted" {
return Redirect::new(format!(
"/client/{}?lang={}",
token_clone,
lang.code()
))
.into_response();
}
if visit.client_id.primary_key().unwrap() == client_id {
visit.client_feedback = Some(form.feedback);
visit.updated_at = now_utc();
@@ -346,7 +383,8 @@ async fn portal_media(
) -> cot::Result<Response> {
// Verify token
let client = match query!(Client, $media_token == token).get(&db).await? {
Some(c) => c,
Some(c) if c.status != "deleted" => c,
Some(_) => return Html::new("404").into_response(),
None => return Html::new("404").into_response(),
};
let client_id = client.id.unwrap();
@@ -355,6 +393,13 @@ async fn portal_media(
Some(m) if m.client_id.primary_key().unwrap() == client_id && m.status == "active" => m,
_ => return Html::new("404").into_response(),
};
if let Some(fk) = &media.visit_id {
let visit_id: i64 = fk.primary_key().unwrap();
match query!(Visit, $id == visit_id).get(&db).await? {
Some(v) if v.status != "deleted" => {}
_ => return Html::new("404").into_response(),
}
}
match tokio::fs::read(&media.file_path).await {
Ok(data) => {
+48
View File
@@ -0,0 +1,48 @@
use cot::db::{Database, query};
use crate::models::Setting;
/// Read `turnstile_site_key` from Settings. Returns empty string if not configured.
pub async fn get_site_key(db: &Database) -> cot::Result<String> {
let key = "turnstile_site_key".to_string();
Ok(query!(Setting, $key == key)
.get(db)
.await?
.map(|s| s.value)
.unwrap_or_default())
}
/// Verify a Turnstile token against Cloudflare.
/// Returns `true` if verification succeeds, or if no secret key is configured (passthrough).
pub async fn verify(db: &Database, token: Option<&str>) -> cot::Result<bool> {
let secret_key_name = "turnstile_secret_key".to_string();
let secret_key = query!(Setting, $key == secret_key_name)
.get(db)
.await?
.map(|s| s.value)
.filter(|s| !s.is_empty());
let Some(secret) = secret_key else {
return Ok(true);
};
let token = token.unwrap_or("");
let client = reqwest::Client::new();
let resp = client
.post("https://challenges.cloudflare.com/turnstile/v0/siteverify")
.json(&serde_json::json!({
"secret": secret,
"response": token
}))
.send()
.await;
Ok(match resp {
Ok(r) => r
.json::<serde_json::Value>()
.await
.map(|v| v["success"].as_bool() == Some(true))
.unwrap_or(false),
Err(_) => false,
})
}
+6 -1
View File
@@ -76,11 +76,16 @@
<form method="post" action="/admin/clients/{{ client_id }}/archive">
<button type="submit" class="button is-warning is-outlined is-fullwidth">{{ t.action_archive }}</button>
</form>
{% else %}
{% else if client_status == "archived" %}
<form method="post" action="/admin/clients/{{ client_id }}/activate">
<button type="submit" class="button is-success is-outlined is-fullwidth">{{ t.action_activate }}</button>
</form>
{% endif %}
{% if client_status != "deleted" %}
<form method="post" action="/admin/clients/{{ client_id }}/delete" onsubmit="return confirm('{{ t.clients_delete_confirm }}');" style="margin-top:0.75rem;">
<button type="submit" class="button is-danger is-outlined is-fullwidth">{{ t.clients_delete }}</button>
</form>
{% endif %}
{% endif %}
</div>
{% endblock %}
+12
View File
@@ -6,6 +6,9 @@
<title>{{ t.nav_title }} — {{ t.login_title }}</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@1/css/bulma.min.css">
{% if !turnstile_site_key.is_empty() %}
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
{% endif %}
<style>
:root { color-scheme: light; }
body { background: #f5f5f5; display: flex; align-items: center; justify-content: center; min-height: 100vh; color: #333; }
@@ -32,6 +35,11 @@
{% if let Some(err) = error.as_ref() %}
<div class="notification is-danger is-light">{{ err }}</div>
{% endif %}
{% if auth_sso_enabled %}
<a href="/admin/oidc/start" class="button is-primary is-fullwidth mt-3">{{ t.login_sso_button }}</a>
{% endif %}
{% if auth_password_enabled %}
{% if auth_sso_enabled %}<hr style="margin:1rem 0;">{% endif %}
<form method="post" action="/admin/login/submit">
<div class="field">
<label class="label">{{ t.users_login }}</label>
@@ -41,8 +49,12 @@
<label class="label">{{ t.users_password }}</label>
<div class="control"><input class="input" type="password" name="password" required></div>
</div>
{% if !turnstile_site_key.is_empty() %}
<div class="cf-turnstile" data-sitekey="{{ turnstile_site_key }}" data-theme="light" style="margin-top:0.75rem;"></div>
{% endif %}
<button type="submit" class="button is-primary is-fullwidth mt-3">{{ t.login_button }}</button>
</form>
{% endif %}
</div>
</div>
</body>
+15 -9
View File
@@ -14,15 +14,7 @@
<div class="field">
<label class="label">{{ t.schedule_client }}</label>
<div class="control">
<div class="select is-fullwidth">
<select name="client_id" required>
{% for c in &clients %}
<option value="{{ c.id }}" {% if c.id.unwrap() == visit.client_id.primary_key().unwrap() %}selected{% endif %}>
{{ c.name }}{% if let Some(p) = c.phone.as_deref() %} ({{ p }}){% endif %}
</option>
{% endfor %}
</select>
</div>
<input class="input" type="text" value="{{ client.name }}{% if let Some(p) = client.phone.as_deref() %} ({{ p }}){% endif %}" readonly>
</div>
</div>
@@ -132,6 +124,9 @@
{% if let Some(cap) = m.caption.as_deref() %}
<div class="media-cap">{{ cap }}</div>
{% endif %}
<div class="visit-media-delete">
<button type="submit" form="visit-media-delete-{{ m.id.unwrap() }}" class="button is-small is-danger is-outlined">{{ t.media_delete }}</button>
</div>
</div>
{% endfor %}
</div>
@@ -141,6 +136,9 @@
<button type="submit" class="button is-primary is-fullwidth">{{ t.schedule_save }}</button>
</form>
{% for m in &media %}
<form id="visit-media-delete-{{ m.id.unwrap() }}" method="post" action="/admin/media/{{ m.id }}/delete" onsubmit="return confirm('{{ t.media_delete_confirm }}');"></form>
{% endfor %}
<hr style="margin:1rem 0;">
<form method="post" action="/admin/schedule/{{ visit.id }}/delete" onsubmit="return confirm('{{ t.schedule_delete_confirm }}');">
@@ -254,6 +252,14 @@
overflow: hidden;
text-overflow: ellipsis;
}
.visit-media-delete {
padding: 0.25rem 0.4rem 0.4rem;
}
.visit-media-delete .button {
width: 100%;
font-size: 0.68rem;
min-height: 1.65rem;
}
.upload-modal-bg {
display: none;
position: fixed;
+85 -20
View File
@@ -14,12 +14,8 @@
<div class="form-card">
<form method="post" action="/admin/settings/save">
<div class="field">
<label class="label">{{ t.settings_telegram_bot_token }}</label>
<div class="control">
<input class="input" type="text" name="telegram_bot_token" value="{% for s in &settings %}{% if s.key == "telegram_bot_token" %}{{ s.value }}{% endif %}{% endfor %}">
</div>
</div>
<h2 class="subtitle is-5 mb-3" style="border-bottom:1px solid #eee;padding-bottom:0.5rem;">{{ t.settings_contact_info }}</h2>
<div class="field">
<label class="label">{{ t.settings_contact_info }}</label>
<div class="control">
@@ -32,18 +28,6 @@
<textarea class="input" name="pricing_info" rows="3" style="min-height:70px;resize:vertical;" placeholder="от 600 рублей за визит">{% for s in &settings %}{% if s.key == "pricing_info" %}{{ s.value }}{% endif %}{% endfor %}</textarea>
</div>
</div>
<div class="field">
<label class="label">{{ t.settings_site_domain }}</label>
<div class="control">
<input class="input" type="text" name="site_domain" placeholder="https://example.com" value="{% for s in &settings %}{% if s.key == "site_domain" %}{{ s.value }}{% endif %}{% endfor %}">
</div>
</div>
<div class="field">
<label class="label">{{ t.settings_timezone }}</label>
<div class="control">
<input class="input" type="text" name="timezone" placeholder="Asia/Vladivostok" value="{% for s in &settings %}{% if s.key == "timezone" %}{{ s.value }}{% endif %}{% endfor %}">
</div>
</div>
<div class="field">
<label class="label">{{ t.settings_seo_keywords }}</label>
<div class="control">
@@ -52,10 +36,91 @@
placeholder="зооняня Хабаровск, присмотр за питомцем Хабаровск, догситтер Хабаровск">{% for s in &settings %}{% if s.key == "seo_keywords" %}{{ s.value }}{% endif %}{% endfor %}</textarea>
</div>
<div id="seoPreview" style="margin-top:0.5rem;padding:0.5rem 0.75rem;background:#fafafa;border:1px solid #eee;border-radius:6px;min-height:2rem;line-height:2;font-size:0.85rem;display:none;"></div>
<p style="font-size:0.78rem;color:#aaa;margin-top:0.3rem;">Каждая фраза между запятыми — отдельное ключевое слово</p>
</div>
<button type="submit" class="button is-primary">{{ t.settings_save }}</button>
<details style="margin-top:1.5rem;">
<summary class="subtitle is-5 mb-3" style="cursor:pointer;border-bottom:1px solid #eee;padding-bottom:0.5rem;">
{{ t.settings_section_advanced }}
</summary>
<div style="margin-top:1rem;">
<h3 class="subtitle is-6 mb-2 has-text-grey">{{ t.settings_section_general }}</h3>
<div class="field">
<label class="label">{{ t.settings_site_domain }}</label>
<div class="control">
<input class="input" type="text" name="site_domain" placeholder="https://example.com" value="{% for s in &settings %}{% if s.key == "site_domain" %}{{ s.value }}{% endif %}{% endfor %}">
</div>
</div>
<div class="field">
<label class="label">{{ t.settings_timezone }}</label>
<div class="control">
<input class="input" type="text" name="timezone" placeholder="Asia/Vladivostok" value="{% for s in &settings %}{% if s.key == "timezone" %}{{ s.value }}{% endif %}{% endfor %}">
</div>
</div>
<h3 class="subtitle is-6 mb-2 has-text-grey" style="margin-top:1.25rem;">{{ t.settings_section_notifications }}</h3>
<div class="field">
<label class="label">{{ t.settings_telegram_bot_token }}</label>
<div class="control">
<input class="input" type="text" name="telegram_bot_token" value="{% for s in &settings %}{% if s.key == "telegram_bot_token" %}{{ s.value }}{% endif %}{% endfor %}">
</div>
</div>
<h3 class="subtitle is-6 mb-2 has-text-grey" style="margin-top:1.25rem;">{{ t.settings_section_captcha }}</h3>
<div class="field">
<label class="label">{{ t.settings_turnstile_site_key }}</label>
<div class="control">
<input class="input" type="text" name="turnstile_site_key" value="{% for s in &settings %}{% if s.key == "turnstile_site_key" %}{{ s.value }}{% endif %}{% endfor %}">
</div>
</div>
<div class="field">
<label class="label">{{ t.settings_turnstile_secret_key }}</label>
<div class="control">
<input class="input" type="text" name="turnstile_secret_key" value="{% for s in &settings %}{% if s.key == "turnstile_secret_key" %}{{ s.value }}{% endif %}{% endfor %}">
</div>
</div>
<h3 class="subtitle is-6 mb-2 has-text-grey" style="margin-top:1.25rem;">{{ t.settings_section_oidc }}</h3>
<div class="field">
<label class="label">{{ t.settings_oidc_issuer_url }}</label>
<div class="control">
<input class="input" type="text" name="oidc_issuer_url" placeholder="https://keycloak.example.com/realms/myrealm" value="{% for s in &settings %}{% if s.key == "oidc_issuer_url" %}{{ s.value }}{% endif %}{% endfor %}">
</div>
</div>
<div class="field">
<label class="label">{{ t.settings_oidc_client_id }}</label>
<div class="control">
<input class="input" type="text" name="oidc_client_id" value="{% for s in &settings %}{% if s.key == "oidc_client_id" %}{{ s.value }}{% endif %}{% endfor %}">
</div>
</div>
<div class="field">
<label class="label">{{ t.settings_oidc_client_secret }}</label>
<div class="control">
<input class="input" type="password" name="oidc_client_secret" value="{% for s in &settings %}{% if s.key == "oidc_client_secret" %}{{ s.value }}{% endif %}{% endfor %}">
</div>
</div>
<div class="field">
<label class="label">{{ t.settings_oidc_allowed_groups }}</label>
<div class="control">
<input class="input" type="text" name="oidc_allowed_groups" placeholder="admins, web-petting" value="{% for s in &settings %}{% if s.key == "oidc_allowed_groups" %}{{ s.value }}{% endif %}{% endfor %}">
</div>
</div>
<div class="field">
<label class="checkbox">
<input type="checkbox" name="auth_password_enabled" value="true"{% if auth_password_checked %} checked{% endif %}>
{{ t.settings_auth_password_enabled }}
</label>
</div>
<div class="field">
<label class="checkbox">
<input type="checkbox" name="auth_sso_enabled" value="true"{% if auth_sso_checked %} checked{% endif %}>
{{ t.settings_auth_sso_enabled }}
</label>
</div>
</div>
</details>
<button type="submit" class="button is-primary" style="margin-top:1.5rem;">{{ t.settings_save }}</button>
</form>
</div>
+9
View File
@@ -5,6 +5,9 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ t.portal_title }} — {{ client.name }}</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
{% if !turnstile_site_key.is_empty() %}
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
{% endif %}
<style>
:root { color-scheme: light; }
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
@@ -166,6 +169,9 @@
</div>
<form class="feedback-form" id="fb-form-{{ pv.visit.id }}" style="display:none;" method="post" action="/client/{{ client.media_token }}/{{ pv.visit.id }}/feedback">
<textarea name="feedback" required>{{ fb }}</textarea>
{% if !turnstile_site_key.is_empty() %}
<div class="cf-turnstile" data-sitekey="{{ turnstile_site_key }}" data-theme="light" data-appearance="interaction-only" style="margin-top:0.4rem;"></div>
{% endif %}
<div style="display:flex;gap:0.4rem;">
<button type="submit">{{ t.portal_feedback_submit }}</button>
<button type="button" class="fb-cancel-btn" onclick="hideFbEdit({{ pv.visit.id }})"></button>
@@ -174,6 +180,9 @@
{% else %}
<form class="feedback-form" method="post" action="/client/{{ client.media_token }}/{{ pv.visit.id }}/feedback">
<textarea name="feedback" placeholder="{{ t.portal_feedback_placeholder }}" required></textarea>
{% if !turnstile_site_key.is_empty() %}
<div class="cf-turnstile" data-sitekey="{{ turnstile_site_key }}" data-theme="light" data-appearance="interaction-only" style="margin-top:0.4rem;"></div>
{% endif %}
<button type="submit">{{ t.portal_feedback_submit }}</button>
</form>
{% endif %}
+7
View File
@@ -50,6 +50,10 @@
}
</script>
{% if !turnstile_site_key.is_empty() %}
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
{% endif %}
<style>
/* ── Reset & Base ── */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
@@ -464,6 +468,9 @@
<input type="checkbox" id="consent" name="consent" required style="margin-top:0.2rem;width:auto;flex-shrink:0;">
<label for="consent" style="font-size:0.82rem;font-weight:400;color:#7a7599;cursor:pointer;display:inline;">{{ t.landing_form_consent }}</label>
</div>
{% if !turnstile_site_key.is_empty() %}
<div class="cf-turnstile" data-sitekey="{{ turnstile_site_key }}" data-theme="light" data-size="compact" style="margin-bottom:1.25rem;"></div>
{% endif %}
<button type="submit" class="form-submit">{{ t.landing_form_submit }}</button>
</form>
{% if !contact_info.is_empty() %}